xref: /titanic_44/usr/src/uts/common/inet/ip/ip.c (revision 494f7e12a62129ef191a15f9dfde6b7abe3bf510)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 1990 Mentat Inc.
25  * Copyright (c) 2012 Joyent, Inc. All rights reserved.
26  */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/suntpi.h>
42 #include <sys/cmn_err.h>
43 #include <sys/debug.h>
44 #include <sys/kobj.h>
45 #include <sys/modctl.h>
46 #include <sys/atomic.h>
47 #include <sys/policy.h>
48 #include <sys/priv.h>
49 #include <sys/taskq.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/sdt.h>
55 #include <sys/socket.h>
56 #include <sys/vtrace.h>
57 #include <sys/isa_defs.h>
58 #include <sys/mac.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/optcom.h>
73 #include <inet/kstatcom.h>
74 
75 #include <netinet/igmp_var.h>
76 #include <netinet/ip6.h>
77 #include <netinet/icmp6.h>
78 #include <netinet/sctp.h>
79 
80 #include <inet/ip.h>
81 #include <inet/ip_impl.h>
82 #include <inet/ip6.h>
83 #include <inet/ip6_asp.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/ip_multi.h>
87 #include <inet/ip_if.h>
88 #include <inet/ip_ire.h>
89 #include <inet/ip_ftable.h>
90 #include <inet/ip_rts.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <inet/iptun/iptun_impl.h>
101 #include <inet/ipdrop.h>
102 #include <inet/ip_netinfo.h>
103 #include <inet/ilb_ip.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/pattr.h>
114 #include <inet/ipclassifier.h>
115 #include <inet/sctp_ip.h>
116 #include <inet/sctp/sctp_impl.h>
117 #include <inet/udp_impl.h>
118 #include <inet/rawip_impl.h>
119 #include <inet/rts_impl.h>
120 
121 #include <sys/tsol/label.h>
122 #include <sys/tsol/tnet.h>
123 
124 #include <sys/squeue_impl.h>
125 #include <inet/ip_arp.h>
126 
127 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 
139 /*
140  * Setable in /etc/system
141  */
142 int ip_poll_normal_ms = 100;
143 int ip_poll_normal_ticks = 0;
144 int ip_modclose_ackwait_ms = 3000;
145 
146 /*
147  * It would be nice to have these present only in DEBUG systems, but the
148  * current design of the global symbol checking logic requires them to be
149  * unconditionally present.
150  */
151 uint_t ip_thread_data;			/* TSD key for debug support */
152 krwlock_t ip_thread_rwlock;
153 list_t	ip_thread_list;
154 
155 /*
156  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
157  */
158 
159 struct listptr_s {
160 	mblk_t	*lp_head;	/* pointer to the head of the list */
161 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
162 };
163 
164 typedef struct listptr_s listptr_t;
165 
166 /*
167  * This is used by ip_snmp_get_mib2_ip_route_media and
168  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
169  */
170 typedef struct iproutedata_s {
171 	uint_t		ird_idx;
172 	uint_t		ird_flags;	/* see below */
173 	listptr_t	ird_route;	/* ipRouteEntryTable */
174 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
175 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
176 } iproutedata_t;
177 
178 /* Include ire_testhidden and IRE_IF_CLONE routes */
179 #define	IRD_REPORT_ALL	0x01
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, IPMP operations, most set ioctls, etc.
236  *
237  * Plumbing is a long sequence of operations involving message
238  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
239  * involved in plumbing operations. A natural model is to serialize these
240  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
241  * parallel without any interference. But various set ioctls on hme0 are best
242  * serialized, along with IPMP operations and processing of DLPI control
243  * messages received from drivers on a per phyint basis. This serialization is
244  * provided by the ipsq_t and primitives operating on this. Details can
245  * be found in ip_if.c above the core primitives operating on ipsq_t.
246  *
247  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
248  * Simiarly lookup of an ire by a thread also returns a refheld ire.
249  * In addition ipif's and ill's referenced by the ire are also indirectly
250  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
251  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
252  * address of an ipif has to go through the ipsq_t. This ensures that only
253  * one such exclusive operation proceeds at any time on the ipif. It then
254  * waits for all refcnts
255  * associated with this ipif to come down to zero. The address is changed
256  * only after the ipif has been quiesced. Then the ipif is brought up again.
257  * More details are described above the comment in ip_sioctl_flags.
258  *
259  * Packet processing is based mostly on IREs and are fully multi-threaded
260  * using standard Solaris MT techniques.
261  *
262  * There are explicit locks in IP to handle:
263  * - The ip_g_head list maintained by mi_open_link() and friends.
264  *
265  * - The reassembly data structures (one lock per hash bucket)
266  *
267  * - conn_lock is meant to protect conn_t fields. The fields actually
268  *   protected by conn_lock are documented in the conn_t definition.
269  *
270  * - ire_lock to protect some of the fields of the ire, IRE tables
271  *   (one lock per hash bucket). Refer to ip_ire.c for details.
272  *
273  * - ndp_g_lock and ncec_lock for protecting NCEs.
274  *
275  * - ill_lock protects fields of the ill and ipif. Details in ip.h
276  *
277  * - ill_g_lock: This is a global reader/writer lock. Protects the following
278  *	* The AVL tree based global multi list of all ills.
279  *	* The linked list of all ipifs of an ill
280  *	* The <ipsq-xop> mapping
281  *	* <ill-phyint> association
282  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
283  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
284  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
285  *   writer for the actual duration of the insertion/deletion/change.
286  *
287  * - ill_lock:  This is a per ill mutex.
288  *   It protects some members of the ill_t struct; see ip.h for details.
289  *   It also protects the <ill-phyint> assoc.
290  *   It also protects the list of ipifs hanging off the ill.
291  *
292  * - ipsq_lock: This is a per ipsq_t mutex lock.
293  *   This protects some members of the ipsq_t struct; see ip.h for details.
294  *   It also protects the <ipsq-ipxop> mapping
295  *
296  * - ipx_lock: This is a per ipxop_t mutex lock.
297  *   This protects some members of the ipxop_t struct; see ip.h for details.
298  *
299  * - phyint_lock: This is a per phyint mutex lock. Protects just the
300  *   phyint_flags
301  *
302  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
303  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
304  *   uniqueness check also done atomically.
305  *
306  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
307  *   group list linked by ill_usesrc_grp_next. It also protects the
308  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
309  *   group is being added or deleted.  This lock is taken as a reader when
310  *   walking the list/group(eg: to get the number of members in a usesrc group).
311  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
312  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
313  *   example, it is not necessary to take this lock in the initial portion
314  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
315  *   operations are executed exclusively and that ensures that the "usesrc
316  *   group state" cannot change. The "usesrc group state" change can happen
317  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
318  *
319  * Changing <ill-phyint>, <ipsq-xop> assocications:
320  *
321  * To change the <ill-phyint> association, the ill_g_lock must be held
322  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
323  * must be held.
324  *
325  * To change the <ipsq-xop> association, the ill_g_lock must be held as
326  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
327  * This is only done when ills are added or removed from IPMP groups.
328  *
329  * To add or delete an ipif from the list of ipifs hanging off the ill,
330  * ill_g_lock (writer) and ill_lock must be held and the thread must be
331  * a writer on the associated ipsq.
332  *
333  * To add or delete an ill to the system, the ill_g_lock must be held as
334  * writer and the thread must be a writer on the associated ipsq.
335  *
336  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
337  * must be a writer on the associated ipsq.
338  *
339  * Lock hierarchy
340  *
341  * Some lock hierarchy scenarios are listed below.
342  *
343  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
344  * ill_g_lock -> ill_lock(s) -> phyint_lock
345  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
346  * ill_g_lock -> ip_addr_avail_lock
347  * conn_lock -> irb_lock -> ill_lock -> ire_lock
348  * ill_g_lock -> ip_g_nd_lock
349  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
350  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
351  * arl_lock -> ill_lock
352  * ips_ire_dep_lock -> irb_lock
353  *
354  * When more than 1 ill lock is needed to be held, all ill lock addresses
355  * are sorted on address and locked starting from highest addressed lock
356  * downward.
357  *
358  * Multicast scenarios
359  * ips_ill_g_lock -> ill_mcast_lock
360  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
361  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
362  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
363  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
364  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
365  *
366  * IPsec scenarios
367  *
368  * ipsa_lock -> ill_g_lock -> ill_lock
369  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
370  *
371  * Trusted Solaris scenarios
372  *
373  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
374  * igsa_lock -> gcdb_lock
375  * gcgrp_rwlock -> ire_lock
376  * gcgrp_rwlock -> gcdb_lock
377  *
378  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
379  *
380  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
381  * sq_lock -> conn_lock -> QLOCK(q)
382  * ill_lock -> ft_lock -> fe_lock
383  *
384  * Routing/forwarding table locking notes:
385  *
386  * Lock acquisition order: Radix tree lock, irb_lock.
387  * Requirements:
388  * i.  Walker must not hold any locks during the walker callback.
389  * ii  Walker must not see a truncated tree during the walk because of any node
390  *     deletion.
391  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
392  *     in many places in the code to walk the irb list. Thus even if all the
393  *     ires in a bucket have been deleted, we still can't free the radix node
394  *     until the ires have actually been inactive'd (freed).
395  *
396  * Tree traversal - Need to hold the global tree lock in read mode.
397  * Before dropping the global tree lock, need to either increment the ire_refcnt
398  * to ensure that the radix node can't be deleted.
399  *
400  * Tree add - Need to hold the global tree lock in write mode to add a
401  * radix node. To prevent the node from being deleted, increment the
402  * irb_refcnt, after the node is added to the tree. The ire itself is
403  * added later while holding the irb_lock, but not the tree lock.
404  *
405  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
406  * All associated ires must be inactive (i.e. freed), and irb_refcnt
407  * must be zero.
408  *
409  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
410  * global tree lock (read mode) for traversal.
411  *
412  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
413  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
414  *
415  * IPsec notes :
416  *
417  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
418  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
419  * ip_xmit_attr_t has the
420  * information used by the IPsec code for applying the right level of
421  * protection. The information initialized by IP in the ip_xmit_attr_t
422  * is determined by the per-socket policy or global policy in the system.
423  * For inbound datagrams, the ip_recv_attr_t
424  * starts out with nothing in it. It gets filled
425  * with the right information if it goes through the AH/ESP code, which
426  * happens if the incoming packet is secure. The information initialized
427  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
428  * the policy requirements needed by per-socket policy or global policy
429  * is met or not.
430  *
431  * For fully connected sockets i.e dst, src [addr, port] is known,
432  * conn_policy_cached is set indicating that policy has been cached.
433  * conn_in_enforce_policy may or may not be set depending on whether
434  * there is a global policy match or per-socket policy match.
435  * Policy inheriting happpens in ip_policy_set once the destination is known.
436  * Once the right policy is set on the conn_t, policy cannot change for
437  * this socket. This makes life simpler for TCP (UDP ?) where
438  * re-transmissions go out with the same policy. For symmetry, policy
439  * is cached for fully connected UDP sockets also. Thus if policy is cached,
440  * it also implies that policy is latched i.e policy cannot change
441  * on these sockets. As we have the right policy on the conn, we don't
442  * have to lookup global policy for every outbound and inbound datagram
443  * and thus serving as an optimization. Note that a global policy change
444  * does not affect fully connected sockets if they have policy. If fully
445  * connected sockets did not have any policy associated with it, global
446  * policy change may affect them.
447  *
448  * IP Flow control notes:
449  * ---------------------
450  * Non-TCP streams are flow controlled by IP. The way this is accomplished
451  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
452  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
453  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
454  * functions.
455  *
456  * Per Tx ring udp flow control:
457  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
458  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
459  *
460  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
461  * To achieve best performance, outgoing traffic need to be fanned out among
462  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
463  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
464  * the address of connp as fanout hint to mac_tx(). Under flow controlled
465  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
466  * cookie points to a specific Tx ring that is blocked. The cookie is used to
467  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
468  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
469  * connp's. The drain list is not a single list but a configurable number of
470  * lists.
471  *
472  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
473  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
474  * which is equal to 128. This array in turn contains a pointer to idl_t[],
475  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
476  * list will point to the list of connp's that are flow controlled.
477  *
478  *                      ---------------   -------   -------   -------
479  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
480  *                   |  ---------------   -------   -------   -------
481  *                   |  ---------------   -------   -------   -------
482  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
483  * ----------------  |  ---------------   -------   -------   -------
484  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
485  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
486  *                   |  ---------------   -------   -------   -------
487  *                   .        .              .         .         .
488  *                   |  ---------------   -------   -------   -------
489  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
490  *                      ---------------   -------   -------   -------
491  *                      ---------------   -------   -------   -------
492  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
493  *                   |  ---------------   -------   -------   -------
494  *                   |  ---------------   -------   -------   -------
495  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
496  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
497  * ----------------  |        .              .         .         .
498  *                   |  ---------------   -------   -------   -------
499  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
500  *                      ---------------   -------   -------   -------
501  *     .....
502  * ----------------
503  * |idl_tx_list[n]|-> ...
504  * ----------------
505  *
506  * When mac_tx() returns a cookie, the cookie is hashed into an index into
507  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
508  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
509  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
510  * Further, conn_blocked is set to indicate that the conn is blocked.
511  *
512  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
513  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
514  * is again hashed to locate the appropriate idl_tx_list, which is then
515  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
516  * the drain list and calls conn_drain_remove() to clear flow control (via
517  * calling su_txq_full() or clearing QFULL), and remove the conn from the
518  * drain list.
519  *
520  * Note that the drain list is not a single list but a (configurable) array of
521  * lists (8 elements by default).  Synchronization between drain insertion and
522  * flow control wakeup is handled by using idl_txl->txl_lock, and only
523  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
524  *
525  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
526  * On the send side, if the packet cannot be sent down to the driver by IP
527  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
528  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
529  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
530  * control has been relieved, the blocked conns in the 0'th drain list are
531  * drained as in the non-STREAMS case.
532  *
533  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
534  * is done when the conn is inserted into the drain list (conn_drain_insert())
535  * and cleared when the conn is removed from the it (conn_drain_remove()).
536  *
537  * IPQOS notes:
538  *
539  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
540  * and IPQoS modules. IPPF includes hooks in IP at different control points
541  * (callout positions) which direct packets to IPQoS modules for policy
542  * processing. Policies, if present, are global.
543  *
544  * The callout positions are located in the following paths:
545  *		o local_in (packets destined for this host)
546  *		o local_out (packets orginating from this host )
547  *		o fwd_in  (packets forwarded by this m/c - inbound)
548  *		o fwd_out (packets forwarded by this m/c - outbound)
549  * Hooks at these callout points can be enabled/disabled using the ndd variable
550  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
551  * By default all the callout positions are enabled.
552  *
553  * Outbound (local_out)
554  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
555  *
556  * Inbound (local_in)
557  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
558  *
559  * Forwarding (in and out)
560  * Hooks are placed in ire_recv_forward_v4/v6.
561  *
562  * IP Policy Framework processing (IPPF processing)
563  * Policy processing for a packet is initiated by ip_process, which ascertains
564  * that the classifier (ipgpc) is loaded and configured, failing which the
565  * packet resumes normal processing in IP. If the clasifier is present, the
566  * packet is acted upon by one or more IPQoS modules (action instances), per
567  * filters configured in ipgpc and resumes normal IP processing thereafter.
568  * An action instance can drop a packet in course of its processing.
569  *
570  * Zones notes:
571  *
572  * The partitioning rules for networking are as follows:
573  * 1) Packets coming from a zone must have a source address belonging to that
574  * zone.
575  * 2) Packets coming from a zone can only be sent on a physical interface on
576  * which the zone has an IP address.
577  * 3) Between two zones on the same machine, packet delivery is only allowed if
578  * there's a matching route for the destination and zone in the forwarding
579  * table.
580  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
581  * different zones can bind to the same port with the wildcard address
582  * (INADDR_ANY).
583  *
584  * The granularity of interface partitioning is at the logical interface level.
585  * Therefore, every zone has its own IP addresses, and incoming packets can be
586  * attributed to a zone unambiguously. A logical interface is placed into a zone
587  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
588  * structure. Rule (1) is implemented by modifying the source address selection
589  * algorithm so that the list of eligible addresses is filtered based on the
590  * sending process zone.
591  *
592  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
593  * across all zones, depending on their type. Here is the break-up:
594  *
595  * IRE type				Shared/exclusive
596  * --------				----------------
597  * IRE_BROADCAST			Exclusive
598  * IRE_DEFAULT (default routes)		Shared (*)
599  * IRE_LOCAL				Exclusive (x)
600  * IRE_LOOPBACK				Exclusive
601  * IRE_PREFIX (net routes)		Shared (*)
602  * IRE_IF_NORESOLVER (interface routes)	Exclusive
603  * IRE_IF_RESOLVER (interface routes)	Exclusive
604  * IRE_IF_CLONE (interface routes)	Exclusive
605  * IRE_HOST (host routes)		Shared (*)
606  *
607  * (*) A zone can only use a default or off-subnet route if the gateway is
608  * directly reachable from the zone, that is, if the gateway's address matches
609  * one of the zone's logical interfaces.
610  *
611  * (x) IRE_LOCAL are handled a bit differently.
612  * When ip_restrict_interzone_loopback is set (the default),
613  * ire_route_recursive restricts loopback using an IRE_LOCAL
614  * between zone to the case when L2 would have conceptually looped the packet
615  * back, i.e. the loopback which is required since neither Ethernet drivers
616  * nor Ethernet hardware loops them back. This is the case when the normal
617  * routes (ignoring IREs with different zoneids) would send out the packet on
618  * the same ill as the ill with which is IRE_LOCAL is associated.
619  *
620  * Multiple zones can share a common broadcast address; typically all zones
621  * share the 255.255.255.255 address. Incoming as well as locally originated
622  * broadcast packets must be dispatched to all the zones on the broadcast
623  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
624  * since some zones may not be on the 10.16.72/24 network. To handle this, each
625  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
626  * sent to every zone that has an IRE_BROADCAST entry for the destination
627  * address on the input ill, see ip_input_broadcast().
628  *
629  * Applications in different zones can join the same multicast group address.
630  * The same logic applies for multicast as for broadcast. ip_input_multicast
631  * dispatches packets to all zones that have members on the physical interface.
632  */
633 
634 /*
635  * Squeue Fanout flags:
636  *	0: No fanout.
637  *	1: Fanout across all squeues
638  */
639 boolean_t	ip_squeue_fanout = 0;
640 
641 /*
642  * Maximum dups allowed per packet.
643  */
644 uint_t ip_max_frag_dups = 10;
645 
646 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
647 		    cred_t *credp, boolean_t isv6);
648 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
649 
650 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
651 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
652 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
653     ip_recv_attr_t *);
654 static void	icmp_options_update(ipha_t *);
655 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
656 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
657 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
658 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
659     ip_recv_attr_t *);
660 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
661 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
662     ip_recv_attr_t *);
663 
664 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
665 char		*ip_dot_addr(ipaddr_t, char *);
666 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
667 int		ip_close(queue_t *, int);
668 static char	*ip_dot_saddr(uchar_t *, char *);
669 static void	ip_lrput(queue_t *, mblk_t *);
670 ipaddr_t	ip_net_mask(ipaddr_t);
671 char		*ip_nv_lookup(nv_t *, int);
672 void	ip_rput(queue_t *, mblk_t *);
673 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
674 		    void *dummy_arg);
675 int		ip_snmp_get(queue_t *, mblk_t *, int, boolean_t);
676 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
677 		    mib2_ipIfStatsEntry_t *, ip_stack_t *, boolean_t);
678 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
679 		    ip_stack_t *, boolean_t);
680 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *,
681 		    boolean_t);
682 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst, boolean_t);
688 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst, boolean_t);
690 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
703 		    ip_stack_t *ipst);
704 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
705 		    ip_stack_t *ipst);
706 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
707 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
708 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
709 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
710 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
711 
712 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
713 		    mblk_t *);
714 
715 static void	conn_drain_init(ip_stack_t *);
716 static void	conn_drain_fini(ip_stack_t *);
717 static void	conn_drain(conn_t *connp, boolean_t closing);
718 
719 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
720 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
721 
722 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
723 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
724 static void	ip_stack_fini(netstackid_t stackid, void *arg);
725 
726 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
727     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
728     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
729     const in6_addr_t *);
730 
731 static int	ip_squeue_switch(int);
732 
733 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
734 static void	ip_kstat_fini(netstackid_t, kstat_t *);
735 static int	ip_kstat_update(kstat_t *kp, int rw);
736 static void	*icmp_kstat_init(netstackid_t);
737 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
738 static int	icmp_kstat_update(kstat_t *kp, int rw);
739 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
740 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
741 
742 static void	ipobs_init(ip_stack_t *);
743 static void	ipobs_fini(ip_stack_t *);
744 
745 static int	ip_tp_cpu_update(cpu_setup_t, int, void *);
746 
747 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
748 
749 static long ip_rput_pullups;
750 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
751 
752 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
753 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
754 
755 int	ip_debug;
756 
757 /*
758  * Multirouting/CGTP stuff
759  */
760 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
761 
762 /*
763  * IP tunables related declarations. Definitions are in ip_tunables.c
764  */
765 extern mod_prop_info_t ip_propinfo_tbl[];
766 extern int ip_propinfo_count;
767 
768 /*
769  * Table of IP ioctls encoding the various properties of the ioctl and
770  * indexed based on the last byte of the ioctl command. Occasionally there
771  * is a clash, and there is more than 1 ioctl with the same last byte.
772  * In such a case 1 ioctl is encoded in the ndx table and the remaining
773  * ioctls are encoded in the misc table. An entry in the ndx table is
774  * retrieved by indexing on the last byte of the ioctl command and comparing
775  * the ioctl command with the value in the ndx table. In the event of a
776  * mismatch the misc table is then searched sequentially for the desired
777  * ioctl command.
778  *
779  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
780  */
781 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
782 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
783 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
784 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
785 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
786 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
787 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
788 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
789 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
790 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
791 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
792 
793 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
794 			MISC_CMD, ip_siocaddrt, NULL },
795 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
796 			MISC_CMD, ip_siocdelrt, NULL },
797 
798 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
799 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
800 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
801 			IF_CMD, ip_sioctl_get_addr, NULL },
802 
803 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
804 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
805 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
806 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
807 
808 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
809 			IPI_PRIV | IPI_WR,
810 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
811 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
812 			IPI_MODOK | IPI_GET_CMD,
813 			IF_CMD, ip_sioctl_get_flags, NULL },
814 
815 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
816 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
817 
818 	/* copyin size cannot be coded for SIOCGIFCONF */
819 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
820 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
821 
822 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
823 			IF_CMD, ip_sioctl_mtu, NULL },
824 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
825 			IF_CMD, ip_sioctl_get_mtu, NULL },
826 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
827 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
828 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
829 			IF_CMD, ip_sioctl_brdaddr, NULL },
830 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
831 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
832 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
833 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
834 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
835 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
836 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
837 			IF_CMD, ip_sioctl_metric, NULL },
838 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
839 
840 	/* See 166-168 below for extended SIOC*XARP ioctls */
841 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
842 			ARP_CMD, ip_sioctl_arp, NULL },
843 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
844 			ARP_CMD, ip_sioctl_arp, NULL },
845 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
846 			ARP_CMD, ip_sioctl_arp, NULL },
847 
848 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
849 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
850 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
851 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
852 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
853 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
854 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
855 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
856 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
857 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
858 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
859 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
860 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
861 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
862 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
863 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
864 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
865 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
866 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
867 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
868 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
869 
870 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
871 			MISC_CMD, if_unitsel, if_unitsel_restart },
872 
873 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
874 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
875 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
876 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
877 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
878 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
879 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
880 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
881 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
882 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
883 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
884 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
885 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
886 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
887 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
888 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
889 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
890 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
891 
892 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
893 			IPI_PRIV | IPI_WR | IPI_MODOK,
894 			IF_CMD, ip_sioctl_sifname, NULL },
895 
896 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
897 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
898 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
899 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
900 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
901 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
902 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
903 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
904 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
905 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
906 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
907 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
908 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
909 
910 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
911 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
912 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
913 			IF_CMD, ip_sioctl_get_muxid, NULL },
914 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
915 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
916 
917 	/* Both if and lif variants share same func */
918 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
919 			IF_CMD, ip_sioctl_get_lifindex, NULL },
920 	/* Both if and lif variants share same func */
921 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
922 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
923 
924 	/* copyin size cannot be coded for SIOCGIFCONF */
925 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
926 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
927 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
928 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
929 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
930 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
931 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
932 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
933 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
934 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
935 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
936 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
937 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
938 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
939 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
940 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
941 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
942 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
943 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
944 
945 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
946 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
947 			ip_sioctl_removeif_restart },
948 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
949 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
950 			LIF_CMD, ip_sioctl_addif, NULL },
951 #define	SIOCLIFADDR_NDX 112
952 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
953 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
954 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
955 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
956 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
957 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
958 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
959 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
960 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
961 			IPI_PRIV | IPI_WR,
962 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
963 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
964 			IPI_GET_CMD | IPI_MODOK,
965 			LIF_CMD, ip_sioctl_get_flags, NULL },
966 
967 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
968 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
969 
970 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
971 			ip_sioctl_get_lifconf, NULL },
972 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
973 			LIF_CMD, ip_sioctl_mtu, NULL },
974 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
975 			LIF_CMD, ip_sioctl_get_mtu, NULL },
976 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
977 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
978 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
979 			LIF_CMD, ip_sioctl_brdaddr, NULL },
980 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
981 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
982 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
983 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
984 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
985 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
986 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
987 			LIF_CMD, ip_sioctl_metric, NULL },
988 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
989 			IPI_PRIV | IPI_WR | IPI_MODOK,
990 			LIF_CMD, ip_sioctl_slifname,
991 			ip_sioctl_slifname_restart },
992 
993 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
994 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
995 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
996 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
997 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
998 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
999 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1000 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1001 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1002 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1003 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1004 			LIF_CMD, ip_sioctl_token, NULL },
1005 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1006 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1007 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1008 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1009 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1010 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1011 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1012 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1013 
1014 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1015 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1016 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1017 			LIF_CMD, ip_siocdelndp_v6, NULL },
1018 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1019 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1020 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1021 			LIF_CMD, ip_siocsetndp_v6, NULL },
1022 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1023 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1024 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1025 			MISC_CMD, ip_sioctl_tonlink, NULL },
1026 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1027 			MISC_CMD, ip_sioctl_tmysite, NULL },
1028 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1031 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1032 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1033 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1034 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1035 
1036 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 
1038 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1039 			LIF_CMD, ip_sioctl_get_binding, NULL },
1040 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1041 			IPI_PRIV | IPI_WR,
1042 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1043 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1044 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1045 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1046 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1047 
1048 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1049 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 
1053 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 
1055 	/* These are handled in ip_sioctl_copyin_setup itself */
1056 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1057 			MISC_CMD, NULL, NULL },
1058 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1059 			MISC_CMD, NULL, NULL },
1060 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1061 
1062 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1063 			ip_sioctl_get_lifconf, NULL },
1064 
1065 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1066 			XARP_CMD, ip_sioctl_arp, NULL },
1067 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1068 			XARP_CMD, ip_sioctl_arp, NULL },
1069 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1070 			XARP_CMD, ip_sioctl_arp, NULL },
1071 
1072 	/* SIOCPOPSOCKFS is not handled by IP */
1073 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1074 
1075 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1076 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1077 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1078 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1079 			ip_sioctl_slifzone_restart },
1080 	/* 172-174 are SCTP ioctls and not handled by IP */
1081 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1085 			IPI_GET_CMD, LIF_CMD,
1086 			ip_sioctl_get_lifusesrc, 0 },
1087 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1088 			IPI_PRIV | IPI_WR,
1089 			LIF_CMD, ip_sioctl_slifusesrc,
1090 			NULL },
1091 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1092 			ip_sioctl_get_lifsrcof, NULL },
1093 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1094 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1095 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1096 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1097 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1098 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1099 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1100 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1101 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* SIOCSENABLESDP is handled by SDP */
1103 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1104 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1105 	/* 185 */ { SIOCGIFHWADDR, sizeof (struct ifreq), IPI_GET_CMD,
1106 			IF_CMD, ip_sioctl_get_ifhwaddr, NULL },
1107 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1108 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1109 			ip_sioctl_ilb_cmd, NULL },
1110 	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1111 	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1112 	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1113 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1114 	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1115 			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart },
1116 	/* 192 */ { SIOCGLIFHWADDR, sizeof (struct lifreq), IPI_GET_CMD,
1117 			LIF_CMD, ip_sioctl_get_lifhwaddr, NULL }
1118 };
1119 
1120 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1121 
1122 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1123 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1124 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1125 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1126 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1127 	{ ND_GET,	0, 0, 0, NULL, NULL },
1128 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1129 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1130 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1131 		MISC_CMD, mrt_ioctl},
1132 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1133 		MISC_CMD, mrt_ioctl},
1134 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1135 		MISC_CMD, mrt_ioctl}
1136 };
1137 
1138 int ip_misc_ioctl_count =
1139     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1140 
1141 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1142 					/* Settable in /etc/system */
1143 /* Defined in ip_ire.c */
1144 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1145 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1146 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1147 
1148 static nv_t	ire_nv_arr[] = {
1149 	{ IRE_BROADCAST, "BROADCAST" },
1150 	{ IRE_LOCAL, "LOCAL" },
1151 	{ IRE_LOOPBACK, "LOOPBACK" },
1152 	{ IRE_DEFAULT, "DEFAULT" },
1153 	{ IRE_PREFIX, "PREFIX" },
1154 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1155 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1156 	{ IRE_IF_CLONE, "IF_CLONE" },
1157 	{ IRE_HOST, "HOST" },
1158 	{ IRE_MULTICAST, "MULTICAST" },
1159 	{ IRE_NOROUTE, "NOROUTE" },
1160 	{ 0 }
1161 };
1162 
1163 nv_t	*ire_nv_tbl = ire_nv_arr;
1164 
1165 /* Simple ICMP IP Header Template */
1166 static ipha_t icmp_ipha = {
1167 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1168 };
1169 
1170 struct module_info ip_mod_info = {
1171 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1172 	IP_MOD_LOWAT
1173 };
1174 
1175 /*
1176  * Duplicate static symbols within a module confuses mdb; so we avoid the
1177  * problem by making the symbols here distinct from those in udp.c.
1178  */
1179 
1180 /*
1181  * Entry points for IP as a device and as a module.
1182  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1183  */
1184 static struct qinit iprinitv4 = {
1185 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1186 	&ip_mod_info
1187 };
1188 
1189 struct qinit iprinitv6 = {
1190 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1191 	&ip_mod_info
1192 };
1193 
1194 static struct qinit ipwinit = {
1195 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1196 	&ip_mod_info
1197 };
1198 
1199 static struct qinit iplrinit = {
1200 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1201 	&ip_mod_info
1202 };
1203 
1204 static struct qinit iplwinit = {
1205 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1206 	&ip_mod_info
1207 };
1208 
1209 /* For AF_INET aka /dev/ip */
1210 struct streamtab ipinfov4 = {
1211 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1212 };
1213 
1214 /* For AF_INET6 aka /dev/ip6 */
1215 struct streamtab ipinfov6 = {
1216 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1217 };
1218 
1219 #ifdef	DEBUG
1220 boolean_t skip_sctp_cksum = B_FALSE;
1221 #endif
1222 
1223 /*
1224  * Generate an ICMP fragmentation needed message.
1225  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1226  * constructed by the caller.
1227  */
1228 void
1229 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1230 {
1231 	icmph_t	icmph;
1232 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1233 
1234 	mp = icmp_pkt_err_ok(mp, ira);
1235 	if (mp == NULL)
1236 		return;
1237 
1238 	bzero(&icmph, sizeof (icmph_t));
1239 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1240 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1241 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1242 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1243 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1244 
1245 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1246 }
1247 
1248 /*
1249  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1250  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1251  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1252  * Likewise, if the ICMP error is misformed (too short, etc), then it
1253  * returns NULL. The caller uses this to determine whether or not to send
1254  * to raw sockets.
1255  *
1256  * All error messages are passed to the matching transport stream.
1257  *
1258  * The following cases are handled by icmp_inbound:
1259  * 1) It needs to send a reply back and possibly delivering it
1260  *    to the "interested" upper clients.
1261  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1262  * 3) It needs to change some values in IP only.
1263  * 4) It needs to change some values in IP and upper layers e.g TCP
1264  *    by delivering an error to the upper layers.
1265  *
1266  * We handle the above three cases in the context of IPsec in the
1267  * following way :
1268  *
1269  * 1) Send the reply back in the same way as the request came in.
1270  *    If it came in encrypted, it goes out encrypted. If it came in
1271  *    clear, it goes out in clear. Thus, this will prevent chosen
1272  *    plain text attack.
1273  * 2) The client may or may not expect things to come in secure.
1274  *    If it comes in secure, the policy constraints are checked
1275  *    before delivering it to the upper layers. If it comes in
1276  *    clear, ipsec_inbound_accept_clear will decide whether to
1277  *    accept this in clear or not. In both the cases, if the returned
1278  *    message (IP header + 8 bytes) that caused the icmp message has
1279  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1280  *    sending up. If there are only 8 bytes of returned message, then
1281  *    upper client will not be notified.
1282  * 3) Check with global policy to see whether it matches the constaints.
1283  *    But this will be done only if icmp_accept_messages_in_clear is
1284  *    zero.
1285  * 4) If we need to change both in IP and ULP, then the decision taken
1286  *    while affecting the values in IP and while delivering up to TCP
1287  *    should be the same.
1288  *
1289  * 	There are two cases.
1290  *
1291  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1292  *	   failed), we will not deliver it to the ULP, even though they
1293  *	   are *willing* to accept in *clear*. This is fine as our global
1294  *	   disposition to icmp messages asks us reject the datagram.
1295  *
1296  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1297  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1298  *	   to deliver it to ULP (policy failed), it can lead to
1299  *	   consistency problems. The cases known at this time are
1300  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1301  *	   values :
1302  *
1303  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1304  *	     and Upper layer rejects. Then the communication will
1305  *	     come to a stop. This is solved by making similar decisions
1306  *	     at both levels. Currently, when we are unable to deliver
1307  *	     to the Upper Layer (due to policy failures) while IP has
1308  *	     adjusted dce_pmtu, the next outbound datagram would
1309  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1310  *	     will be with the right level of protection. Thus the right
1311  *	     value will be communicated even if we are not able to
1312  *	     communicate when we get from the wire initially. But this
1313  *	     assumes there would be at least one outbound datagram after
1314  *	     IP has adjusted its dce_pmtu value. To make things
1315  *	     simpler, we accept in clear after the validation of
1316  *	     AH/ESP headers.
1317  *
1318  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1319  *	     upper layer depending on the level of protection the upper
1320  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1321  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1322  *	     should be accepted in clear when the Upper layer expects secure.
1323  *	     Thus the communication may get aborted by some bad ICMP
1324  *	     packets.
1325  */
1326 mblk_t *
1327 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1328 {
1329 	icmph_t		*icmph;
1330 	ipha_t		*ipha;		/* Outer header */
1331 	int		ip_hdr_length;	/* Outer header length */
1332 	boolean_t	interested;
1333 	ipif_t		*ipif;
1334 	uint32_t	ts;
1335 	uint32_t	*tsp;
1336 	timestruc_t	now;
1337 	ill_t		*ill = ira->ira_ill;
1338 	ip_stack_t	*ipst = ill->ill_ipst;
1339 	zoneid_t	zoneid = ira->ira_zoneid;
1340 	int		len_needed;
1341 	mblk_t		*mp_ret = NULL;
1342 
1343 	ipha = (ipha_t *)mp->b_rptr;
1344 
1345 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1346 
1347 	ip_hdr_length = ira->ira_ip_hdr_length;
1348 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1349 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1350 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1351 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1352 			freemsg(mp);
1353 			return (NULL);
1354 		}
1355 		/* Last chance to get real. */
1356 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1357 		if (ipha == NULL) {
1358 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1359 			freemsg(mp);
1360 			return (NULL);
1361 		}
1362 	}
1363 
1364 	/* The IP header will always be a multiple of four bytes */
1365 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1366 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1367 	    icmph->icmph_code));
1368 
1369 	/*
1370 	 * We will set "interested" to "true" if we should pass a copy to
1371 	 * the transport or if we handle the packet locally.
1372 	 */
1373 	interested = B_FALSE;
1374 	switch (icmph->icmph_type) {
1375 	case ICMP_ECHO_REPLY:
1376 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1377 		break;
1378 	case ICMP_DEST_UNREACHABLE:
1379 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1380 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1381 		interested = B_TRUE;	/* Pass up to transport */
1382 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1383 		break;
1384 	case ICMP_SOURCE_QUENCH:
1385 		interested = B_TRUE;	/* Pass up to transport */
1386 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1387 		break;
1388 	case ICMP_REDIRECT:
1389 		if (!ipst->ips_ip_ignore_redirect)
1390 			interested = B_TRUE;
1391 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1392 		break;
1393 	case ICMP_ECHO_REQUEST:
1394 		/*
1395 		 * Whether to respond to echo requests that come in as IP
1396 		 * broadcasts or as IP multicast is subject to debate
1397 		 * (what isn't?).  We aim to please, you pick it.
1398 		 * Default is do it.
1399 		 */
1400 		if (ira->ira_flags & IRAF_MULTICAST) {
1401 			/* multicast: respond based on tunable */
1402 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1403 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1404 			/* broadcast: respond based on tunable */
1405 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1406 		} else {
1407 			/* unicast: always respond */
1408 			interested = B_TRUE;
1409 		}
1410 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1411 		if (!interested) {
1412 			/* We never pass these to RAW sockets */
1413 			freemsg(mp);
1414 			return (NULL);
1415 		}
1416 
1417 		/* Check db_ref to make sure we can modify the packet. */
1418 		if (mp->b_datap->db_ref > 1) {
1419 			mblk_t	*mp1;
1420 
1421 			mp1 = copymsg(mp);
1422 			freemsg(mp);
1423 			if (!mp1) {
1424 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1425 				return (NULL);
1426 			}
1427 			mp = mp1;
1428 			ipha = (ipha_t *)mp->b_rptr;
1429 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1430 		}
1431 		icmph->icmph_type = ICMP_ECHO_REPLY;
1432 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1433 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1434 		return (NULL);
1435 
1436 	case ICMP_ROUTER_ADVERTISEMENT:
1437 	case ICMP_ROUTER_SOLICITATION:
1438 		break;
1439 	case ICMP_TIME_EXCEEDED:
1440 		interested = B_TRUE;	/* Pass up to transport */
1441 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1442 		break;
1443 	case ICMP_PARAM_PROBLEM:
1444 		interested = B_TRUE;	/* Pass up to transport */
1445 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1446 		break;
1447 	case ICMP_TIME_STAMP_REQUEST:
1448 		/* Response to Time Stamp Requests is local policy. */
1449 		if (ipst->ips_ip_g_resp_to_timestamp) {
1450 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1451 				interested =
1452 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1453 			else
1454 				interested = B_TRUE;
1455 		}
1456 		if (!interested) {
1457 			/* We never pass these to RAW sockets */
1458 			freemsg(mp);
1459 			return (NULL);
1460 		}
1461 
1462 		/* Make sure we have enough of the packet */
1463 		len_needed = ip_hdr_length + ICMPH_SIZE +
1464 		    3 * sizeof (uint32_t);
1465 
1466 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1467 			ipha = ip_pullup(mp, len_needed, ira);
1468 			if (ipha == NULL) {
1469 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1470 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1471 				    mp, ill);
1472 				freemsg(mp);
1473 				return (NULL);
1474 			}
1475 			/* Refresh following the pullup. */
1476 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1477 		}
1478 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1479 		/* Check db_ref to make sure we can modify the packet. */
1480 		if (mp->b_datap->db_ref > 1) {
1481 			mblk_t	*mp1;
1482 
1483 			mp1 = copymsg(mp);
1484 			freemsg(mp);
1485 			if (!mp1) {
1486 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1487 				return (NULL);
1488 			}
1489 			mp = mp1;
1490 			ipha = (ipha_t *)mp->b_rptr;
1491 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1492 		}
1493 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1494 		tsp = (uint32_t *)&icmph[1];
1495 		tsp++;		/* Skip past 'originate time' */
1496 		/* Compute # of milliseconds since midnight */
1497 		gethrestime(&now);
1498 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1499 		    now.tv_nsec / (NANOSEC / MILLISEC);
1500 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1501 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1502 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1503 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1504 		return (NULL);
1505 
1506 	case ICMP_TIME_STAMP_REPLY:
1507 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1508 		break;
1509 	case ICMP_INFO_REQUEST:
1510 		/* Per RFC 1122 3.2.2.7, ignore this. */
1511 	case ICMP_INFO_REPLY:
1512 		break;
1513 	case ICMP_ADDRESS_MASK_REQUEST:
1514 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1515 			interested =
1516 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1517 		} else {
1518 			interested = B_TRUE;
1519 		}
1520 		if (!interested) {
1521 			/* We never pass these to RAW sockets */
1522 			freemsg(mp);
1523 			return (NULL);
1524 		}
1525 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1526 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1527 			ipha = ip_pullup(mp, len_needed, ira);
1528 			if (ipha == NULL) {
1529 				BUMP_MIB(ill->ill_ip_mib,
1530 				    ipIfStatsInTruncatedPkts);
1531 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1532 				    ill);
1533 				freemsg(mp);
1534 				return (NULL);
1535 			}
1536 			/* Refresh following the pullup. */
1537 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1538 		}
1539 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1540 		/* Check db_ref to make sure we can modify the packet. */
1541 		if (mp->b_datap->db_ref > 1) {
1542 			mblk_t	*mp1;
1543 
1544 			mp1 = copymsg(mp);
1545 			freemsg(mp);
1546 			if (!mp1) {
1547 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1548 				return (NULL);
1549 			}
1550 			mp = mp1;
1551 			ipha = (ipha_t *)mp->b_rptr;
1552 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1553 		}
1554 		/*
1555 		 * Need the ipif with the mask be the same as the source
1556 		 * address of the mask reply. For unicast we have a specific
1557 		 * ipif. For multicast/broadcast we only handle onlink
1558 		 * senders, and use the source address to pick an ipif.
1559 		 */
1560 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1561 		if (ipif == NULL) {
1562 			/* Broadcast or multicast */
1563 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1564 			if (ipif == NULL) {
1565 				freemsg(mp);
1566 				return (NULL);
1567 			}
1568 		}
1569 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1570 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1571 		ipif_refrele(ipif);
1572 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1573 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1574 		return (NULL);
1575 
1576 	case ICMP_ADDRESS_MASK_REPLY:
1577 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1578 		break;
1579 	default:
1580 		interested = B_TRUE;	/* Pass up to transport */
1581 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1582 		break;
1583 	}
1584 	/*
1585 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1586 	 * if there isn't one.
1587 	 */
1588 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1589 		/* If there is an ICMP client and we want one too, copy it. */
1590 
1591 		if (!interested) {
1592 			/* Caller will deliver to RAW sockets */
1593 			return (mp);
1594 		}
1595 		mp_ret = copymsg(mp);
1596 		if (mp_ret == NULL) {
1597 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1598 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1599 		}
1600 	} else if (!interested) {
1601 		/* Neither we nor raw sockets are interested. Drop packet now */
1602 		freemsg(mp);
1603 		return (NULL);
1604 	}
1605 
1606 	/*
1607 	 * ICMP error or redirect packet. Make sure we have enough of
1608 	 * the header and that db_ref == 1 since we might end up modifying
1609 	 * the packet.
1610 	 */
1611 	if (mp->b_cont != NULL) {
1612 		if (ip_pullup(mp, -1, ira) == NULL) {
1613 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1614 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1615 			    mp, ill);
1616 			freemsg(mp);
1617 			return (mp_ret);
1618 		}
1619 	}
1620 
1621 	if (mp->b_datap->db_ref > 1) {
1622 		mblk_t	*mp1;
1623 
1624 		mp1 = copymsg(mp);
1625 		if (mp1 == NULL) {
1626 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1627 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1628 			freemsg(mp);
1629 			return (mp_ret);
1630 		}
1631 		freemsg(mp);
1632 		mp = mp1;
1633 	}
1634 
1635 	/*
1636 	 * In case mp has changed, verify the message before any further
1637 	 * processes.
1638 	 */
1639 	ipha = (ipha_t *)mp->b_rptr;
1640 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1641 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1642 		freemsg(mp);
1643 		return (mp_ret);
1644 	}
1645 
1646 	switch (icmph->icmph_type) {
1647 	case ICMP_REDIRECT:
1648 		icmp_redirect_v4(mp, ipha, icmph, ira);
1649 		break;
1650 	case ICMP_DEST_UNREACHABLE:
1651 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1652 			/* Update DCE and adjust MTU is icmp header if needed */
1653 			icmp_inbound_too_big_v4(icmph, ira);
1654 		}
1655 		/* FALLTHRU */
1656 	default:
1657 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1658 		break;
1659 	}
1660 	return (mp_ret);
1661 }
1662 
1663 /*
1664  * Send an ICMP echo, timestamp or address mask reply.
1665  * The caller has already updated the payload part of the packet.
1666  * We handle the ICMP checksum, IP source address selection and feed
1667  * the packet into ip_output_simple.
1668  */
1669 static void
1670 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1671     ip_recv_attr_t *ira)
1672 {
1673 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1674 	ill_t		*ill = ira->ira_ill;
1675 	ip_stack_t	*ipst = ill->ill_ipst;
1676 	ip_xmit_attr_t	ixas;
1677 
1678 	/* Send out an ICMP packet */
1679 	icmph->icmph_checksum = 0;
1680 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1681 	/* Reset time to live. */
1682 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1683 	{
1684 		/* Swap source and destination addresses */
1685 		ipaddr_t tmp;
1686 
1687 		tmp = ipha->ipha_src;
1688 		ipha->ipha_src = ipha->ipha_dst;
1689 		ipha->ipha_dst = tmp;
1690 	}
1691 	ipha->ipha_ident = 0;
1692 	if (!IS_SIMPLE_IPH(ipha))
1693 		icmp_options_update(ipha);
1694 
1695 	bzero(&ixas, sizeof (ixas));
1696 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1697 	ixas.ixa_zoneid = ira->ira_zoneid;
1698 	ixas.ixa_cred = kcred;
1699 	ixas.ixa_cpid = NOPID;
1700 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1701 	ixas.ixa_ifindex = 0;
1702 	ixas.ixa_ipst = ipst;
1703 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1704 
1705 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1706 		/*
1707 		 * This packet should go out the same way as it
1708 		 * came in i.e in clear, independent of the IPsec policy
1709 		 * for transmitting packets.
1710 		 */
1711 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1712 	} else {
1713 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1714 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1715 			/* Note: mp already consumed and ip_drop_packet done */
1716 			return;
1717 		}
1718 	}
1719 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1720 		/*
1721 		 * Not one or our addresses (IRE_LOCALs), thus we let
1722 		 * ip_output_simple pick the source.
1723 		 */
1724 		ipha->ipha_src = INADDR_ANY;
1725 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1726 	}
1727 	/* Should we send with DF and use dce_pmtu? */
1728 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1729 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1730 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1731 	}
1732 
1733 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1734 
1735 	(void) ip_output_simple(mp, &ixas);
1736 	ixa_cleanup(&ixas);
1737 }
1738 
1739 /*
1740  * Verify the ICMP messages for either for ICMP error or redirect packet.
1741  * The caller should have fully pulled up the message. If it's a redirect
1742  * packet, only basic checks on IP header will be done; otherwise, verify
1743  * the packet by looking at the included ULP header.
1744  *
1745  * Called before icmp_inbound_error_fanout_v4 is called.
1746  */
1747 static boolean_t
1748 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1749 {
1750 	ill_t		*ill = ira->ira_ill;
1751 	int		hdr_length;
1752 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1753 	conn_t		*connp;
1754 	ipha_t		*ipha;	/* Inner IP header */
1755 
1756 	ipha = (ipha_t *)&icmph[1];
1757 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1758 		goto truncated;
1759 
1760 	hdr_length = IPH_HDR_LENGTH(ipha);
1761 
1762 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1763 		goto discard_pkt;
1764 
1765 	if (hdr_length < sizeof (ipha_t))
1766 		goto truncated;
1767 
1768 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1769 		goto truncated;
1770 
1771 	/*
1772 	 * Stop here for ICMP_REDIRECT.
1773 	 */
1774 	if (icmph->icmph_type == ICMP_REDIRECT)
1775 		return (B_TRUE);
1776 
1777 	/*
1778 	 * ICMP errors only.
1779 	 */
1780 	switch (ipha->ipha_protocol) {
1781 	case IPPROTO_UDP:
1782 		/*
1783 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1784 		 * transport header.
1785 		 */
1786 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1787 		    mp->b_wptr)
1788 			goto truncated;
1789 		break;
1790 	case IPPROTO_TCP: {
1791 		tcpha_t		*tcpha;
1792 
1793 		/*
1794 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1795 		 * transport header.
1796 		 */
1797 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1798 		    mp->b_wptr)
1799 			goto truncated;
1800 
1801 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1802 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1803 		    ipst);
1804 		if (connp == NULL)
1805 			goto discard_pkt;
1806 
1807 		if ((connp->conn_verifyicmp != NULL) &&
1808 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1809 			CONN_DEC_REF(connp);
1810 			goto discard_pkt;
1811 		}
1812 		CONN_DEC_REF(connp);
1813 		break;
1814 	}
1815 	case IPPROTO_SCTP:
1816 		/*
1817 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1818 		 * transport header.
1819 		 */
1820 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1821 		    mp->b_wptr)
1822 			goto truncated;
1823 		break;
1824 	case IPPROTO_ESP:
1825 	case IPPROTO_AH:
1826 		break;
1827 	case IPPROTO_ENCAP:
1828 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1829 		    mp->b_wptr)
1830 			goto truncated;
1831 		break;
1832 	default:
1833 		break;
1834 	}
1835 
1836 	return (B_TRUE);
1837 
1838 discard_pkt:
1839 	/* Bogus ICMP error. */
1840 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1841 	return (B_FALSE);
1842 
1843 truncated:
1844 	/* We pulled up everthing already. Must be truncated */
1845 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1846 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1847 	return (B_FALSE);
1848 }
1849 
1850 /* Table from RFC 1191 */
1851 static int icmp_frag_size_table[] =
1852 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1853 
1854 /*
1855  * Process received ICMP Packet too big.
1856  * Just handles the DCE create/update, including using the above table of
1857  * PMTU guesses. The caller is responsible for validating the packet before
1858  * passing it in and also to fanout the ICMP error to any matching transport
1859  * conns. Assumes the message has been fully pulled up and verified.
1860  *
1861  * Before getting here, the caller has called icmp_inbound_verify_v4()
1862  * that should have verified with ULP to prevent undoing the changes we're
1863  * going to make to DCE. For example, TCP might have verified that the packet
1864  * which generated error is in the send window.
1865  *
1866  * In some cases modified this MTU in the ICMP header packet; the caller
1867  * should pass to the matching ULP after this returns.
1868  */
1869 static void
1870 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1871 {
1872 	dce_t		*dce;
1873 	int		old_mtu;
1874 	int		mtu, orig_mtu;
1875 	ipaddr_t	dst;
1876 	boolean_t	disable_pmtud;
1877 	ill_t		*ill = ira->ira_ill;
1878 	ip_stack_t	*ipst = ill->ill_ipst;
1879 	uint_t		hdr_length;
1880 	ipha_t		*ipha;
1881 
1882 	/* Caller already pulled up everything. */
1883 	ipha = (ipha_t *)&icmph[1];
1884 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1885 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1886 	ASSERT(ill != NULL);
1887 
1888 	hdr_length = IPH_HDR_LENGTH(ipha);
1889 
1890 	/*
1891 	 * We handle path MTU for source routed packets since the DCE
1892 	 * is looked up using the final destination.
1893 	 */
1894 	dst = ip_get_dst(ipha);
1895 
1896 	dce = dce_lookup_and_add_v4(dst, ipst);
1897 	if (dce == NULL) {
1898 		/* Couldn't add a unique one - ENOMEM */
1899 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1900 		    ntohl(dst)));
1901 		return;
1902 	}
1903 
1904 	/* Check for MTU discovery advice as described in RFC 1191 */
1905 	mtu = ntohs(icmph->icmph_du_mtu);
1906 	orig_mtu = mtu;
1907 	disable_pmtud = B_FALSE;
1908 
1909 	mutex_enter(&dce->dce_lock);
1910 	if (dce->dce_flags & DCEF_PMTU)
1911 		old_mtu = dce->dce_pmtu;
1912 	else
1913 		old_mtu = ill->ill_mtu;
1914 
1915 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1916 		uint32_t length;
1917 		int	i;
1918 
1919 		/*
1920 		 * Use the table from RFC 1191 to figure out
1921 		 * the next "plateau" based on the length in
1922 		 * the original IP packet.
1923 		 */
1924 		length = ntohs(ipha->ipha_length);
1925 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1926 		    uint32_t, length);
1927 		if (old_mtu <= length &&
1928 		    old_mtu >= length - hdr_length) {
1929 			/*
1930 			 * Handle broken BSD 4.2 systems that
1931 			 * return the wrong ipha_length in ICMP
1932 			 * errors.
1933 			 */
1934 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1935 			    length, old_mtu));
1936 			length -= hdr_length;
1937 		}
1938 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1939 			if (length > icmp_frag_size_table[i])
1940 				break;
1941 		}
1942 		if (i == A_CNT(icmp_frag_size_table)) {
1943 			/* Smaller than IP_MIN_MTU! */
1944 			ip1dbg(("Too big for packet size %d\n",
1945 			    length));
1946 			disable_pmtud = B_TRUE;
1947 			mtu = ipst->ips_ip_pmtu_min;
1948 		} else {
1949 			mtu = icmp_frag_size_table[i];
1950 			ip1dbg(("Calculated mtu %d, packet size %d, "
1951 			    "before %d\n", mtu, length, old_mtu));
1952 			if (mtu < ipst->ips_ip_pmtu_min) {
1953 				mtu = ipst->ips_ip_pmtu_min;
1954 				disable_pmtud = B_TRUE;
1955 			}
1956 		}
1957 	}
1958 	if (disable_pmtud)
1959 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1960 	else
1961 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1962 
1963 	dce->dce_pmtu = MIN(old_mtu, mtu);
1964 	/* Prepare to send the new max frag size for the ULP. */
1965 	icmph->icmph_du_zero = 0;
1966 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1967 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1968 	    dce, int, orig_mtu, int, mtu);
1969 
1970 	/* We now have a PMTU for sure */
1971 	dce->dce_flags |= DCEF_PMTU;
1972 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1973 	mutex_exit(&dce->dce_lock);
1974 	/*
1975 	 * After dropping the lock the new value is visible to everyone.
1976 	 * Then we bump the generation number so any cached values reinspect
1977 	 * the dce_t.
1978 	 */
1979 	dce_increment_generation(dce);
1980 	dce_refrele(dce);
1981 }
1982 
1983 /*
1984  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1985  * calls this function.
1986  */
1987 static mblk_t *
1988 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1989 {
1990 	int length;
1991 
1992 	ASSERT(mp->b_datap->db_type == M_DATA);
1993 
1994 	/* icmp_inbound_v4 has already pulled up the whole error packet */
1995 	ASSERT(mp->b_cont == NULL);
1996 
1997 	/*
1998 	 * The length that we want to overlay is the inner header
1999 	 * and what follows it.
2000 	 */
2001 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
2002 
2003 	/*
2004 	 * Overlay the inner header and whatever follows it over the
2005 	 * outer header.
2006 	 */
2007 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2008 
2009 	/* Adjust for what we removed */
2010 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2011 	return (mp);
2012 }
2013 
2014 /*
2015  * Try to pass the ICMP message upstream in case the ULP cares.
2016  *
2017  * If the packet that caused the ICMP error is secure, we send
2018  * it to AH/ESP to make sure that the attached packet has a
2019  * valid association. ipha in the code below points to the
2020  * IP header of the packet that caused the error.
2021  *
2022  * For IPsec cases, we let the next-layer-up (which has access to
2023  * cached policy on the conn_t, or can query the SPD directly)
2024  * subtract out any IPsec overhead if they must.  We therefore make no
2025  * adjustments here for IPsec overhead.
2026  *
2027  * IFN could have been generated locally or by some router.
2028  *
2029  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2030  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2031  *	    This happens because IP adjusted its value of MTU on an
2032  *	    earlier IFN message and could not tell the upper layer,
2033  *	    the new adjusted value of MTU e.g. Packet was encrypted
2034  *	    or there was not enough information to fanout to upper
2035  *	    layers. Thus on the next outbound datagram, ire_send_wire
2036  *	    generates the IFN, where IPsec processing has *not* been
2037  *	    done.
2038  *
2039  *	    Note that we retain ixa_fragsize across IPsec thus once
2040  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2041  *	    no change the fragsize even if the path MTU changes before
2042  *	    we reach ip_output_post_ipsec.
2043  *
2044  *	    In the local case, IRAF_LOOPBACK will be set indicating
2045  *	    that IFN was generated locally.
2046  *
2047  * ROUTER : IFN could be secure or non-secure.
2048  *
2049  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2050  *	      packet in error has AH/ESP headers to validate the AH/ESP
2051  *	      headers. AH/ESP will verify whether there is a valid SA or
2052  *	      not and send it back. We will fanout again if we have more
2053  *	      data in the packet.
2054  *
2055  *	      If the packet in error does not have AH/ESP, we handle it
2056  *	      like any other case.
2057  *
2058  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2059  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2060  *	      valid SA or not and send it back. We will fanout again if
2061  *	      we have more data in the packet.
2062  *
2063  *	      If the packet in error does not have AH/ESP, we handle it
2064  *	      like any other case.
2065  *
2066  * The caller must have called icmp_inbound_verify_v4.
2067  */
2068 static void
2069 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2070 {
2071 	uint16_t	*up;	/* Pointer to ports in ULP header */
2072 	uint32_t	ports;	/* reversed ports for fanout */
2073 	ipha_t		ripha;	/* With reversed addresses */
2074 	ipha_t		*ipha;  /* Inner IP header */
2075 	uint_t		hdr_length; /* Inner IP header length */
2076 	tcpha_t		*tcpha;
2077 	conn_t		*connp;
2078 	ill_t		*ill = ira->ira_ill;
2079 	ip_stack_t	*ipst = ill->ill_ipst;
2080 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2081 	ill_t		*rill = ira->ira_rill;
2082 
2083 	/* Caller already pulled up everything. */
2084 	ipha = (ipha_t *)&icmph[1];
2085 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2086 	ASSERT(mp->b_cont == NULL);
2087 
2088 	hdr_length = IPH_HDR_LENGTH(ipha);
2089 	ira->ira_protocol = ipha->ipha_protocol;
2090 
2091 	/*
2092 	 * We need a separate IP header with the source and destination
2093 	 * addresses reversed to do fanout/classification because the ipha in
2094 	 * the ICMP error is in the form we sent it out.
2095 	 */
2096 	ripha.ipha_src = ipha->ipha_dst;
2097 	ripha.ipha_dst = ipha->ipha_src;
2098 	ripha.ipha_protocol = ipha->ipha_protocol;
2099 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2100 
2101 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2102 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2103 	    ntohl(ipha->ipha_dst),
2104 	    icmph->icmph_type, icmph->icmph_code));
2105 
2106 	switch (ipha->ipha_protocol) {
2107 	case IPPROTO_UDP:
2108 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2109 
2110 		/* Attempt to find a client stream based on port. */
2111 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2112 		    ntohs(up[0]), ntohs(up[1])));
2113 
2114 		/* Note that we send error to all matches. */
2115 		ira->ira_flags |= IRAF_ICMP_ERROR;
2116 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2117 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2118 		return;
2119 
2120 	case IPPROTO_TCP:
2121 		/*
2122 		 * Find a TCP client stream for this packet.
2123 		 * Note that we do a reverse lookup since the header is
2124 		 * in the form we sent it out.
2125 		 */
2126 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2127 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2128 		    ipst);
2129 		if (connp == NULL)
2130 			goto discard_pkt;
2131 
2132 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2133 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2134 			mp = ipsec_check_inbound_policy(mp, connp,
2135 			    ipha, NULL, ira);
2136 			if (mp == NULL) {
2137 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2138 				/* Note that mp is NULL */
2139 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2140 				CONN_DEC_REF(connp);
2141 				return;
2142 			}
2143 		}
2144 
2145 		ira->ira_flags |= IRAF_ICMP_ERROR;
2146 		ira->ira_ill = ira->ira_rill = NULL;
2147 		if (IPCL_IS_TCP(connp)) {
2148 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2149 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2150 			    SQTAG_TCP_INPUT_ICMP_ERR);
2151 		} else {
2152 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2153 			(connp->conn_recv)(connp, mp, NULL, ira);
2154 			CONN_DEC_REF(connp);
2155 		}
2156 		ira->ira_ill = ill;
2157 		ira->ira_rill = rill;
2158 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2159 		return;
2160 
2161 	case IPPROTO_SCTP:
2162 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2163 		/* Find a SCTP client stream for this packet. */
2164 		((uint16_t *)&ports)[0] = up[1];
2165 		((uint16_t *)&ports)[1] = up[0];
2166 
2167 		ira->ira_flags |= IRAF_ICMP_ERROR;
2168 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2169 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2170 		return;
2171 
2172 	case IPPROTO_ESP:
2173 	case IPPROTO_AH:
2174 		if (!ipsec_loaded(ipss)) {
2175 			ip_proto_not_sup(mp, ira);
2176 			return;
2177 		}
2178 
2179 		if (ipha->ipha_protocol == IPPROTO_ESP)
2180 			mp = ipsecesp_icmp_error(mp, ira);
2181 		else
2182 			mp = ipsecah_icmp_error(mp, ira);
2183 		if (mp == NULL)
2184 			return;
2185 
2186 		/* Just in case ipsec didn't preserve the NULL b_cont */
2187 		if (mp->b_cont != NULL) {
2188 			if (!pullupmsg(mp, -1))
2189 				goto discard_pkt;
2190 		}
2191 
2192 		/*
2193 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2194 		 * correct, but we don't use them any more here.
2195 		 *
2196 		 * If succesful, the mp has been modified to not include
2197 		 * the ESP/AH header so we can fanout to the ULP's icmp
2198 		 * error handler.
2199 		 */
2200 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2201 			goto truncated;
2202 
2203 		/* Verify the modified message before any further processes. */
2204 		ipha = (ipha_t *)mp->b_rptr;
2205 		hdr_length = IPH_HDR_LENGTH(ipha);
2206 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2207 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2208 			freemsg(mp);
2209 			return;
2210 		}
2211 
2212 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2213 		return;
2214 
2215 	case IPPROTO_ENCAP: {
2216 		/* Look for self-encapsulated packets that caused an error */
2217 		ipha_t *in_ipha;
2218 
2219 		/*
2220 		 * Caller has verified that length has to be
2221 		 * at least the size of IP header.
2222 		 */
2223 		ASSERT(hdr_length >= sizeof (ipha_t));
2224 		/*
2225 		 * Check the sanity of the inner IP header like
2226 		 * we did for the outer header.
2227 		 */
2228 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2229 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2230 			goto discard_pkt;
2231 		}
2232 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2233 			goto discard_pkt;
2234 		}
2235 		/* Check for Self-encapsulated tunnels */
2236 		if (in_ipha->ipha_src == ipha->ipha_src &&
2237 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2238 
2239 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2240 			    in_ipha);
2241 			if (mp == NULL)
2242 				goto discard_pkt;
2243 
2244 			/*
2245 			 * Just in case self_encap didn't preserve the NULL
2246 			 * b_cont
2247 			 */
2248 			if (mp->b_cont != NULL) {
2249 				if (!pullupmsg(mp, -1))
2250 					goto discard_pkt;
2251 			}
2252 			/*
2253 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2254 			 * longer correct, but we don't use them any more here.
2255 			 */
2256 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2257 				goto truncated;
2258 
2259 			/*
2260 			 * Verify the modified message before any further
2261 			 * processes.
2262 			 */
2263 			ipha = (ipha_t *)mp->b_rptr;
2264 			hdr_length = IPH_HDR_LENGTH(ipha);
2265 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2266 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2267 				freemsg(mp);
2268 				return;
2269 			}
2270 
2271 			/*
2272 			 * The packet in error is self-encapsualted.
2273 			 * And we are finding it further encapsulated
2274 			 * which we could not have possibly generated.
2275 			 */
2276 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2277 				goto discard_pkt;
2278 			}
2279 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2280 			return;
2281 		}
2282 		/* No self-encapsulated */
2283 		/* FALLTHRU */
2284 	}
2285 	case IPPROTO_IPV6:
2286 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2287 		    &ripha.ipha_dst, ipst)) != NULL) {
2288 			ira->ira_flags |= IRAF_ICMP_ERROR;
2289 			connp->conn_recvicmp(connp, mp, NULL, ira);
2290 			CONN_DEC_REF(connp);
2291 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2292 			return;
2293 		}
2294 		/*
2295 		 * No IP tunnel is interested, fallthrough and see
2296 		 * if a raw socket will want it.
2297 		 */
2298 		/* FALLTHRU */
2299 	default:
2300 		ira->ira_flags |= IRAF_ICMP_ERROR;
2301 		ip_fanout_proto_v4(mp, &ripha, ira);
2302 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2303 		return;
2304 	}
2305 	/* NOTREACHED */
2306 discard_pkt:
2307 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2308 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2309 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2310 	freemsg(mp);
2311 	return;
2312 
2313 truncated:
2314 	/* We pulled up everthing already. Must be truncated */
2315 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2316 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2317 	freemsg(mp);
2318 }
2319 
2320 /*
2321  * Common IP options parser.
2322  *
2323  * Setup routine: fill in *optp with options-parsing state, then
2324  * tail-call ipoptp_next to return the first option.
2325  */
2326 uint8_t
2327 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2328 {
2329 	uint32_t totallen; /* total length of all options */
2330 
2331 	totallen = ipha->ipha_version_and_hdr_length -
2332 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2333 	totallen <<= 2;
2334 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2335 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2336 	optp->ipoptp_flags = 0;
2337 	return (ipoptp_next(optp));
2338 }
2339 
2340 /* Like above but without an ipha_t */
2341 uint8_t
2342 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2343 {
2344 	optp->ipoptp_next = opt;
2345 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2346 	optp->ipoptp_flags = 0;
2347 	return (ipoptp_next(optp));
2348 }
2349 
2350 /*
2351  * Common IP options parser: extract next option.
2352  */
2353 uint8_t
2354 ipoptp_next(ipoptp_t *optp)
2355 {
2356 	uint8_t *end = optp->ipoptp_end;
2357 	uint8_t *cur = optp->ipoptp_next;
2358 	uint8_t opt, len, pointer;
2359 
2360 	/*
2361 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2362 	 * has been corrupted.
2363 	 */
2364 	ASSERT(cur <= end);
2365 
2366 	if (cur == end)
2367 		return (IPOPT_EOL);
2368 
2369 	opt = cur[IPOPT_OPTVAL];
2370 
2371 	/*
2372 	 * Skip any NOP options.
2373 	 */
2374 	while (opt == IPOPT_NOP) {
2375 		cur++;
2376 		if (cur == end)
2377 			return (IPOPT_EOL);
2378 		opt = cur[IPOPT_OPTVAL];
2379 	}
2380 
2381 	if (opt == IPOPT_EOL)
2382 		return (IPOPT_EOL);
2383 
2384 	/*
2385 	 * Option requiring a length.
2386 	 */
2387 	if ((cur + 1) >= end) {
2388 		optp->ipoptp_flags |= IPOPTP_ERROR;
2389 		return (IPOPT_EOL);
2390 	}
2391 	len = cur[IPOPT_OLEN];
2392 	if (len < 2) {
2393 		optp->ipoptp_flags |= IPOPTP_ERROR;
2394 		return (IPOPT_EOL);
2395 	}
2396 	optp->ipoptp_cur = cur;
2397 	optp->ipoptp_len = len;
2398 	optp->ipoptp_next = cur + len;
2399 	if (cur + len > end) {
2400 		optp->ipoptp_flags |= IPOPTP_ERROR;
2401 		return (IPOPT_EOL);
2402 	}
2403 
2404 	/*
2405 	 * For the options which require a pointer field, make sure
2406 	 * its there, and make sure it points to either something
2407 	 * inside this option, or the end of the option.
2408 	 */
2409 	switch (opt) {
2410 	case IPOPT_RR:
2411 	case IPOPT_TS:
2412 	case IPOPT_LSRR:
2413 	case IPOPT_SSRR:
2414 		if (len <= IPOPT_OFFSET) {
2415 			optp->ipoptp_flags |= IPOPTP_ERROR;
2416 			return (opt);
2417 		}
2418 		pointer = cur[IPOPT_OFFSET];
2419 		if (pointer - 1 > len) {
2420 			optp->ipoptp_flags |= IPOPTP_ERROR;
2421 			return (opt);
2422 		}
2423 		break;
2424 	}
2425 
2426 	/*
2427 	 * Sanity check the pointer field based on the type of the
2428 	 * option.
2429 	 */
2430 	switch (opt) {
2431 	case IPOPT_RR:
2432 	case IPOPT_SSRR:
2433 	case IPOPT_LSRR:
2434 		if (pointer < IPOPT_MINOFF_SR)
2435 			optp->ipoptp_flags |= IPOPTP_ERROR;
2436 		break;
2437 	case IPOPT_TS:
2438 		if (pointer < IPOPT_MINOFF_IT)
2439 			optp->ipoptp_flags |= IPOPTP_ERROR;
2440 		/*
2441 		 * Note that the Internet Timestamp option also
2442 		 * contains two four bit fields (the Overflow field,
2443 		 * and the Flag field), which follow the pointer
2444 		 * field.  We don't need to check that these fields
2445 		 * fall within the length of the option because this
2446 		 * was implicitely done above.  We've checked that the
2447 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2448 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2449 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2450 		 */
2451 		ASSERT(len > IPOPT_POS_OV_FLG);
2452 		break;
2453 	}
2454 
2455 	return (opt);
2456 }
2457 
2458 /*
2459  * Use the outgoing IP header to create an IP_OPTIONS option the way
2460  * it was passed down from the application.
2461  *
2462  * This is compatible with BSD in that it returns
2463  * the reverse source route with the final destination
2464  * as the last entry. The first 4 bytes of the option
2465  * will contain the final destination.
2466  */
2467 int
2468 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2469 {
2470 	ipoptp_t	opts;
2471 	uchar_t		*opt;
2472 	uint8_t		optval;
2473 	uint8_t		optlen;
2474 	uint32_t	len = 0;
2475 	uchar_t		*buf1 = buf;
2476 	uint32_t	totallen;
2477 	ipaddr_t	dst;
2478 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2479 
2480 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2481 		return (0);
2482 
2483 	totallen = ipp->ipp_ipv4_options_len;
2484 	if (totallen & 0x3)
2485 		return (0);
2486 
2487 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2488 	len += IP_ADDR_LEN;
2489 	bzero(buf1, IP_ADDR_LEN);
2490 
2491 	dst = connp->conn_faddr_v4;
2492 
2493 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2494 	    optval != IPOPT_EOL;
2495 	    optval = ipoptp_next(&opts)) {
2496 		int	off;
2497 
2498 		opt = opts.ipoptp_cur;
2499 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2500 			break;
2501 		}
2502 		optlen = opts.ipoptp_len;
2503 
2504 		switch (optval) {
2505 		case IPOPT_SSRR:
2506 		case IPOPT_LSRR:
2507 
2508 			/*
2509 			 * Insert destination as the first entry in the source
2510 			 * route and move down the entries on step.
2511 			 * The last entry gets placed at buf1.
2512 			 */
2513 			buf[IPOPT_OPTVAL] = optval;
2514 			buf[IPOPT_OLEN] = optlen;
2515 			buf[IPOPT_OFFSET] = optlen;
2516 
2517 			off = optlen - IP_ADDR_LEN;
2518 			if (off < 0) {
2519 				/* No entries in source route */
2520 				break;
2521 			}
2522 			/* Last entry in source route if not already set */
2523 			if (dst == INADDR_ANY)
2524 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2525 			off -= IP_ADDR_LEN;
2526 
2527 			while (off > 0) {
2528 				bcopy(opt + off,
2529 				    buf + off + IP_ADDR_LEN,
2530 				    IP_ADDR_LEN);
2531 				off -= IP_ADDR_LEN;
2532 			}
2533 			/* ipha_dst into first slot */
2534 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2535 			    IP_ADDR_LEN);
2536 			buf += optlen;
2537 			len += optlen;
2538 			break;
2539 
2540 		default:
2541 			bcopy(opt, buf, optlen);
2542 			buf += optlen;
2543 			len += optlen;
2544 			break;
2545 		}
2546 	}
2547 done:
2548 	/* Pad the resulting options */
2549 	while (len & 0x3) {
2550 		*buf++ = IPOPT_EOL;
2551 		len++;
2552 	}
2553 	return (len);
2554 }
2555 
2556 /*
2557  * Update any record route or timestamp options to include this host.
2558  * Reverse any source route option.
2559  * This routine assumes that the options are well formed i.e. that they
2560  * have already been checked.
2561  */
2562 static void
2563 icmp_options_update(ipha_t *ipha)
2564 {
2565 	ipoptp_t	opts;
2566 	uchar_t		*opt;
2567 	uint8_t		optval;
2568 	ipaddr_t	src;		/* Our local address */
2569 	ipaddr_t	dst;
2570 
2571 	ip2dbg(("icmp_options_update\n"));
2572 	src = ipha->ipha_src;
2573 	dst = ipha->ipha_dst;
2574 
2575 	for (optval = ipoptp_first(&opts, ipha);
2576 	    optval != IPOPT_EOL;
2577 	    optval = ipoptp_next(&opts)) {
2578 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2579 		opt = opts.ipoptp_cur;
2580 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2581 		    optval, opts.ipoptp_len));
2582 		switch (optval) {
2583 			int off1, off2;
2584 		case IPOPT_SSRR:
2585 		case IPOPT_LSRR:
2586 			/*
2587 			 * Reverse the source route.  The first entry
2588 			 * should be the next to last one in the current
2589 			 * source route (the last entry is our address).
2590 			 * The last entry should be the final destination.
2591 			 */
2592 			off1 = IPOPT_MINOFF_SR - 1;
2593 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2594 			if (off2 < 0) {
2595 				/* No entries in source route */
2596 				ip1dbg((
2597 				    "icmp_options_update: bad src route\n"));
2598 				break;
2599 			}
2600 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2601 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2602 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2603 			off2 -= IP_ADDR_LEN;
2604 
2605 			while (off1 < off2) {
2606 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2607 				bcopy((char *)opt + off2, (char *)opt + off1,
2608 				    IP_ADDR_LEN);
2609 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2610 				off1 += IP_ADDR_LEN;
2611 				off2 -= IP_ADDR_LEN;
2612 			}
2613 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2614 			break;
2615 		}
2616 	}
2617 }
2618 
2619 /*
2620  * Process received ICMP Redirect messages.
2621  * Assumes the caller has verified that the headers are in the pulled up mblk.
2622  * Consumes mp.
2623  */
2624 static void
2625 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2626 {
2627 	ire_t		*ire, *nire;
2628 	ire_t		*prev_ire;
2629 	ipaddr_t  	src, dst, gateway;
2630 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2631 	ipha_t		*inner_ipha;	/* Inner IP header */
2632 
2633 	/* Caller already pulled up everything. */
2634 	inner_ipha = (ipha_t *)&icmph[1];
2635 	src = ipha->ipha_src;
2636 	dst = inner_ipha->ipha_dst;
2637 	gateway = icmph->icmph_rd_gateway;
2638 	/* Make sure the new gateway is reachable somehow. */
2639 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2640 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2641 	/*
2642 	 * Make sure we had a route for the dest in question and that
2643 	 * that route was pointing to the old gateway (the source of the
2644 	 * redirect packet.)
2645 	 * We do longest match and then compare ire_gateway_addr below.
2646 	 */
2647 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2648 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2649 	/*
2650 	 * Check that
2651 	 *	the redirect was not from ourselves
2652 	 *	the new gateway and the old gateway are directly reachable
2653 	 */
2654 	if (prev_ire == NULL || ire == NULL ||
2655 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2656 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2657 	    !(ire->ire_type & IRE_IF_ALL) ||
2658 	    prev_ire->ire_gateway_addr != src) {
2659 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2660 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2661 		freemsg(mp);
2662 		if (ire != NULL)
2663 			ire_refrele(ire);
2664 		if (prev_ire != NULL)
2665 			ire_refrele(prev_ire);
2666 		return;
2667 	}
2668 
2669 	ire_refrele(prev_ire);
2670 	ire_refrele(ire);
2671 
2672 	/*
2673 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2674 	 * require TOS routing
2675 	 */
2676 	switch (icmph->icmph_code) {
2677 	case 0:
2678 	case 1:
2679 		/* TODO: TOS specificity for cases 2 and 3 */
2680 	case 2:
2681 	case 3:
2682 		break;
2683 	default:
2684 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2685 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2686 		freemsg(mp);
2687 		return;
2688 	}
2689 	/*
2690 	 * Create a Route Association.  This will allow us to remember that
2691 	 * someone we believe told us to use the particular gateway.
2692 	 */
2693 	ire = ire_create(
2694 	    (uchar_t *)&dst,			/* dest addr */
2695 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2696 	    (uchar_t *)&gateway,		/* gateway addr */
2697 	    IRE_HOST,
2698 	    NULL,				/* ill */
2699 	    ALL_ZONES,
2700 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2701 	    NULL,				/* tsol_gc_t */
2702 	    ipst);
2703 
2704 	if (ire == NULL) {
2705 		freemsg(mp);
2706 		return;
2707 	}
2708 	nire = ire_add(ire);
2709 	/* Check if it was a duplicate entry */
2710 	if (nire != NULL && nire != ire) {
2711 		ASSERT(nire->ire_identical_ref > 1);
2712 		ire_delete(nire);
2713 		ire_refrele(nire);
2714 		nire = NULL;
2715 	}
2716 	ire = nire;
2717 	if (ire != NULL) {
2718 		ire_refrele(ire);		/* Held in ire_add */
2719 
2720 		/* tell routing sockets that we received a redirect */
2721 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2722 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2723 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2724 	}
2725 
2726 	/*
2727 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2728 	 * This together with the added IRE has the effect of
2729 	 * modifying an existing redirect.
2730 	 */
2731 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2732 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2733 	if (prev_ire != NULL) {
2734 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2735 			ire_delete(prev_ire);
2736 		ire_refrele(prev_ire);
2737 	}
2738 
2739 	freemsg(mp);
2740 }
2741 
2742 /*
2743  * Generate an ICMP parameter problem message.
2744  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2745  * constructed by the caller.
2746  */
2747 static void
2748 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2749 {
2750 	icmph_t	icmph;
2751 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2752 
2753 	mp = icmp_pkt_err_ok(mp, ira);
2754 	if (mp == NULL)
2755 		return;
2756 
2757 	bzero(&icmph, sizeof (icmph_t));
2758 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2759 	icmph.icmph_pp_ptr = ptr;
2760 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2761 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2762 }
2763 
2764 /*
2765  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2766  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2767  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2768  * an icmp error packet can be sent.
2769  * Assigns an appropriate source address to the packet. If ipha_dst is
2770  * one of our addresses use it for source. Otherwise let ip_output_simple
2771  * pick the source address.
2772  */
2773 static void
2774 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2775 {
2776 	ipaddr_t dst;
2777 	icmph_t	*icmph;
2778 	ipha_t	*ipha;
2779 	uint_t	len_needed;
2780 	size_t	msg_len;
2781 	mblk_t	*mp1;
2782 	ipaddr_t src;
2783 	ire_t	*ire;
2784 	ip_xmit_attr_t ixas;
2785 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2786 
2787 	ipha = (ipha_t *)mp->b_rptr;
2788 
2789 	bzero(&ixas, sizeof (ixas));
2790 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2791 	ixas.ixa_zoneid = ira->ira_zoneid;
2792 	ixas.ixa_ifindex = 0;
2793 	ixas.ixa_ipst = ipst;
2794 	ixas.ixa_cred = kcred;
2795 	ixas.ixa_cpid = NOPID;
2796 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2797 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2798 
2799 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2800 		/*
2801 		 * Apply IPsec based on how IPsec was applied to
2802 		 * the packet that had the error.
2803 		 *
2804 		 * If it was an outbound packet that caused the ICMP
2805 		 * error, then the caller will have setup the IRA
2806 		 * appropriately.
2807 		 */
2808 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2809 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2810 			/* Note: mp already consumed and ip_drop_packet done */
2811 			return;
2812 		}
2813 	} else {
2814 		/*
2815 		 * This is in clear. The icmp message we are building
2816 		 * here should go out in clear, independent of our policy.
2817 		 */
2818 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2819 	}
2820 
2821 	/* Remember our eventual destination */
2822 	dst = ipha->ipha_src;
2823 
2824 	/*
2825 	 * If the packet was for one of our unicast addresses, make
2826 	 * sure we respond with that as the source. Otherwise
2827 	 * have ip_output_simple pick the source address.
2828 	 */
2829 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2830 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2831 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2832 	if (ire != NULL) {
2833 		ire_refrele(ire);
2834 		src = ipha->ipha_dst;
2835 	} else {
2836 		src = INADDR_ANY;
2837 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2838 	}
2839 
2840 	/*
2841 	 * Check if we can send back more then 8 bytes in addition to
2842 	 * the IP header.  We try to send 64 bytes of data and the internal
2843 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2844 	 */
2845 	len_needed = IPH_HDR_LENGTH(ipha);
2846 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2847 	    ipha->ipha_protocol == IPPROTO_IPV6) {
2848 		if (!pullupmsg(mp, -1)) {
2849 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2850 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2851 			freemsg(mp);
2852 			return;
2853 		}
2854 		ipha = (ipha_t *)mp->b_rptr;
2855 
2856 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2857 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2858 			    len_needed));
2859 		} else {
2860 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2861 
2862 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2863 			len_needed += ip_hdr_length_v6(mp, ip6h);
2864 		}
2865 	}
2866 	len_needed += ipst->ips_ip_icmp_return;
2867 	msg_len = msgdsize(mp);
2868 	if (msg_len > len_needed) {
2869 		(void) adjmsg(mp, len_needed - msg_len);
2870 		msg_len = len_needed;
2871 	}
2872 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2873 	if (mp1 == NULL) {
2874 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2875 		freemsg(mp);
2876 		return;
2877 	}
2878 	mp1->b_cont = mp;
2879 	mp = mp1;
2880 
2881 	/*
2882 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2883 	 * node generates be accepted in peace by all on-host destinations.
2884 	 * If we do NOT assume that all on-host destinations trust
2885 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2886 	 * (Look for IXAF_TRUSTED_ICMP).
2887 	 */
2888 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2889 
2890 	ipha = (ipha_t *)mp->b_rptr;
2891 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2892 	*ipha = icmp_ipha;
2893 	ipha->ipha_src = src;
2894 	ipha->ipha_dst = dst;
2895 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2896 	msg_len += sizeof (icmp_ipha) + len;
2897 	if (msg_len > IP_MAXPACKET) {
2898 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
2899 		msg_len = IP_MAXPACKET;
2900 	}
2901 	ipha->ipha_length = htons((uint16_t)msg_len);
2902 	icmph = (icmph_t *)&ipha[1];
2903 	bcopy(stuff, icmph, len);
2904 	icmph->icmph_checksum = 0;
2905 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2906 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2907 
2908 	(void) ip_output_simple(mp, &ixas);
2909 	ixa_cleanup(&ixas);
2910 }
2911 
2912 /*
2913  * Determine if an ICMP error packet can be sent given the rate limit.
2914  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2915  * in milliseconds) and a burst size. Burst size number of packets can
2916  * be sent arbitrarely closely spaced.
2917  * The state is tracked using two variables to implement an approximate
2918  * token bucket filter:
2919  *	icmp_pkt_err_last - lbolt value when the last burst started
2920  *	icmp_pkt_err_sent - number of packets sent in current burst
2921  */
2922 boolean_t
2923 icmp_err_rate_limit(ip_stack_t *ipst)
2924 {
2925 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2926 	uint_t refilled; /* Number of packets refilled in tbf since last */
2927 	/* Guard against changes by loading into local variable */
2928 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2929 
2930 	if (err_interval == 0)
2931 		return (B_FALSE);
2932 
2933 	if (ipst->ips_icmp_pkt_err_last > now) {
2934 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2935 		ipst->ips_icmp_pkt_err_last = 0;
2936 		ipst->ips_icmp_pkt_err_sent = 0;
2937 	}
2938 	/*
2939 	 * If we are in a burst update the token bucket filter.
2940 	 * Update the "last" time to be close to "now" but make sure
2941 	 * we don't loose precision.
2942 	 */
2943 	if (ipst->ips_icmp_pkt_err_sent != 0) {
2944 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2945 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
2946 			ipst->ips_icmp_pkt_err_sent = 0;
2947 		} else {
2948 			ipst->ips_icmp_pkt_err_sent -= refilled;
2949 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2950 		}
2951 	}
2952 	if (ipst->ips_icmp_pkt_err_sent == 0) {
2953 		/* Start of new burst */
2954 		ipst->ips_icmp_pkt_err_last = now;
2955 	}
2956 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2957 		ipst->ips_icmp_pkt_err_sent++;
2958 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2959 		    ipst->ips_icmp_pkt_err_sent));
2960 		return (B_FALSE);
2961 	}
2962 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
2963 	return (B_TRUE);
2964 }
2965 
2966 /*
2967  * Check if it is ok to send an IPv4 ICMP error packet in
2968  * response to the IPv4 packet in mp.
2969  * Free the message and return null if no
2970  * ICMP error packet should be sent.
2971  */
2972 static mblk_t *
2973 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2974 {
2975 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2976 	icmph_t	*icmph;
2977 	ipha_t	*ipha;
2978 	uint_t	len_needed;
2979 
2980 	if (!mp)
2981 		return (NULL);
2982 	ipha = (ipha_t *)mp->b_rptr;
2983 	if (ip_csum_hdr(ipha)) {
2984 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2985 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2986 		freemsg(mp);
2987 		return (NULL);
2988 	}
2989 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2990 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2991 	    CLASSD(ipha->ipha_dst) ||
2992 	    CLASSD(ipha->ipha_src) ||
2993 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2994 		/* Note: only errors to the fragment with offset 0 */
2995 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2996 		freemsg(mp);
2997 		return (NULL);
2998 	}
2999 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3000 		/*
3001 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3002 		 * errors in response to any ICMP errors.
3003 		 */
3004 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3005 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3006 			if (!pullupmsg(mp, len_needed)) {
3007 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3008 				freemsg(mp);
3009 				return (NULL);
3010 			}
3011 			ipha = (ipha_t *)mp->b_rptr;
3012 		}
3013 		icmph = (icmph_t *)
3014 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3015 		switch (icmph->icmph_type) {
3016 		case ICMP_DEST_UNREACHABLE:
3017 		case ICMP_SOURCE_QUENCH:
3018 		case ICMP_TIME_EXCEEDED:
3019 		case ICMP_PARAM_PROBLEM:
3020 		case ICMP_REDIRECT:
3021 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3022 			freemsg(mp);
3023 			return (NULL);
3024 		default:
3025 			break;
3026 		}
3027 	}
3028 	/*
3029 	 * If this is a labeled system, then check to see if we're allowed to
3030 	 * send a response to this particular sender.  If not, then just drop.
3031 	 */
3032 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3033 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3034 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3035 		freemsg(mp);
3036 		return (NULL);
3037 	}
3038 	if (icmp_err_rate_limit(ipst)) {
3039 		/*
3040 		 * Only send ICMP error packets every so often.
3041 		 * This should be done on a per port/source basis,
3042 		 * but for now this will suffice.
3043 		 */
3044 		freemsg(mp);
3045 		return (NULL);
3046 	}
3047 	return (mp);
3048 }
3049 
3050 /*
3051  * Called when a packet was sent out the same link that it arrived on.
3052  * Check if it is ok to send a redirect and then send it.
3053  */
3054 void
3055 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3056     ip_recv_attr_t *ira)
3057 {
3058 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3059 	ipaddr_t	src, nhop;
3060 	mblk_t		*mp1;
3061 	ire_t		*nhop_ire;
3062 
3063 	/*
3064 	 * Check the source address to see if it originated
3065 	 * on the same logical subnet it is going back out on.
3066 	 * If so, we should be able to send it a redirect.
3067 	 * Avoid sending a redirect if the destination
3068 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3069 	 * or if the packet was source routed out this interface.
3070 	 *
3071 	 * We avoid sending a redirect if the
3072 	 * destination is directly connected
3073 	 * because it is possible that multiple
3074 	 * IP subnets may have been configured on
3075 	 * the link, and the source may not
3076 	 * be on the same subnet as ip destination,
3077 	 * even though they are on the same
3078 	 * physical link.
3079 	 */
3080 	if ((ire->ire_type & IRE_ONLINK) ||
3081 	    ip_source_routed(ipha, ipst))
3082 		return;
3083 
3084 	nhop_ire = ire_nexthop(ire);
3085 	if (nhop_ire == NULL)
3086 		return;
3087 
3088 	nhop = nhop_ire->ire_addr;
3089 
3090 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3091 		ire_t	*ire2;
3092 
3093 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3094 		mutex_enter(&nhop_ire->ire_lock);
3095 		ire2 = nhop_ire->ire_dep_parent;
3096 		if (ire2 != NULL)
3097 			ire_refhold(ire2);
3098 		mutex_exit(&nhop_ire->ire_lock);
3099 		ire_refrele(nhop_ire);
3100 		nhop_ire = ire2;
3101 	}
3102 	if (nhop_ire == NULL)
3103 		return;
3104 
3105 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3106 
3107 	src = ipha->ipha_src;
3108 
3109 	/*
3110 	 * We look at the interface ire for the nexthop,
3111 	 * to see if ipha_src is in the same subnet
3112 	 * as the nexthop.
3113 	 */
3114 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3115 		/*
3116 		 * The source is directly connected.
3117 		 */
3118 		mp1 = copymsg(mp);
3119 		if (mp1 != NULL) {
3120 			icmp_send_redirect(mp1, nhop, ira);
3121 		}
3122 	}
3123 	ire_refrele(nhop_ire);
3124 }
3125 
3126 /*
3127  * Generate an ICMP redirect message.
3128  */
3129 static void
3130 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3131 {
3132 	icmph_t	icmph;
3133 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3134 
3135 	mp = icmp_pkt_err_ok(mp, ira);
3136 	if (mp == NULL)
3137 		return;
3138 
3139 	bzero(&icmph, sizeof (icmph_t));
3140 	icmph.icmph_type = ICMP_REDIRECT;
3141 	icmph.icmph_code = 1;
3142 	icmph.icmph_rd_gateway = gateway;
3143 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3144 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3145 }
3146 
3147 /*
3148  * Generate an ICMP time exceeded message.
3149  */
3150 void
3151 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3152 {
3153 	icmph_t	icmph;
3154 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3155 
3156 	mp = icmp_pkt_err_ok(mp, ira);
3157 	if (mp == NULL)
3158 		return;
3159 
3160 	bzero(&icmph, sizeof (icmph_t));
3161 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3162 	icmph.icmph_code = code;
3163 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3164 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3165 }
3166 
3167 /*
3168  * Generate an ICMP unreachable message.
3169  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3170  * constructed by the caller.
3171  */
3172 void
3173 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3174 {
3175 	icmph_t	icmph;
3176 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3177 
3178 	mp = icmp_pkt_err_ok(mp, ira);
3179 	if (mp == NULL)
3180 		return;
3181 
3182 	bzero(&icmph, sizeof (icmph_t));
3183 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3184 	icmph.icmph_code = code;
3185 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3186 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3187 }
3188 
3189 /*
3190  * Latch in the IPsec state for a stream based the policy in the listener
3191  * and the actions in the ip_recv_attr_t.
3192  * Called directly from TCP and SCTP.
3193  */
3194 boolean_t
3195 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3196 {
3197 	ASSERT(lconnp->conn_policy != NULL);
3198 	ASSERT(connp->conn_policy == NULL);
3199 
3200 	IPPH_REFHOLD(lconnp->conn_policy);
3201 	connp->conn_policy = lconnp->conn_policy;
3202 
3203 	if (ira->ira_ipsec_action != NULL) {
3204 		if (connp->conn_latch == NULL) {
3205 			connp->conn_latch = iplatch_create();
3206 			if (connp->conn_latch == NULL)
3207 				return (B_FALSE);
3208 		}
3209 		ipsec_latch_inbound(connp, ira);
3210 	}
3211 	return (B_TRUE);
3212 }
3213 
3214 /*
3215  * Verify whether or not the IP address is a valid local address.
3216  * Could be a unicast, including one for a down interface.
3217  * If allow_mcbc then a multicast or broadcast address is also
3218  * acceptable.
3219  *
3220  * In the case of a broadcast/multicast address, however, the
3221  * upper protocol is expected to reset the src address
3222  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3223  * no packets are emitted with broadcast/multicast address as
3224  * source address (that violates hosts requirements RFC 1122)
3225  * The addresses valid for bind are:
3226  *	(1) - INADDR_ANY (0)
3227  *	(2) - IP address of an UP interface
3228  *	(3) - IP address of a DOWN interface
3229  *	(4) - valid local IP broadcast addresses. In this case
3230  *	the conn will only receive packets destined to
3231  *	the specified broadcast address.
3232  *	(5) - a multicast address. In this case
3233  *	the conn will only receive packets destined to
3234  *	the specified multicast address. Note: the
3235  *	application still has to issue an
3236  *	IP_ADD_MEMBERSHIP socket option.
3237  *
3238  * In all the above cases, the bound address must be valid in the current zone.
3239  * When the address is loopback, multicast or broadcast, there might be many
3240  * matching IREs so bind has to look up based on the zone.
3241  */
3242 ip_laddr_t
3243 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3244     ip_stack_t *ipst, boolean_t allow_mcbc)
3245 {
3246 	ire_t *src_ire;
3247 
3248 	ASSERT(src_addr != INADDR_ANY);
3249 
3250 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3251 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3252 
3253 	/*
3254 	 * If an address other than in6addr_any is requested,
3255 	 * we verify that it is a valid address for bind
3256 	 * Note: Following code is in if-else-if form for
3257 	 * readability compared to a condition check.
3258 	 */
3259 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3260 		/*
3261 		 * (2) Bind to address of local UP interface
3262 		 */
3263 		ire_refrele(src_ire);
3264 		return (IPVL_UNICAST_UP);
3265 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3266 		/*
3267 		 * (4) Bind to broadcast address
3268 		 */
3269 		ire_refrele(src_ire);
3270 		if (allow_mcbc)
3271 			return (IPVL_BCAST);
3272 		else
3273 			return (IPVL_BAD);
3274 	} else if (CLASSD(src_addr)) {
3275 		/* (5) bind to multicast address. */
3276 		if (src_ire != NULL)
3277 			ire_refrele(src_ire);
3278 
3279 		if (allow_mcbc)
3280 			return (IPVL_MCAST);
3281 		else
3282 			return (IPVL_BAD);
3283 	} else {
3284 		ipif_t *ipif;
3285 
3286 		/*
3287 		 * (3) Bind to address of local DOWN interface?
3288 		 * (ipif_lookup_addr() looks up all interfaces
3289 		 * but we do not get here for UP interfaces
3290 		 * - case (2) above)
3291 		 */
3292 		if (src_ire != NULL)
3293 			ire_refrele(src_ire);
3294 
3295 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3296 		if (ipif == NULL)
3297 			return (IPVL_BAD);
3298 
3299 		/* Not a useful source? */
3300 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3301 			ipif_refrele(ipif);
3302 			return (IPVL_BAD);
3303 		}
3304 		ipif_refrele(ipif);
3305 		return (IPVL_UNICAST_DOWN);
3306 	}
3307 }
3308 
3309 /*
3310  * Insert in the bind fanout for IPv4 and IPv6.
3311  * The caller should already have used ip_laddr_verify_v*() before calling
3312  * this.
3313  */
3314 int
3315 ip_laddr_fanout_insert(conn_t *connp)
3316 {
3317 	int		error;
3318 
3319 	/*
3320 	 * Allow setting new policies. For example, disconnects result
3321 	 * in us being called. As we would have set conn_policy_cached
3322 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3323 	 * can change after the disconnect.
3324 	 */
3325 	connp->conn_policy_cached = B_FALSE;
3326 
3327 	error = ipcl_bind_insert(connp);
3328 	if (error != 0) {
3329 		if (connp->conn_anon_port) {
3330 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3331 			    connp->conn_mlp_type, connp->conn_proto,
3332 			    ntohs(connp->conn_lport), B_FALSE);
3333 		}
3334 		connp->conn_mlp_type = mlptSingle;
3335 	}
3336 	return (error);
3337 }
3338 
3339 /*
3340  * Verify that both the source and destination addresses are valid. If
3341  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3342  * i.e. have no route to it.  Protocols like TCP want to verify destination
3343  * reachability, while tunnels do not.
3344  *
3345  * Determine the route, the interface, and (optionally) the source address
3346  * to use to reach a given destination.
3347  * Note that we allow connect to broadcast and multicast addresses when
3348  * IPDF_ALLOW_MCBC is set.
3349  * first_hop and dst_addr are normally the same, but if source routing
3350  * they will differ; in that case the first_hop is what we'll use for the
3351  * routing lookup but the dce and label checks will be done on dst_addr,
3352  *
3353  * If uinfo is set, then we fill in the best available information
3354  * we have for the destination. This is based on (in priority order) any
3355  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3356  * ill_mtu/ill_mc_mtu.
3357  *
3358  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3359  * always do the label check on dst_addr.
3360  */
3361 int
3362 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3363     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3364 {
3365 	ire_t		*ire = NULL;
3366 	int		error = 0;
3367 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3368 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3369 	ip_stack_t	*ipst = ixa->ixa_ipst;
3370 	dce_t		*dce;
3371 	uint_t		pmtu;
3372 	uint_t		generation;
3373 	nce_t		*nce;
3374 	ill_t		*ill = NULL;
3375 	boolean_t	multirt = B_FALSE;
3376 
3377 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3378 
3379 	/*
3380 	 * We never send to zero; the ULPs map it to the loopback address.
3381 	 * We can't allow it since we use zero to mean unitialized in some
3382 	 * places.
3383 	 */
3384 	ASSERT(dst_addr != INADDR_ANY);
3385 
3386 	if (is_system_labeled()) {
3387 		ts_label_t *tsl = NULL;
3388 
3389 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3390 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3391 		if (error != 0)
3392 			return (error);
3393 		if (tsl != NULL) {
3394 			/* Update the label */
3395 			ip_xmit_attr_replace_tsl(ixa, tsl);
3396 		}
3397 	}
3398 
3399 	setsrc = INADDR_ANY;
3400 	/*
3401 	 * Select a route; For IPMP interfaces, we would only select
3402 	 * a "hidden" route (i.e., going through a specific under_ill)
3403 	 * if ixa_ifindex has been specified.
3404 	 */
3405 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3406 	    &generation, &setsrc, &error, &multirt);
3407 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3408 	if (error != 0)
3409 		goto bad_addr;
3410 
3411 	/*
3412 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3413 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3414 	 * Otherwise the destination needn't be reachable.
3415 	 *
3416 	 * If we match on a reject or black hole, then we've got a
3417 	 * local failure.  May as well fail out the connect() attempt,
3418 	 * since it's never going to succeed.
3419 	 */
3420 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3421 		/*
3422 		 * If we're verifying destination reachability, we always want
3423 		 * to complain here.
3424 		 *
3425 		 * If we're not verifying destination reachability but the
3426 		 * destination has a route, we still want to fail on the
3427 		 * temporary address and broadcast address tests.
3428 		 *
3429 		 * In both cases do we let the code continue so some reasonable
3430 		 * information is returned to the caller. That enables the
3431 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3432 		 * use the generation mismatch path to check for the unreachable
3433 		 * case thereby avoiding any specific check in the main path.
3434 		 */
3435 		ASSERT(generation == IRE_GENERATION_VERIFY);
3436 		if (flags & IPDF_VERIFY_DST) {
3437 			/*
3438 			 * Set errno but continue to set up ixa_ire to be
3439 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3440 			 * That allows callers to use ip_output to get an
3441 			 * ICMP error back.
3442 			 */
3443 			if (!(ire->ire_type & IRE_HOST))
3444 				error = ENETUNREACH;
3445 			else
3446 				error = EHOSTUNREACH;
3447 		}
3448 	}
3449 
3450 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3451 	    !(flags & IPDF_ALLOW_MCBC)) {
3452 		ire_refrele(ire);
3453 		ire = ire_reject(ipst, B_FALSE);
3454 		generation = IRE_GENERATION_VERIFY;
3455 		error = ENETUNREACH;
3456 	}
3457 
3458 	/* Cache things */
3459 	if (ixa->ixa_ire != NULL)
3460 		ire_refrele_notr(ixa->ixa_ire);
3461 #ifdef DEBUG
3462 	ire_refhold_notr(ire);
3463 	ire_refrele(ire);
3464 #endif
3465 	ixa->ixa_ire = ire;
3466 	ixa->ixa_ire_generation = generation;
3467 
3468 	/*
3469 	 * Ensure that ixa_dce is always set any time that ixa_ire is set,
3470 	 * since some callers will send a packet to conn_ip_output() even if
3471 	 * there's an error.
3472 	 */
3473 	if (flags & IPDF_UNIQUE_DCE) {
3474 		/* Fallback to the default dce if allocation fails */
3475 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3476 		if (dce != NULL)
3477 			generation = dce->dce_generation;
3478 		else
3479 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3480 	} else {
3481 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3482 	}
3483 	ASSERT(dce != NULL);
3484 	if (ixa->ixa_dce != NULL)
3485 		dce_refrele_notr(ixa->ixa_dce);
3486 #ifdef DEBUG
3487 	dce_refhold_notr(dce);
3488 	dce_refrele(dce);
3489 #endif
3490 	ixa->ixa_dce = dce;
3491 	ixa->ixa_dce_generation = generation;
3492 
3493 	/*
3494 	 * For multicast with multirt we have a flag passed back from
3495 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3496 	 * possible multicast address.
3497 	 * We also need a flag for multicast since we can't check
3498 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3499 	 */
3500 	if (multirt) {
3501 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3502 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3503 	} else {
3504 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3505 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3506 	}
3507 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3508 		/* Get an nce to cache. */
3509 		nce = ire_to_nce(ire, firsthop, NULL);
3510 		if (nce == NULL) {
3511 			/* Allocation failure? */
3512 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3513 		} else {
3514 			if (ixa->ixa_nce != NULL)
3515 				nce_refrele(ixa->ixa_nce);
3516 			ixa->ixa_nce = nce;
3517 		}
3518 	}
3519 
3520 	/*
3521 	 * If the source address is a loopback address, the
3522 	 * destination had best be local or multicast.
3523 	 * If we are sending to an IRE_LOCAL using a loopback source then
3524 	 * it had better be the same zoneid.
3525 	 */
3526 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3527 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3528 			ire = NULL;	/* Stored in ixa_ire */
3529 			error = EADDRNOTAVAIL;
3530 			goto bad_addr;
3531 		}
3532 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3533 			ire = NULL;	/* Stored in ixa_ire */
3534 			error = EADDRNOTAVAIL;
3535 			goto bad_addr;
3536 		}
3537 	}
3538 	if (ire->ire_type & IRE_BROADCAST) {
3539 		/*
3540 		 * If the ULP didn't have a specified source, then we
3541 		 * make sure we reselect the source when sending
3542 		 * broadcasts out different interfaces.
3543 		 */
3544 		if (flags & IPDF_SELECT_SRC)
3545 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3546 		else
3547 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3548 	}
3549 
3550 	/*
3551 	 * Does the caller want us to pick a source address?
3552 	 */
3553 	if (flags & IPDF_SELECT_SRC) {
3554 		ipaddr_t	src_addr;
3555 
3556 		/*
3557 		 * We use use ire_nexthop_ill to avoid the under ipmp
3558 		 * interface for source address selection. Note that for ipmp
3559 		 * probe packets, ixa_ifindex would have been specified, and
3560 		 * the ip_select_route() invocation would have picked an ire
3561 		 * will ire_ill pointing at an under interface.
3562 		 */
3563 		ill = ire_nexthop_ill(ire);
3564 
3565 		/* If unreachable we have no ill but need some source */
3566 		if (ill == NULL) {
3567 			src_addr = htonl(INADDR_LOOPBACK);
3568 			/* Make sure we look for a better source address */
3569 			generation = SRC_GENERATION_VERIFY;
3570 		} else {
3571 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3572 			    ixa->ixa_multicast_ifaddr, zoneid,
3573 			    ipst, &src_addr, &generation, NULL);
3574 			if (error != 0) {
3575 				ire = NULL;	/* Stored in ixa_ire */
3576 				goto bad_addr;
3577 			}
3578 		}
3579 
3580 		/*
3581 		 * We allow the source address to to down.
3582 		 * However, we check that we don't use the loopback address
3583 		 * as a source when sending out on the wire.
3584 		 */
3585 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3586 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3587 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3588 			ire = NULL;	/* Stored in ixa_ire */
3589 			error = EADDRNOTAVAIL;
3590 			goto bad_addr;
3591 		}
3592 
3593 		*src_addrp = src_addr;
3594 		ixa->ixa_src_generation = generation;
3595 	}
3596 
3597 	/*
3598 	 * Make sure we don't leave an unreachable ixa_nce in place
3599 	 * since ip_select_route is used when we unplumb i.e., remove
3600 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3601 	 */
3602 	nce = ixa->ixa_nce;
3603 	if (nce != NULL && nce->nce_is_condemned) {
3604 		nce_refrele(nce);
3605 		ixa->ixa_nce = NULL;
3606 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3607 	}
3608 
3609 	/*
3610 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3611 	 * However, we can't do it for IPv4 multicast or broadcast.
3612 	 */
3613 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3614 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3615 
3616 	/*
3617 	 * Set initial value for fragmentation limit. Either conn_ip_output
3618 	 * or ULP might updates it when there are routing changes.
3619 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3620 	 */
3621 	pmtu = ip_get_pmtu(ixa);
3622 	ixa->ixa_fragsize = pmtu;
3623 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3624 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3625 		ixa->ixa_pmtu = pmtu;
3626 
3627 	/*
3628 	 * Extract information useful for some transports.
3629 	 * First we look for DCE metrics. Then we take what we have in
3630 	 * the metrics in the route, where the offlink is used if we have
3631 	 * one.
3632 	 */
3633 	if (uinfo != NULL) {
3634 		bzero(uinfo, sizeof (*uinfo));
3635 
3636 		if (dce->dce_flags & DCEF_UINFO)
3637 			*uinfo = dce->dce_uinfo;
3638 
3639 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3640 
3641 		/* Allow ire_metrics to decrease the path MTU from above */
3642 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3643 			uinfo->iulp_mtu = pmtu;
3644 
3645 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3646 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3647 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3648 	}
3649 
3650 	if (ill != NULL)
3651 		ill_refrele(ill);
3652 
3653 	return (error);
3654 
3655 bad_addr:
3656 	if (ire != NULL)
3657 		ire_refrele(ire);
3658 
3659 	if (ill != NULL)
3660 		ill_refrele(ill);
3661 
3662 	/*
3663 	 * Make sure we don't leave an unreachable ixa_nce in place
3664 	 * since ip_select_route is used when we unplumb i.e., remove
3665 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3666 	 */
3667 	nce = ixa->ixa_nce;
3668 	if (nce != NULL && nce->nce_is_condemned) {
3669 		nce_refrele(nce);
3670 		ixa->ixa_nce = NULL;
3671 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3672 	}
3673 
3674 	return (error);
3675 }
3676 
3677 
3678 /*
3679  * Get the base MTU for the case when path MTU discovery is not used.
3680  * Takes the MTU of the IRE into account.
3681  */
3682 uint_t
3683 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3684 {
3685 	uint_t mtu;
3686 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3687 
3688 	if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST))
3689 		mtu = ill->ill_mc_mtu;
3690 	else
3691 		mtu = ill->ill_mtu;
3692 
3693 	if (iremtu != 0 && iremtu < mtu)
3694 		mtu = iremtu;
3695 
3696 	return (mtu);
3697 }
3698 
3699 /*
3700  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3701  * Assumes that ixa_ire, dce, and nce have already been set up.
3702  *
3703  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3704  * We avoid path MTU discovery if it is disabled with ndd.
3705  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3706  *
3707  * NOTE: We also used to turn it off for source routed packets. That
3708  * is no longer required since the dce is per final destination.
3709  */
3710 uint_t
3711 ip_get_pmtu(ip_xmit_attr_t *ixa)
3712 {
3713 	ip_stack_t	*ipst = ixa->ixa_ipst;
3714 	dce_t		*dce;
3715 	nce_t		*nce;
3716 	ire_t		*ire;
3717 	uint_t		pmtu;
3718 
3719 	ire = ixa->ixa_ire;
3720 	dce = ixa->ixa_dce;
3721 	nce = ixa->ixa_nce;
3722 
3723 	/*
3724 	 * If path MTU discovery has been turned off by ndd, then we ignore
3725 	 * any dce_pmtu and for IPv4 we will not set DF.
3726 	 */
3727 	if (!ipst->ips_ip_path_mtu_discovery)
3728 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3729 
3730 	pmtu = IP_MAXPACKET;
3731 	/*
3732 	 * Decide whether whether IPv4 sets DF
3733 	 * For IPv6 "no DF" means to use the 1280 mtu
3734 	 */
3735 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3736 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3737 	} else {
3738 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3739 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3740 			pmtu = IPV6_MIN_MTU;
3741 	}
3742 
3743 	/* Check if the PMTU is to old before we use it */
3744 	if ((dce->dce_flags & DCEF_PMTU) &&
3745 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3746 	    ipst->ips_ip_pathmtu_interval) {
3747 		/*
3748 		 * Older than 20 minutes. Drop the path MTU information.
3749 		 */
3750 		mutex_enter(&dce->dce_lock);
3751 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3752 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3753 		mutex_exit(&dce->dce_lock);
3754 		dce_increment_generation(dce);
3755 	}
3756 
3757 	/* The metrics on the route can lower the path MTU */
3758 	if (ire->ire_metrics.iulp_mtu != 0 &&
3759 	    ire->ire_metrics.iulp_mtu < pmtu)
3760 		pmtu = ire->ire_metrics.iulp_mtu;
3761 
3762 	/*
3763 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3764 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3765 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3766 	 */
3767 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3768 		if (dce->dce_flags & DCEF_PMTU) {
3769 			if (dce->dce_pmtu < pmtu)
3770 				pmtu = dce->dce_pmtu;
3771 
3772 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3773 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3774 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3775 			} else {
3776 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3777 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3778 			}
3779 		} else {
3780 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3781 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3782 		}
3783 	}
3784 
3785 	/*
3786 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3787 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3788 	 * mtu as IRE_LOOPBACK.
3789 	 */
3790 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3791 		uint_t loopback_mtu;
3792 
3793 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3794 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3795 
3796 		if (loopback_mtu < pmtu)
3797 			pmtu = loopback_mtu;
3798 	} else if (nce != NULL) {
3799 		/*
3800 		 * Make sure we don't exceed the interface MTU.
3801 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3802 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3803 		 * to tell the transport something larger than zero.
3804 		 */
3805 		if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST)) {
3806 			if (nce->nce_common->ncec_ill->ill_mc_mtu < pmtu)
3807 				pmtu = nce->nce_common->ncec_ill->ill_mc_mtu;
3808 			if (nce->nce_common->ncec_ill != nce->nce_ill &&
3809 			    nce->nce_ill->ill_mc_mtu < pmtu) {
3810 				/*
3811 				 * for interfaces in an IPMP group, the mtu of
3812 				 * the nce_ill (under_ill) could be different
3813 				 * from the mtu of the ncec_ill, so we take the
3814 				 * min of the two.
3815 				 */
3816 				pmtu = nce->nce_ill->ill_mc_mtu;
3817 			}
3818 		} else {
3819 			if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3820 				pmtu = nce->nce_common->ncec_ill->ill_mtu;
3821 			if (nce->nce_common->ncec_ill != nce->nce_ill &&
3822 			    nce->nce_ill->ill_mtu < pmtu) {
3823 				/*
3824 				 * for interfaces in an IPMP group, the mtu of
3825 				 * the nce_ill (under_ill) could be different
3826 				 * from the mtu of the ncec_ill, so we take the
3827 				 * min of the two.
3828 				 */
3829 				pmtu = nce->nce_ill->ill_mtu;
3830 			}
3831 		}
3832 	}
3833 
3834 	/*
3835 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3836 	 * Only applies to IPv6.
3837 	 */
3838 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3839 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3840 			switch (ixa->ixa_use_min_mtu) {
3841 			case IPV6_USE_MIN_MTU_MULTICAST:
3842 				if (ire->ire_type & IRE_MULTICAST)
3843 					pmtu = IPV6_MIN_MTU;
3844 				break;
3845 			case IPV6_USE_MIN_MTU_ALWAYS:
3846 				pmtu = IPV6_MIN_MTU;
3847 				break;
3848 			case IPV6_USE_MIN_MTU_NEVER:
3849 				break;
3850 			}
3851 		} else {
3852 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3853 			if (ire->ire_type & IRE_MULTICAST)
3854 				pmtu = IPV6_MIN_MTU;
3855 		}
3856 	}
3857 
3858 	/*
3859 	 * After receiving an ICMPv6 "packet too big" message with a
3860 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3861 	 * will insert a 8-byte fragment header in every packet. We compensate
3862 	 * for those cases by returning a smaller path MTU to the ULP.
3863 	 *
3864 	 * In the case of CGTP then ip_output will add a fragment header.
3865 	 * Make sure there is room for it by telling a smaller number
3866 	 * to the transport.
3867 	 *
3868 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3869 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3870 	 * which is the size of the packets it can send.
3871 	 */
3872 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3873 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
3874 		    (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)
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 	ret = untimeout(ipst->ips_igmp_timeout_id);
4423 	if (ret == -1) {
4424 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4425 	} else {
4426 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4427 		ipst->ips_igmp_timeout_id = 0;
4428 	}
4429 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4430 	if (ret == -1) {
4431 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4432 	} else {
4433 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4434 		ipst->ips_igmp_slowtimeout_id = 0;
4435 	}
4436 	ret = untimeout(ipst->ips_mld_timeout_id);
4437 	if (ret == -1) {
4438 		ASSERT(ipst->ips_mld_timeout_id == 0);
4439 	} else {
4440 		ASSERT(ipst->ips_mld_timeout_id != 0);
4441 		ipst->ips_mld_timeout_id = 0;
4442 	}
4443 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4444 	if (ret == -1) {
4445 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4446 	} else {
4447 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4448 		ipst->ips_mld_slowtimeout_id = 0;
4449 	}
4450 
4451 	ip_ire_fini(ipst);
4452 	ip6_asp_free(ipst);
4453 	conn_drain_fini(ipst);
4454 	ipcl_destroy(ipst);
4455 
4456 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4457 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4458 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4459 	ipst->ips_ndp4 = NULL;
4460 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4461 	ipst->ips_ndp6 = NULL;
4462 
4463 	if (ipst->ips_loopback_ksp != NULL) {
4464 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4465 		ipst->ips_loopback_ksp = NULL;
4466 	}
4467 
4468 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4469 	cv_destroy(&ipst->ips_capab_taskq_cv);
4470 
4471 	rw_destroy(&ipst->ips_srcid_lock);
4472 
4473 	mutex_destroy(&ipst->ips_ip_mi_lock);
4474 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4475 
4476 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4477 	mutex_destroy(&ipst->ips_mld_timer_lock);
4478 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4479 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4480 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4481 	rw_destroy(&ipst->ips_ill_g_lock);
4482 
4483 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4484 	ipst->ips_phyint_g_list = NULL;
4485 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4486 	ipst->ips_ill_g_heads = NULL;
4487 
4488 	ldi_ident_release(ipst->ips_ldi_ident);
4489 	kmem_free(ipst, sizeof (*ipst));
4490 }
4491 
4492 /*
4493  * This function is called from the TSD destructor, and is used to debug
4494  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4495  * details.
4496  */
4497 static void
4498 ip_thread_exit(void *phash)
4499 {
4500 	th_hash_t *thh = phash;
4501 
4502 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4503 	list_remove(&ip_thread_list, thh);
4504 	rw_exit(&ip_thread_rwlock);
4505 	mod_hash_destroy_hash(thh->thh_hash);
4506 	kmem_free(thh, sizeof (*thh));
4507 }
4508 
4509 /*
4510  * Called when the IP kernel module is loaded into the kernel
4511  */
4512 void
4513 ip_ddi_init(void)
4514 {
4515 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4516 
4517 	/*
4518 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4519 	 * initial devices: ip, ip6, tcp, tcp6.
4520 	 */
4521 	/*
4522 	 * If this is a 64-bit kernel, then create two separate arenas -
4523 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4524 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4525 	 */
4526 	ip_minor_arena_la = NULL;
4527 	ip_minor_arena_sa = NULL;
4528 #if defined(_LP64)
4529 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4530 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4531 		cmn_err(CE_PANIC,
4532 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4533 	}
4534 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4535 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4536 		cmn_err(CE_PANIC,
4537 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4538 	}
4539 #else
4540 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4541 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4542 		cmn_err(CE_PANIC,
4543 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4544 	}
4545 #endif
4546 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4547 
4548 	ipcl_g_init();
4549 	ip_ire_g_init();
4550 	ip_net_g_init();
4551 
4552 #ifdef DEBUG
4553 	tsd_create(&ip_thread_data, ip_thread_exit);
4554 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4555 	list_create(&ip_thread_list, sizeof (th_hash_t),
4556 	    offsetof(th_hash_t, thh_link));
4557 #endif
4558 	ipsec_policy_g_init();
4559 	tcp_ddi_g_init();
4560 	sctp_ddi_g_init();
4561 	dce_g_init();
4562 
4563 	/*
4564 	 * We want to be informed each time a stack is created or
4565 	 * destroyed in the kernel, so we can maintain the
4566 	 * set of udp_stack_t's.
4567 	 */
4568 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4569 	    ip_stack_fini);
4570 
4571 	tnet_init();
4572 
4573 	udp_ddi_g_init();
4574 	rts_ddi_g_init();
4575 	icmp_ddi_g_init();
4576 	ilb_ddi_g_init();
4577 
4578 	/* This needs to be called after all transports are initialized. */
4579 	mutex_enter(&cpu_lock);
4580 	register_cpu_setup_func(ip_tp_cpu_update, NULL);
4581 	mutex_exit(&cpu_lock);
4582 }
4583 
4584 /*
4585  * Initialize the IP stack instance.
4586  */
4587 static void *
4588 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4589 {
4590 	ip_stack_t	*ipst;
4591 	size_t		arrsz;
4592 	major_t		major;
4593 
4594 #ifdef NS_DEBUG
4595 	printf("ip_stack_init(stack %d)\n", stackid);
4596 #endif
4597 
4598 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4599 	ipst->ips_netstack = ns;
4600 
4601 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4602 	    KM_SLEEP);
4603 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4604 	    KM_SLEEP);
4605 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4606 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4607 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4608 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4609 
4610 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4611 	ipst->ips_igmp_deferred_next = INFINITY;
4612 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4613 	ipst->ips_mld_deferred_next = INFINITY;
4614 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4615 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4616 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4617 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4618 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4619 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4620 
4621 	ipcl_init(ipst);
4622 	ip_ire_init(ipst);
4623 	ip6_asp_init(ipst);
4624 	ipif_init(ipst);
4625 	conn_drain_init(ipst);
4626 	ip_mrouter_stack_init(ipst);
4627 	dce_stack_init(ipst);
4628 
4629 	ipst->ips_ip_multirt_log_interval = 1000;
4630 
4631 	ipst->ips_ill_index = 1;
4632 
4633 	ipst->ips_saved_ip_forwarding = -1;
4634 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4635 
4636 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4637 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4638 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4639 
4640 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4641 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4642 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4643 	ipst->ips_ip6_kstat =
4644 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4645 
4646 	ipst->ips_ip_src_id = 1;
4647 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4648 
4649 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4650 
4651 	ip_net_init(ipst, ns);
4652 	ipv4_hook_init(ipst);
4653 	ipv6_hook_init(ipst);
4654 	arp_hook_init(ipst);
4655 	ipmp_init(ipst);
4656 	ipobs_init(ipst);
4657 
4658 	/*
4659 	 * Create the taskq dispatcher thread and initialize related stuff.
4660 	 */
4661 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4662 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4663 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4664 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4665 
4666 	major = mod_name_to_major(INET_NAME);
4667 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4668 	return (ipst);
4669 }
4670 
4671 /*
4672  * Allocate and initialize a DLPI template of the specified length.  (May be
4673  * called as writer.)
4674  */
4675 mblk_t *
4676 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4677 {
4678 	mblk_t	*mp;
4679 
4680 	mp = allocb(len, BPRI_MED);
4681 	if (!mp)
4682 		return (NULL);
4683 
4684 	/*
4685 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4686 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4687 	 * that other DLPI are M_PROTO.
4688 	 */
4689 	if (prim == DL_INFO_REQ) {
4690 		mp->b_datap->db_type = M_PCPROTO;
4691 	} else {
4692 		mp->b_datap->db_type = M_PROTO;
4693 	}
4694 
4695 	mp->b_wptr = mp->b_rptr + len;
4696 	bzero(mp->b_rptr, len);
4697 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4698 	return (mp);
4699 }
4700 
4701 /*
4702  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4703  */
4704 mblk_t *
4705 ip_dlnotify_alloc(uint_t notification, uint_t data)
4706 {
4707 	dl_notify_ind_t	*notifyp;
4708 	mblk_t		*mp;
4709 
4710 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4711 		return (NULL);
4712 
4713 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4714 	notifyp->dl_notification = notification;
4715 	notifyp->dl_data = data;
4716 	return (mp);
4717 }
4718 
4719 mblk_t *
4720 ip_dlnotify_alloc2(uint_t notification, uint_t data1, uint_t data2)
4721 {
4722 	dl_notify_ind_t	*notifyp;
4723 	mblk_t		*mp;
4724 
4725 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4726 		return (NULL);
4727 
4728 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4729 	notifyp->dl_notification = notification;
4730 	notifyp->dl_data1 = data1;
4731 	notifyp->dl_data2 = data2;
4732 	return (mp);
4733 }
4734 
4735 /*
4736  * Debug formatting routine.  Returns a character string representation of the
4737  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4738  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4739  *
4740  * Once the ndd table-printing interfaces are removed, this can be changed to
4741  * standard dotted-decimal form.
4742  */
4743 char *
4744 ip_dot_addr(ipaddr_t addr, char *buf)
4745 {
4746 	uint8_t *ap = (uint8_t *)&addr;
4747 
4748 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4749 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4750 	return (buf);
4751 }
4752 
4753 /*
4754  * Write the given MAC address as a printable string in the usual colon-
4755  * separated format.
4756  */
4757 const char *
4758 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4759 {
4760 	char *bp;
4761 
4762 	if (alen == 0 || buflen < 4)
4763 		return ("?");
4764 	bp = buf;
4765 	for (;;) {
4766 		/*
4767 		 * If there are more MAC address bytes available, but we won't
4768 		 * have any room to print them, then add "..." to the string
4769 		 * instead.  See below for the 'magic number' explanation.
4770 		 */
4771 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4772 			(void) strcpy(bp, "...");
4773 			break;
4774 		}
4775 		(void) sprintf(bp, "%02x", *addr++);
4776 		bp += 2;
4777 		if (--alen == 0)
4778 			break;
4779 		*bp++ = ':';
4780 		buflen -= 3;
4781 		/*
4782 		 * At this point, based on the first 'if' statement above,
4783 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4784 		 * buflen >= 4.  The first case leaves room for the final "xx"
4785 		 * number and trailing NUL byte.  The second leaves room for at
4786 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4787 		 * that statement.
4788 		 */
4789 	}
4790 	return (buf);
4791 }
4792 
4793 /*
4794  * Called when it is conceptually a ULP that would sent the packet
4795  * e.g., port unreachable and protocol unreachable. Check that the packet
4796  * would have passed the IPsec global policy before sending the error.
4797  *
4798  * Send an ICMP error after patching up the packet appropriately.
4799  * Uses ip_drop_input and bumps the appropriate MIB.
4800  */
4801 void
4802 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4803     ip_recv_attr_t *ira)
4804 {
4805 	ipha_t		*ipha;
4806 	boolean_t	secure;
4807 	ill_t		*ill = ira->ira_ill;
4808 	ip_stack_t	*ipst = ill->ill_ipst;
4809 	netstack_t	*ns = ipst->ips_netstack;
4810 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4811 
4812 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4813 
4814 	/*
4815 	 * We are generating an icmp error for some inbound packet.
4816 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4817 	 * Before we generate an error, check with global policy
4818 	 * to see whether this is allowed to enter the system. As
4819 	 * there is no "conn", we are checking with global policy.
4820 	 */
4821 	ipha = (ipha_t *)mp->b_rptr;
4822 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4823 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4824 		if (mp == NULL)
4825 			return;
4826 	}
4827 
4828 	/* We never send errors for protocols that we do implement */
4829 	if (ira->ira_protocol == IPPROTO_ICMP ||
4830 	    ira->ira_protocol == IPPROTO_IGMP) {
4831 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4832 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4833 		freemsg(mp);
4834 		return;
4835 	}
4836 	/*
4837 	 * Have to correct checksum since
4838 	 * the packet might have been
4839 	 * fragmented and the reassembly code in ip_rput
4840 	 * does not restore the IP checksum.
4841 	 */
4842 	ipha->ipha_hdr_checksum = 0;
4843 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4844 
4845 	switch (icmp_type) {
4846 	case ICMP_DEST_UNREACHABLE:
4847 		switch (icmp_code) {
4848 		case ICMP_PROTOCOL_UNREACHABLE:
4849 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4850 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4851 			break;
4852 		case ICMP_PORT_UNREACHABLE:
4853 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4854 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4855 			break;
4856 		}
4857 
4858 		icmp_unreachable(mp, icmp_code, ira);
4859 		break;
4860 	default:
4861 #ifdef DEBUG
4862 		panic("ip_fanout_send_icmp_v4: wrong type");
4863 		/*NOTREACHED*/
4864 #else
4865 		freemsg(mp);
4866 		break;
4867 #endif
4868 	}
4869 }
4870 
4871 /*
4872  * Used to send an ICMP error message when a packet is received for
4873  * a protocol that is not supported. The mblk passed as argument
4874  * is consumed by this function.
4875  */
4876 void
4877 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4878 {
4879 	ipha_t		*ipha;
4880 
4881 	ipha = (ipha_t *)mp->b_rptr;
4882 	if (ira->ira_flags & IRAF_IS_IPV4) {
4883 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4884 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4885 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4886 	} else {
4887 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4888 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4889 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4890 	}
4891 }
4892 
4893 /*
4894  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4895  * Handles IPv4 and IPv6.
4896  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4897  * Caller is responsible for dropping references to the conn.
4898  */
4899 void
4900 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4901     ip_recv_attr_t *ira)
4902 {
4903 	ill_t		*ill = ira->ira_ill;
4904 	ip_stack_t	*ipst = ill->ill_ipst;
4905 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4906 	boolean_t	secure;
4907 	uint_t		protocol = ira->ira_protocol;
4908 	iaflags_t	iraflags = ira->ira_flags;
4909 	queue_t		*rq;
4910 
4911 	secure = iraflags & IRAF_IPSEC_SECURE;
4912 
4913 	rq = connp->conn_rq;
4914 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4915 		switch (protocol) {
4916 		case IPPROTO_ICMPV6:
4917 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4918 			break;
4919 		case IPPROTO_ICMP:
4920 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4921 			break;
4922 		default:
4923 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4924 			break;
4925 		}
4926 		freemsg(mp);
4927 		return;
4928 	}
4929 
4930 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4931 
4932 	if (((iraflags & IRAF_IS_IPV4) ?
4933 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4934 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4935 	    secure) {
4936 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4937 		    ip6h, ira);
4938 		if (mp == NULL) {
4939 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4940 			/* Note that mp is NULL */
4941 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4942 			return;
4943 		}
4944 	}
4945 
4946 	if (iraflags & IRAF_ICMP_ERROR) {
4947 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4948 	} else {
4949 		ill_t *rill = ira->ira_rill;
4950 
4951 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4952 		ira->ira_ill = ira->ira_rill = NULL;
4953 		/* Send it upstream */
4954 		(connp->conn_recv)(connp, mp, NULL, ira);
4955 		ira->ira_ill = ill;
4956 		ira->ira_rill = rill;
4957 	}
4958 }
4959 
4960 /*
4961  * Handle protocols with which IP is less intimate.  There
4962  * can be more than one stream bound to a particular
4963  * protocol.  When this is the case, normally each one gets a copy
4964  * of any incoming packets.
4965  *
4966  * IPsec NOTE :
4967  *
4968  * Don't allow a secure packet going up a non-secure connection.
4969  * We don't allow this because
4970  *
4971  * 1) Reply might go out in clear which will be dropped at
4972  *    the sending side.
4973  * 2) If the reply goes out in clear it will give the
4974  *    adversary enough information for getting the key in
4975  *    most of the cases.
4976  *
4977  * Moreover getting a secure packet when we expect clear
4978  * implies that SA's were added without checking for
4979  * policy on both ends. This should not happen once ISAKMP
4980  * is used to negotiate SAs as SAs will be added only after
4981  * verifying the policy.
4982  *
4983  * Zones notes:
4984  * Earlier in ip_input on a system with multiple shared-IP zones we
4985  * duplicate the multicast and broadcast packets and send them up
4986  * with each explicit zoneid that exists on that ill.
4987  * This means that here we can match the zoneid with SO_ALLZONES being special.
4988  */
4989 void
4990 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
4991 {
4992 	mblk_t		*mp1;
4993 	ipaddr_t	laddr;
4994 	conn_t		*connp, *first_connp, *next_connp;
4995 	connf_t		*connfp;
4996 	ill_t		*ill = ira->ira_ill;
4997 	ip_stack_t	*ipst = ill->ill_ipst;
4998 
4999 	laddr = ipha->ipha_dst;
5000 
5001 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
5002 	mutex_enter(&connfp->connf_lock);
5003 	connp = connfp->connf_head;
5004 	for (connp = connfp->connf_head; connp != NULL;
5005 	    connp = connp->conn_next) {
5006 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5007 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5008 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5009 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
5010 			break;
5011 		}
5012 	}
5013 
5014 	if (connp == NULL) {
5015 		/*
5016 		 * No one bound to these addresses.  Is
5017 		 * there a client that wants all
5018 		 * unclaimed datagrams?
5019 		 */
5020 		mutex_exit(&connfp->connf_lock);
5021 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5022 		    ICMP_PROTOCOL_UNREACHABLE, ira);
5023 		return;
5024 	}
5025 
5026 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5027 
5028 	CONN_INC_REF(connp);
5029 	first_connp = connp;
5030 	connp = connp->conn_next;
5031 
5032 	for (;;) {
5033 		while (connp != NULL) {
5034 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5035 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5036 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5037 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5038 			    ira, connp)))
5039 				break;
5040 			connp = connp->conn_next;
5041 		}
5042 
5043 		if (connp == NULL) {
5044 			/* No more interested clients */
5045 			connp = first_connp;
5046 			break;
5047 		}
5048 		if (((mp1 = dupmsg(mp)) == NULL) &&
5049 		    ((mp1 = copymsg(mp)) == NULL)) {
5050 			/* Memory allocation failed */
5051 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5052 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5053 			connp = first_connp;
5054 			break;
5055 		}
5056 
5057 		CONN_INC_REF(connp);
5058 		mutex_exit(&connfp->connf_lock);
5059 
5060 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5061 		    ira);
5062 
5063 		mutex_enter(&connfp->connf_lock);
5064 		/* Follow the next pointer before releasing the conn. */
5065 		next_connp = connp->conn_next;
5066 		CONN_DEC_REF(connp);
5067 		connp = next_connp;
5068 	}
5069 
5070 	/* Last one.  Send it upstream. */
5071 	mutex_exit(&connfp->connf_lock);
5072 
5073 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5074 
5075 	CONN_DEC_REF(connp);
5076 }
5077 
5078 /*
5079  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5080  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5081  * is not consumed.
5082  *
5083  * One of three things can happen, all of which affect the passed-in mblk:
5084  *
5085  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5086  *
5087  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5088  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5089  *
5090  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5091  */
5092 mblk_t *
5093 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5094 {
5095 	int shift, plen, iph_len;
5096 	ipha_t *ipha;
5097 	udpha_t *udpha;
5098 	uint32_t *spi;
5099 	uint32_t esp_ports;
5100 	uint8_t *orptr;
5101 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5102 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5103 
5104 	ipha = (ipha_t *)mp->b_rptr;
5105 	iph_len = ira->ira_ip_hdr_length;
5106 	plen = ira->ira_pktlen;
5107 
5108 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5109 		/*
5110 		 * Most likely a keepalive for the benefit of an intervening
5111 		 * NAT.  These aren't for us, per se, so drop it.
5112 		 *
5113 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5114 		 * byte packets (keepalives are 1-byte), but we'll drop them
5115 		 * also.
5116 		 */
5117 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5118 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5119 		return (NULL);
5120 	}
5121 
5122 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5123 		/* might as well pull it all up - it might be ESP. */
5124 		if (!pullupmsg(mp, -1)) {
5125 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5126 			    DROPPER(ipss, ipds_esp_nomem),
5127 			    &ipss->ipsec_dropper);
5128 			return (NULL);
5129 		}
5130 
5131 		ipha = (ipha_t *)mp->b_rptr;
5132 	}
5133 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5134 	if (*spi == 0) {
5135 		/* UDP packet - remove 0-spi. */
5136 		shift = sizeof (uint32_t);
5137 	} else {
5138 		/* ESP-in-UDP packet - reduce to ESP. */
5139 		ipha->ipha_protocol = IPPROTO_ESP;
5140 		shift = sizeof (udpha_t);
5141 	}
5142 
5143 	/* Fix IP header */
5144 	ira->ira_pktlen = (plen - shift);
5145 	ipha->ipha_length = htons(ira->ira_pktlen);
5146 	ipha->ipha_hdr_checksum = 0;
5147 
5148 	orptr = mp->b_rptr;
5149 	mp->b_rptr += shift;
5150 
5151 	udpha = (udpha_t *)(orptr + iph_len);
5152 	if (*spi == 0) {
5153 		ASSERT((uint8_t *)ipha == orptr);
5154 		udpha->uha_length = htons(plen - shift - iph_len);
5155 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5156 		esp_ports = 0;
5157 	} else {
5158 		esp_ports = *((uint32_t *)udpha);
5159 		ASSERT(esp_ports != 0);
5160 	}
5161 	ovbcopy(orptr, orptr + shift, iph_len);
5162 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5163 		ipha = (ipha_t *)(orptr + shift);
5164 
5165 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5166 		ira->ira_esp_udp_ports = esp_ports;
5167 		ip_fanout_v4(mp, ipha, ira);
5168 		return (NULL);
5169 	}
5170 	return (mp);
5171 }
5172 
5173 /*
5174  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5175  * Handles IPv4 and IPv6.
5176  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5177  * Caller is responsible for dropping references to the conn.
5178  */
5179 void
5180 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5181     ip_recv_attr_t *ira)
5182 {
5183 	ill_t		*ill = ira->ira_ill;
5184 	ip_stack_t	*ipst = ill->ill_ipst;
5185 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5186 	boolean_t	secure;
5187 	iaflags_t	iraflags = ira->ira_flags;
5188 
5189 	secure = iraflags & IRAF_IPSEC_SECURE;
5190 
5191 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5192 	    !canputnext(connp->conn_rq)) {
5193 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5194 		freemsg(mp);
5195 		return;
5196 	}
5197 
5198 	if (((iraflags & IRAF_IS_IPV4) ?
5199 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5200 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5201 	    secure) {
5202 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5203 		    ip6h, ira);
5204 		if (mp == NULL) {
5205 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5206 			/* Note that mp is NULL */
5207 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5208 			return;
5209 		}
5210 	}
5211 
5212 	/*
5213 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5214 	 * check. Only ip_fanout_v4 has that check.
5215 	 */
5216 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5217 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5218 	} else {
5219 		ill_t *rill = ira->ira_rill;
5220 
5221 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5222 		ira->ira_ill = ira->ira_rill = NULL;
5223 		/* Send it upstream */
5224 		(connp->conn_recv)(connp, mp, NULL, ira);
5225 		ira->ira_ill = ill;
5226 		ira->ira_rill = rill;
5227 	}
5228 }
5229 
5230 /*
5231  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5232  * (Unicast fanout is handled in ip_input_v4.)
5233  *
5234  * If SO_REUSEADDR is set all multicast and broadcast packets
5235  * will be delivered to all conns bound to the same port.
5236  *
5237  * If there is at least one matching AF_INET receiver, then we will
5238  * ignore any AF_INET6 receivers.
5239  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5240  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5241  * packets.
5242  *
5243  * Zones notes:
5244  * Earlier in ip_input on a system with multiple shared-IP zones we
5245  * duplicate the multicast and broadcast packets and send them up
5246  * with each explicit zoneid that exists on that ill.
5247  * This means that here we can match the zoneid with SO_ALLZONES being special.
5248  */
5249 void
5250 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5251     ip_recv_attr_t *ira)
5252 {
5253 	ipaddr_t	laddr;
5254 	in6_addr_t	v6faddr;
5255 	conn_t		*connp;
5256 	connf_t		*connfp;
5257 	ipaddr_t	faddr;
5258 	ill_t		*ill = ira->ira_ill;
5259 	ip_stack_t	*ipst = ill->ill_ipst;
5260 
5261 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5262 
5263 	laddr = ipha->ipha_dst;
5264 	faddr = ipha->ipha_src;
5265 
5266 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5267 	mutex_enter(&connfp->connf_lock);
5268 	connp = connfp->connf_head;
5269 
5270 	/*
5271 	 * If SO_REUSEADDR has been set on the first we send the
5272 	 * packet to all clients that have joined the group and
5273 	 * match the port.
5274 	 */
5275 	while (connp != NULL) {
5276 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5277 		    conn_wantpacket(connp, ira, ipha) &&
5278 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5279 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5280 			break;
5281 		connp = connp->conn_next;
5282 	}
5283 
5284 	if (connp == NULL)
5285 		goto notfound;
5286 
5287 	CONN_INC_REF(connp);
5288 
5289 	if (connp->conn_reuseaddr) {
5290 		conn_t		*first_connp = connp;
5291 		conn_t		*next_connp;
5292 		mblk_t		*mp1;
5293 
5294 		connp = connp->conn_next;
5295 		for (;;) {
5296 			while (connp != NULL) {
5297 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5298 				    fport, faddr) &&
5299 				    conn_wantpacket(connp, ira, ipha) &&
5300 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5301 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5302 				    ira, connp)))
5303 					break;
5304 				connp = connp->conn_next;
5305 			}
5306 			if (connp == NULL) {
5307 				/* No more interested clients */
5308 				connp = first_connp;
5309 				break;
5310 			}
5311 			if (((mp1 = dupmsg(mp)) == NULL) &&
5312 			    ((mp1 = copymsg(mp)) == NULL)) {
5313 				/* Memory allocation failed */
5314 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5315 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5316 				connp = first_connp;
5317 				break;
5318 			}
5319 			CONN_INC_REF(connp);
5320 			mutex_exit(&connfp->connf_lock);
5321 
5322 			IP_STAT(ipst, ip_udp_fanmb);
5323 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5324 			    NULL, ira);
5325 			mutex_enter(&connfp->connf_lock);
5326 			/* Follow the next pointer before releasing the conn */
5327 			next_connp = connp->conn_next;
5328 			CONN_DEC_REF(connp);
5329 			connp = next_connp;
5330 		}
5331 	}
5332 
5333 	/* Last one.  Send it upstream. */
5334 	mutex_exit(&connfp->connf_lock);
5335 	IP_STAT(ipst, ip_udp_fanmb);
5336 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5337 	CONN_DEC_REF(connp);
5338 	return;
5339 
5340 notfound:
5341 	mutex_exit(&connfp->connf_lock);
5342 	/*
5343 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5344 	 * have already been matched above, since they live in the IPv4
5345 	 * fanout tables. This implies we only need to
5346 	 * check for IPv6 in6addr_any endpoints here.
5347 	 * Thus we compare using ipv6_all_zeros instead of the destination
5348 	 * address, except for the multicast group membership lookup which
5349 	 * uses the IPv4 destination.
5350 	 */
5351 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5352 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5353 	mutex_enter(&connfp->connf_lock);
5354 	connp = connfp->connf_head;
5355 	/*
5356 	 * IPv4 multicast packet being delivered to an AF_INET6
5357 	 * in6addr_any endpoint.
5358 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5359 	 * and not conn_wantpacket_v6() since any multicast membership is
5360 	 * for an IPv4-mapped multicast address.
5361 	 */
5362 	while (connp != NULL) {
5363 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5364 		    fport, v6faddr) &&
5365 		    conn_wantpacket(connp, ira, ipha) &&
5366 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5367 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5368 			break;
5369 		connp = connp->conn_next;
5370 	}
5371 
5372 	if (connp == NULL) {
5373 		/*
5374 		 * No one bound to this port.  Is
5375 		 * there a client that wants all
5376 		 * unclaimed datagrams?
5377 		 */
5378 		mutex_exit(&connfp->connf_lock);
5379 
5380 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5381 		    NULL) {
5382 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5383 			ip_fanout_proto_v4(mp, ipha, ira);
5384 		} else {
5385 			/*
5386 			 * We used to attempt to send an icmp error here, but
5387 			 * since this is known to be a multicast packet
5388 			 * and we don't send icmp errors in response to
5389 			 * multicast, just drop the packet and give up sooner.
5390 			 */
5391 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5392 			freemsg(mp);
5393 		}
5394 		return;
5395 	}
5396 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5397 
5398 	/*
5399 	 * If SO_REUSEADDR has been set on the first we send the
5400 	 * packet to all clients that have joined the group and
5401 	 * match the port.
5402 	 */
5403 	if (connp->conn_reuseaddr) {
5404 		conn_t		*first_connp = connp;
5405 		conn_t		*next_connp;
5406 		mblk_t		*mp1;
5407 
5408 		CONN_INC_REF(connp);
5409 		connp = connp->conn_next;
5410 		for (;;) {
5411 			while (connp != NULL) {
5412 				if (IPCL_UDP_MATCH_V6(connp, lport,
5413 				    ipv6_all_zeros, fport, v6faddr) &&
5414 				    conn_wantpacket(connp, ira, ipha) &&
5415 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5416 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5417 				    ira, connp)))
5418 					break;
5419 				connp = connp->conn_next;
5420 			}
5421 			if (connp == NULL) {
5422 				/* No more interested clients */
5423 				connp = first_connp;
5424 				break;
5425 			}
5426 			if (((mp1 = dupmsg(mp)) == NULL) &&
5427 			    ((mp1 = copymsg(mp)) == NULL)) {
5428 				/* Memory allocation failed */
5429 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5430 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5431 				connp = first_connp;
5432 				break;
5433 			}
5434 			CONN_INC_REF(connp);
5435 			mutex_exit(&connfp->connf_lock);
5436 
5437 			IP_STAT(ipst, ip_udp_fanmb);
5438 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5439 			    NULL, ira);
5440 			mutex_enter(&connfp->connf_lock);
5441 			/* Follow the next pointer before releasing the conn */
5442 			next_connp = connp->conn_next;
5443 			CONN_DEC_REF(connp);
5444 			connp = next_connp;
5445 		}
5446 	}
5447 
5448 	/* Last one.  Send it upstream. */
5449 	mutex_exit(&connfp->connf_lock);
5450 	IP_STAT(ipst, ip_udp_fanmb);
5451 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5452 	CONN_DEC_REF(connp);
5453 }
5454 
5455 /*
5456  * Split an incoming packet's IPv4 options into the label and the other options.
5457  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5458  * clearing out any leftover label or options.
5459  * Otherwise it just makes ipp point into the packet.
5460  *
5461  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5462  */
5463 int
5464 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5465 {
5466 	uchar_t		*opt;
5467 	uint32_t	totallen;
5468 	uint32_t	optval;
5469 	uint32_t	optlen;
5470 
5471 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5472 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5473 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5474 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5475 
5476 	/*
5477 	 * Get length (in 4 byte octets) of IP header options.
5478 	 */
5479 	totallen = ipha->ipha_version_and_hdr_length -
5480 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5481 
5482 	if (totallen == 0) {
5483 		if (!allocate)
5484 			return (0);
5485 
5486 		/* Clear out anything from a previous packet */
5487 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5488 			kmem_free(ipp->ipp_ipv4_options,
5489 			    ipp->ipp_ipv4_options_len);
5490 			ipp->ipp_ipv4_options = NULL;
5491 			ipp->ipp_ipv4_options_len = 0;
5492 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5493 		}
5494 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5495 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5496 			ipp->ipp_label_v4 = NULL;
5497 			ipp->ipp_label_len_v4 = 0;
5498 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5499 		}
5500 		return (0);
5501 	}
5502 
5503 	totallen <<= 2;
5504 	opt = (uchar_t *)&ipha[1];
5505 	if (!is_system_labeled()) {
5506 
5507 	copyall:
5508 		if (!allocate) {
5509 			if (totallen != 0) {
5510 				ipp->ipp_ipv4_options = opt;
5511 				ipp->ipp_ipv4_options_len = totallen;
5512 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5513 			}
5514 			return (0);
5515 		}
5516 		/* Just copy all of options */
5517 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5518 			if (totallen == ipp->ipp_ipv4_options_len) {
5519 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5520 				return (0);
5521 			}
5522 			kmem_free(ipp->ipp_ipv4_options,
5523 			    ipp->ipp_ipv4_options_len);
5524 			ipp->ipp_ipv4_options = NULL;
5525 			ipp->ipp_ipv4_options_len = 0;
5526 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5527 		}
5528 		if (totallen == 0)
5529 			return (0);
5530 
5531 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5532 		if (ipp->ipp_ipv4_options == NULL)
5533 			return (ENOMEM);
5534 		ipp->ipp_ipv4_options_len = totallen;
5535 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5536 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5537 		return (0);
5538 	}
5539 
5540 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5541 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5542 		ipp->ipp_label_v4 = NULL;
5543 		ipp->ipp_label_len_v4 = 0;
5544 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5545 	}
5546 
5547 	/*
5548 	 * Search for CIPSO option.
5549 	 * We assume CIPSO is first in options if it is present.
5550 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5551 	 * prior to the CIPSO option.
5552 	 */
5553 	while (totallen != 0) {
5554 		switch (optval = opt[IPOPT_OPTVAL]) {
5555 		case IPOPT_EOL:
5556 			return (0);
5557 		case IPOPT_NOP:
5558 			optlen = 1;
5559 			break;
5560 		default:
5561 			if (totallen <= IPOPT_OLEN)
5562 				return (EINVAL);
5563 			optlen = opt[IPOPT_OLEN];
5564 			if (optlen < 2)
5565 				return (EINVAL);
5566 		}
5567 		if (optlen > totallen)
5568 			return (EINVAL);
5569 
5570 		switch (optval) {
5571 		case IPOPT_COMSEC:
5572 			if (!allocate) {
5573 				ipp->ipp_label_v4 = opt;
5574 				ipp->ipp_label_len_v4 = optlen;
5575 				ipp->ipp_fields |= IPPF_LABEL_V4;
5576 			} else {
5577 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5578 				    KM_NOSLEEP);
5579 				if (ipp->ipp_label_v4 == NULL)
5580 					return (ENOMEM);
5581 				ipp->ipp_label_len_v4 = optlen;
5582 				ipp->ipp_fields |= IPPF_LABEL_V4;
5583 				bcopy(opt, ipp->ipp_label_v4, optlen);
5584 			}
5585 			totallen -= optlen;
5586 			opt += optlen;
5587 
5588 			/* Skip padding bytes until we get to a multiple of 4 */
5589 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5590 				totallen--;
5591 				opt++;
5592 			}
5593 			/* Remaining as ipp_ipv4_options */
5594 			goto copyall;
5595 		}
5596 		totallen -= optlen;
5597 		opt += optlen;
5598 	}
5599 	/* No CIPSO found; return everything as ipp_ipv4_options */
5600 	totallen = ipha->ipha_version_and_hdr_length -
5601 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5602 	totallen <<= 2;
5603 	opt = (uchar_t *)&ipha[1];
5604 	goto copyall;
5605 }
5606 
5607 /*
5608  * Efficient versions of lookup for an IRE when we only
5609  * match the address.
5610  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5611  * Does not handle multicast addresses.
5612  */
5613 uint_t
5614 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5615 {
5616 	ire_t *ire;
5617 	uint_t result;
5618 
5619 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5620 	ASSERT(ire != NULL);
5621 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5622 		result = IRE_NOROUTE;
5623 	else
5624 		result = ire->ire_type;
5625 	ire_refrele(ire);
5626 	return (result);
5627 }
5628 
5629 /*
5630  * Efficient versions of lookup for an IRE when we only
5631  * match the address.
5632  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5633  * Does not handle multicast addresses.
5634  */
5635 uint_t
5636 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5637 {
5638 	ire_t *ire;
5639 	uint_t result;
5640 
5641 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5642 	ASSERT(ire != NULL);
5643 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5644 		result = IRE_NOROUTE;
5645 	else
5646 		result = ire->ire_type;
5647 	ire_refrele(ire);
5648 	return (result);
5649 }
5650 
5651 /*
5652  * Nobody should be sending
5653  * packets up this stream
5654  */
5655 static void
5656 ip_lrput(queue_t *q, mblk_t *mp)
5657 {
5658 	switch (mp->b_datap->db_type) {
5659 	case M_FLUSH:
5660 		/* Turn around */
5661 		if (*mp->b_rptr & FLUSHW) {
5662 			*mp->b_rptr &= ~FLUSHR;
5663 			qreply(q, mp);
5664 			return;
5665 		}
5666 		break;
5667 	}
5668 	freemsg(mp);
5669 }
5670 
5671 /* Nobody should be sending packets down this stream */
5672 /* ARGSUSED */
5673 void
5674 ip_lwput(queue_t *q, mblk_t *mp)
5675 {
5676 	freemsg(mp);
5677 }
5678 
5679 /*
5680  * Move the first hop in any source route to ipha_dst and remove that part of
5681  * the source route.  Called by other protocols.  Errors in option formatting
5682  * are ignored - will be handled by ip_output_options. Return the final
5683  * destination (either ipha_dst or the last entry in a source route.)
5684  */
5685 ipaddr_t
5686 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5687 {
5688 	ipoptp_t	opts;
5689 	uchar_t		*opt;
5690 	uint8_t		optval;
5691 	uint8_t		optlen;
5692 	ipaddr_t	dst;
5693 	int		i;
5694 	ip_stack_t	*ipst = ns->netstack_ip;
5695 
5696 	ip2dbg(("ip_massage_options\n"));
5697 	dst = ipha->ipha_dst;
5698 	for (optval = ipoptp_first(&opts, ipha);
5699 	    optval != IPOPT_EOL;
5700 	    optval = ipoptp_next(&opts)) {
5701 		opt = opts.ipoptp_cur;
5702 		switch (optval) {
5703 			uint8_t off;
5704 		case IPOPT_SSRR:
5705 		case IPOPT_LSRR:
5706 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5707 				ip1dbg(("ip_massage_options: bad src route\n"));
5708 				break;
5709 			}
5710 			optlen = opts.ipoptp_len;
5711 			off = opt[IPOPT_OFFSET];
5712 			off--;
5713 		redo_srr:
5714 			if (optlen < IP_ADDR_LEN ||
5715 			    off > optlen - IP_ADDR_LEN) {
5716 				/* End of source route */
5717 				ip1dbg(("ip_massage_options: end of SR\n"));
5718 				break;
5719 			}
5720 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5721 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5722 			    ntohl(dst)));
5723 			/*
5724 			 * Check if our address is present more than
5725 			 * once as consecutive hops in source route.
5726 			 * XXX verify per-interface ip_forwarding
5727 			 * for source route?
5728 			 */
5729 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5730 				off += IP_ADDR_LEN;
5731 				goto redo_srr;
5732 			}
5733 			if (dst == htonl(INADDR_LOOPBACK)) {
5734 				ip1dbg(("ip_massage_options: loopback addr in "
5735 				    "source route!\n"));
5736 				break;
5737 			}
5738 			/*
5739 			 * Update ipha_dst to be the first hop and remove the
5740 			 * first hop from the source route (by overwriting
5741 			 * part of the option with NOP options).
5742 			 */
5743 			ipha->ipha_dst = dst;
5744 			/* Put the last entry in dst */
5745 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5746 			    3;
5747 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5748 
5749 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5750 			    ntohl(dst)));
5751 			/* Move down and overwrite */
5752 			opt[IP_ADDR_LEN] = opt[0];
5753 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5754 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5755 			for (i = 0; i < IP_ADDR_LEN; i++)
5756 				opt[i] = IPOPT_NOP;
5757 			break;
5758 		}
5759 	}
5760 	return (dst);
5761 }
5762 
5763 /*
5764  * Return the network mask
5765  * associated with the specified address.
5766  */
5767 ipaddr_t
5768 ip_net_mask(ipaddr_t addr)
5769 {
5770 	uchar_t	*up = (uchar_t *)&addr;
5771 	ipaddr_t mask = 0;
5772 	uchar_t	*maskp = (uchar_t *)&mask;
5773 
5774 #if defined(__i386) || defined(__amd64)
5775 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5776 #endif
5777 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5778 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5779 #endif
5780 	if (CLASSD(addr)) {
5781 		maskp[0] = 0xF0;
5782 		return (mask);
5783 	}
5784 
5785 	/* We assume Class E default netmask to be 32 */
5786 	if (CLASSE(addr))
5787 		return (0xffffffffU);
5788 
5789 	if (addr == 0)
5790 		return (0);
5791 	maskp[0] = 0xFF;
5792 	if ((up[0] & 0x80) == 0)
5793 		return (mask);
5794 
5795 	maskp[1] = 0xFF;
5796 	if ((up[0] & 0xC0) == 0x80)
5797 		return (mask);
5798 
5799 	maskp[2] = 0xFF;
5800 	if ((up[0] & 0xE0) == 0xC0)
5801 		return (mask);
5802 
5803 	/* Otherwise return no mask */
5804 	return ((ipaddr_t)0);
5805 }
5806 
5807 /* Name/Value Table Lookup Routine */
5808 char *
5809 ip_nv_lookup(nv_t *nv, int value)
5810 {
5811 	if (!nv)
5812 		return (NULL);
5813 	for (; nv->nv_name; nv++) {
5814 		if (nv->nv_value == value)
5815 			return (nv->nv_name);
5816 	}
5817 	return ("unknown");
5818 }
5819 
5820 static int
5821 ip_wait_for_info_ack(ill_t *ill)
5822 {
5823 	int err;
5824 
5825 	mutex_enter(&ill->ill_lock);
5826 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5827 		/*
5828 		 * Return value of 0 indicates a pending signal.
5829 		 */
5830 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5831 		if (err == 0) {
5832 			mutex_exit(&ill->ill_lock);
5833 			return (EINTR);
5834 		}
5835 	}
5836 	mutex_exit(&ill->ill_lock);
5837 	/*
5838 	 * ip_rput_other could have set an error  in ill_error on
5839 	 * receipt of M_ERROR.
5840 	 */
5841 	return (ill->ill_error);
5842 }
5843 
5844 /*
5845  * This is a module open, i.e. this is a control stream for access
5846  * to a DLPI device.  We allocate an ill_t as the instance data in
5847  * this case.
5848  */
5849 static int
5850 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5851 {
5852 	ill_t	*ill;
5853 	int	err;
5854 	zoneid_t zoneid;
5855 	netstack_t *ns;
5856 	ip_stack_t *ipst;
5857 
5858 	/*
5859 	 * Prevent unprivileged processes from pushing IP so that
5860 	 * they can't send raw IP.
5861 	 */
5862 	if (secpolicy_net_rawaccess(credp) != 0)
5863 		return (EPERM);
5864 
5865 	ns = netstack_find_by_cred(credp);
5866 	ASSERT(ns != NULL);
5867 	ipst = ns->netstack_ip;
5868 	ASSERT(ipst != NULL);
5869 
5870 	/*
5871 	 * For exclusive stacks we set the zoneid to zero
5872 	 * to make IP operate as if in the global zone.
5873 	 */
5874 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5875 		zoneid = GLOBAL_ZONEID;
5876 	else
5877 		zoneid = crgetzoneid(credp);
5878 
5879 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5880 	q->q_ptr = WR(q)->q_ptr = ill;
5881 	ill->ill_ipst = ipst;
5882 	ill->ill_zoneid = zoneid;
5883 
5884 	/*
5885 	 * ill_init initializes the ill fields and then sends down
5886 	 * down a DL_INFO_REQ after calling qprocson.
5887 	 */
5888 	err = ill_init(q, ill);
5889 
5890 	if (err != 0) {
5891 		mi_free(ill);
5892 		netstack_rele(ipst->ips_netstack);
5893 		q->q_ptr = NULL;
5894 		WR(q)->q_ptr = NULL;
5895 		return (err);
5896 	}
5897 
5898 	/*
5899 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5900 	 *
5901 	 * ill_init initializes the ipsq marking this thread as
5902 	 * writer
5903 	 */
5904 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5905 	err = ip_wait_for_info_ack(ill);
5906 	if (err == 0)
5907 		ill->ill_credp = credp;
5908 	else
5909 		goto fail;
5910 
5911 	crhold(credp);
5912 
5913 	mutex_enter(&ipst->ips_ip_mi_lock);
5914 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5915 	    sflag, credp);
5916 	mutex_exit(&ipst->ips_ip_mi_lock);
5917 fail:
5918 	if (err) {
5919 		(void) ip_close(q, 0);
5920 		return (err);
5921 	}
5922 	return (0);
5923 }
5924 
5925 /* For /dev/ip aka AF_INET open */
5926 int
5927 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5928 {
5929 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5930 }
5931 
5932 /* For /dev/ip6 aka AF_INET6 open */
5933 int
5934 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5935 {
5936 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5937 }
5938 
5939 /* IP open routine. */
5940 int
5941 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5942     boolean_t isv6)
5943 {
5944 	conn_t 		*connp;
5945 	major_t		maj;
5946 	zoneid_t	zoneid;
5947 	netstack_t	*ns;
5948 	ip_stack_t	*ipst;
5949 
5950 	/* Allow reopen. */
5951 	if (q->q_ptr != NULL)
5952 		return (0);
5953 
5954 	if (sflag & MODOPEN) {
5955 		/* This is a module open */
5956 		return (ip_modopen(q, devp, flag, sflag, credp));
5957 	}
5958 
5959 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5960 		/*
5961 		 * Non streams based socket looking for a stream
5962 		 * to access IP
5963 		 */
5964 		return (ip_helper_stream_setup(q, devp, flag, sflag,
5965 		    credp, isv6));
5966 	}
5967 
5968 	ns = netstack_find_by_cred(credp);
5969 	ASSERT(ns != NULL);
5970 	ipst = ns->netstack_ip;
5971 	ASSERT(ipst != NULL);
5972 
5973 	/*
5974 	 * For exclusive stacks we set the zoneid to zero
5975 	 * to make IP operate as if in the global zone.
5976 	 */
5977 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5978 		zoneid = GLOBAL_ZONEID;
5979 	else
5980 		zoneid = crgetzoneid(credp);
5981 
5982 	/*
5983 	 * We are opening as a device. This is an IP client stream, and we
5984 	 * allocate an conn_t as the instance data.
5985 	 */
5986 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
5987 
5988 	/*
5989 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
5990 	 * done by netstack_find_by_cred()
5991 	 */
5992 	netstack_rele(ipst->ips_netstack);
5993 
5994 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
5995 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
5996 	connp->conn_ixa->ixa_zoneid = zoneid;
5997 	connp->conn_zoneid = zoneid;
5998 
5999 	connp->conn_rq = q;
6000 	q->q_ptr = WR(q)->q_ptr = connp;
6001 
6002 	/* Minor tells us which /dev entry was opened */
6003 	if (isv6) {
6004 		connp->conn_family = AF_INET6;
6005 		connp->conn_ipversion = IPV6_VERSION;
6006 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
6007 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
6008 	} else {
6009 		connp->conn_family = AF_INET;
6010 		connp->conn_ipversion = IPV4_VERSION;
6011 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
6012 	}
6013 
6014 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
6015 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
6016 		connp->conn_minor_arena = ip_minor_arena_la;
6017 	} else {
6018 		/*
6019 		 * Either minor numbers in the large arena were exhausted
6020 		 * or a non socket application is doing the open.
6021 		 * Try to allocate from the small arena.
6022 		 */
6023 		if ((connp->conn_dev =
6024 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
6025 			/* CONN_DEC_REF takes care of netstack_rele() */
6026 			q->q_ptr = WR(q)->q_ptr = NULL;
6027 			CONN_DEC_REF(connp);
6028 			return (EBUSY);
6029 		}
6030 		connp->conn_minor_arena = ip_minor_arena_sa;
6031 	}
6032 
6033 	maj = getemajor(*devp);
6034 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
6035 
6036 	/*
6037 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
6038 	 */
6039 	connp->conn_cred = credp;
6040 	connp->conn_cpid = curproc->p_pid;
6041 	/* Cache things in ixa without an extra refhold */
6042 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
6043 	connp->conn_ixa->ixa_cred = connp->conn_cred;
6044 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6045 	if (is_system_labeled())
6046 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6047 
6048 	/*
6049 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6050 	 */
6051 	connp->conn_recv = ip_conn_input;
6052 	connp->conn_recvicmp = ip_conn_input_icmp;
6053 
6054 	crhold(connp->conn_cred);
6055 
6056 	/*
6057 	 * If the caller has the process-wide flag set, then default to MAC
6058 	 * exempt mode.  This allows read-down to unlabeled hosts.
6059 	 */
6060 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6061 		connp->conn_mac_mode = CONN_MAC_AWARE;
6062 
6063 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6064 
6065 	connp->conn_rq = q;
6066 	connp->conn_wq = WR(q);
6067 
6068 	/* Non-zero default values */
6069 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6070 
6071 	/*
6072 	 * Make the conn globally visible to walkers
6073 	 */
6074 	ASSERT(connp->conn_ref == 1);
6075 	mutex_enter(&connp->conn_lock);
6076 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6077 	mutex_exit(&connp->conn_lock);
6078 
6079 	qprocson(q);
6080 
6081 	return (0);
6082 }
6083 
6084 /*
6085  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6086  * all of them are copied to the conn_t. If the req is "zero", the policy is
6087  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6088  * fields.
6089  * We keep only the latest setting of the policy and thus policy setting
6090  * is not incremental/cumulative.
6091  *
6092  * Requests to set policies with multiple alternative actions will
6093  * go through a different API.
6094  */
6095 int
6096 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6097 {
6098 	uint_t ah_req = 0;
6099 	uint_t esp_req = 0;
6100 	uint_t se_req = 0;
6101 	ipsec_act_t *actp = NULL;
6102 	uint_t nact;
6103 	ipsec_policy_head_t *ph;
6104 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6105 	int error = 0;
6106 	netstack_t	*ns = connp->conn_netstack;
6107 	ip_stack_t	*ipst = ns->netstack_ip;
6108 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6109 
6110 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6111 
6112 	/*
6113 	 * The IP_SEC_OPT option does not allow variable length parameters,
6114 	 * hence a request cannot be NULL.
6115 	 */
6116 	if (req == NULL)
6117 		return (EINVAL);
6118 
6119 	ah_req = req->ipsr_ah_req;
6120 	esp_req = req->ipsr_esp_req;
6121 	se_req = req->ipsr_self_encap_req;
6122 
6123 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6124 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6125 		return (EINVAL);
6126 
6127 	/*
6128 	 * Are we dealing with a request to reset the policy (i.e.
6129 	 * zero requests).
6130 	 */
6131 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6132 	    (esp_req & REQ_MASK) == 0 &&
6133 	    (se_req & REQ_MASK) == 0);
6134 
6135 	if (!is_pol_reset) {
6136 		/*
6137 		 * If we couldn't load IPsec, fail with "protocol
6138 		 * not supported".
6139 		 * IPsec may not have been loaded for a request with zero
6140 		 * policies, so we don't fail in this case.
6141 		 */
6142 		mutex_enter(&ipss->ipsec_loader_lock);
6143 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6144 			mutex_exit(&ipss->ipsec_loader_lock);
6145 			return (EPROTONOSUPPORT);
6146 		}
6147 		mutex_exit(&ipss->ipsec_loader_lock);
6148 
6149 		/*
6150 		 * Test for valid requests. Invalid algorithms
6151 		 * need to be tested by IPsec code because new
6152 		 * algorithms can be added dynamically.
6153 		 */
6154 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6155 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6156 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6157 			return (EINVAL);
6158 		}
6159 
6160 		/*
6161 		 * Only privileged users can issue these
6162 		 * requests.
6163 		 */
6164 		if (((ah_req & IPSEC_PREF_NEVER) ||
6165 		    (esp_req & IPSEC_PREF_NEVER) ||
6166 		    (se_req & IPSEC_PREF_NEVER)) &&
6167 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6168 			return (EPERM);
6169 		}
6170 
6171 		/*
6172 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6173 		 * are mutually exclusive.
6174 		 */
6175 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6176 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6177 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6178 			/* Both of them are set */
6179 			return (EINVAL);
6180 		}
6181 	}
6182 
6183 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6184 
6185 	/*
6186 	 * If we have already cached policies in conn_connect(), don't
6187 	 * let them change now. We cache policies for connections
6188 	 * whose src,dst [addr, port] is known.
6189 	 */
6190 	if (connp->conn_policy_cached) {
6191 		return (EINVAL);
6192 	}
6193 
6194 	/*
6195 	 * We have a zero policies, reset the connection policy if already
6196 	 * set. This will cause the connection to inherit the
6197 	 * global policy, if any.
6198 	 */
6199 	if (is_pol_reset) {
6200 		if (connp->conn_policy != NULL) {
6201 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6202 			connp->conn_policy = NULL;
6203 		}
6204 		connp->conn_in_enforce_policy = B_FALSE;
6205 		connp->conn_out_enforce_policy = B_FALSE;
6206 		return (0);
6207 	}
6208 
6209 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6210 	    ipst->ips_netstack);
6211 	if (ph == NULL)
6212 		goto enomem;
6213 
6214 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6215 	if (actp == NULL)
6216 		goto enomem;
6217 
6218 	/*
6219 	 * Always insert IPv4 policy entries, since they can also apply to
6220 	 * ipv6 sockets being used in ipv4-compat mode.
6221 	 */
6222 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6223 	    IPSEC_TYPE_INBOUND, ns))
6224 		goto enomem;
6225 	is_pol_inserted = B_TRUE;
6226 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6227 	    IPSEC_TYPE_OUTBOUND, ns))
6228 		goto enomem;
6229 
6230 	/*
6231 	 * We're looking at a v6 socket, also insert the v6-specific
6232 	 * entries.
6233 	 */
6234 	if (connp->conn_family == AF_INET6) {
6235 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6236 		    IPSEC_TYPE_INBOUND, ns))
6237 			goto enomem;
6238 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6239 		    IPSEC_TYPE_OUTBOUND, ns))
6240 			goto enomem;
6241 	}
6242 
6243 	ipsec_actvec_free(actp, nact);
6244 
6245 	/*
6246 	 * If the requests need security, set enforce_policy.
6247 	 * If the requests are IPSEC_PREF_NEVER, one should
6248 	 * still set conn_out_enforce_policy so that ip_set_destination
6249 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6250 	 * for connections that we don't cache policy in at connect time,
6251 	 * if global policy matches in ip_output_attach_policy, we
6252 	 * don't wrongly inherit global policy. Similarly, we need
6253 	 * to set conn_in_enforce_policy also so that we don't verify
6254 	 * policy wrongly.
6255 	 */
6256 	if ((ah_req & REQ_MASK) != 0 ||
6257 	    (esp_req & REQ_MASK) != 0 ||
6258 	    (se_req & REQ_MASK) != 0) {
6259 		connp->conn_in_enforce_policy = B_TRUE;
6260 		connp->conn_out_enforce_policy = B_TRUE;
6261 	}
6262 
6263 	return (error);
6264 #undef REQ_MASK
6265 
6266 	/*
6267 	 * Common memory-allocation-failure exit path.
6268 	 */
6269 enomem:
6270 	if (actp != NULL)
6271 		ipsec_actvec_free(actp, nact);
6272 	if (is_pol_inserted)
6273 		ipsec_polhead_flush(ph, ns);
6274 	return (ENOMEM);
6275 }
6276 
6277 /*
6278  * Set socket options for joining and leaving multicast groups.
6279  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6280  * The caller has already check that the option name is consistent with
6281  * the address family of the socket.
6282  */
6283 int
6284 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6285     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6286 {
6287 	int		*i1 = (int *)invalp;
6288 	int		error = 0;
6289 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6290 	struct ip_mreq	*v4_mreqp;
6291 	struct ipv6_mreq *v6_mreqp;
6292 	struct group_req *greqp;
6293 	ire_t *ire;
6294 	boolean_t done = B_FALSE;
6295 	ipaddr_t ifaddr;
6296 	in6_addr_t v6group;
6297 	uint_t ifindex;
6298 	boolean_t mcast_opt = B_TRUE;
6299 	mcast_record_t fmode;
6300 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6301 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6302 
6303 	switch (name) {
6304 	case IP_ADD_MEMBERSHIP:
6305 	case IPV6_JOIN_GROUP:
6306 		mcast_opt = B_FALSE;
6307 		/* FALLTHRU */
6308 	case MCAST_JOIN_GROUP:
6309 		fmode = MODE_IS_EXCLUDE;
6310 		optfn = ip_opt_add_group;
6311 		break;
6312 
6313 	case IP_DROP_MEMBERSHIP:
6314 	case IPV6_LEAVE_GROUP:
6315 		mcast_opt = B_FALSE;
6316 		/* FALLTHRU */
6317 	case MCAST_LEAVE_GROUP:
6318 		fmode = MODE_IS_INCLUDE;
6319 		optfn = ip_opt_delete_group;
6320 		break;
6321 	default:
6322 		ASSERT(0);
6323 	}
6324 
6325 	if (mcast_opt) {
6326 		struct sockaddr_in *sin;
6327 		struct sockaddr_in6 *sin6;
6328 
6329 		greqp = (struct group_req *)i1;
6330 		if (greqp->gr_group.ss_family == AF_INET) {
6331 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6332 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6333 		} else {
6334 			if (!inet6)
6335 				return (EINVAL);	/* Not on INET socket */
6336 
6337 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6338 			v6group = sin6->sin6_addr;
6339 		}
6340 		ifaddr = INADDR_ANY;
6341 		ifindex = greqp->gr_interface;
6342 	} else if (inet6) {
6343 		v6_mreqp = (struct ipv6_mreq *)i1;
6344 		v6group = v6_mreqp->ipv6mr_multiaddr;
6345 		ifaddr = INADDR_ANY;
6346 		ifindex = v6_mreqp->ipv6mr_interface;
6347 	} else {
6348 		v4_mreqp = (struct ip_mreq *)i1;
6349 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6350 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6351 		ifindex = 0;
6352 	}
6353 
6354 	/*
6355 	 * In the multirouting case, we need to replicate
6356 	 * the request on all interfaces that will take part
6357 	 * in replication.  We do so because multirouting is
6358 	 * reflective, thus we will probably receive multi-
6359 	 * casts on those interfaces.
6360 	 * The ip_multirt_apply_membership() succeeds if
6361 	 * the operation succeeds on at least one interface.
6362 	 */
6363 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6364 		ipaddr_t group;
6365 
6366 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6367 
6368 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6369 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6370 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6371 	} else {
6372 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6373 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6374 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6375 	}
6376 	if (ire != NULL) {
6377 		if (ire->ire_flags & RTF_MULTIRT) {
6378 			error = ip_multirt_apply_membership(optfn, ire, connp,
6379 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6380 			done = B_TRUE;
6381 		}
6382 		ire_refrele(ire);
6383 	}
6384 
6385 	if (!done) {
6386 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6387 		    fmode, &ipv6_all_zeros);
6388 	}
6389 	return (error);
6390 }
6391 
6392 /*
6393  * Set socket options for joining and leaving multicast groups
6394  * for specific sources.
6395  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6396  * The caller has already check that the option name is consistent with
6397  * the address family of the socket.
6398  */
6399 int
6400 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6401     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6402 {
6403 	int		*i1 = (int *)invalp;
6404 	int		error = 0;
6405 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6406 	struct ip_mreq_source *imreqp;
6407 	struct group_source_req *gsreqp;
6408 	in6_addr_t v6group, v6src;
6409 	uint32_t ifindex;
6410 	ipaddr_t ifaddr;
6411 	boolean_t mcast_opt = B_TRUE;
6412 	mcast_record_t fmode;
6413 	ire_t *ire;
6414 	boolean_t done = B_FALSE;
6415 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6416 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6417 
6418 	switch (name) {
6419 	case IP_BLOCK_SOURCE:
6420 		mcast_opt = B_FALSE;
6421 		/* FALLTHRU */
6422 	case MCAST_BLOCK_SOURCE:
6423 		fmode = MODE_IS_EXCLUDE;
6424 		optfn = ip_opt_add_group;
6425 		break;
6426 
6427 	case IP_UNBLOCK_SOURCE:
6428 		mcast_opt = B_FALSE;
6429 		/* FALLTHRU */
6430 	case MCAST_UNBLOCK_SOURCE:
6431 		fmode = MODE_IS_EXCLUDE;
6432 		optfn = ip_opt_delete_group;
6433 		break;
6434 
6435 	case IP_ADD_SOURCE_MEMBERSHIP:
6436 		mcast_opt = B_FALSE;
6437 		/* FALLTHRU */
6438 	case MCAST_JOIN_SOURCE_GROUP:
6439 		fmode = MODE_IS_INCLUDE;
6440 		optfn = ip_opt_add_group;
6441 		break;
6442 
6443 	case IP_DROP_SOURCE_MEMBERSHIP:
6444 		mcast_opt = B_FALSE;
6445 		/* FALLTHRU */
6446 	case MCAST_LEAVE_SOURCE_GROUP:
6447 		fmode = MODE_IS_INCLUDE;
6448 		optfn = ip_opt_delete_group;
6449 		break;
6450 	default:
6451 		ASSERT(0);
6452 	}
6453 
6454 	if (mcast_opt) {
6455 		gsreqp = (struct group_source_req *)i1;
6456 		ifindex = gsreqp->gsr_interface;
6457 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6458 			struct sockaddr_in *s;
6459 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6460 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6461 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6462 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6463 		} else {
6464 			struct sockaddr_in6 *s6;
6465 
6466 			if (!inet6)
6467 				return (EINVAL);	/* Not on INET socket */
6468 
6469 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6470 			v6group = s6->sin6_addr;
6471 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6472 			v6src = s6->sin6_addr;
6473 		}
6474 		ifaddr = INADDR_ANY;
6475 	} else {
6476 		imreqp = (struct ip_mreq_source *)i1;
6477 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6478 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6479 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6480 		ifindex = 0;
6481 	}
6482 
6483 	/*
6484 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6485 	 */
6486 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6487 		v6src = ipv6_all_zeros;
6488 
6489 	/*
6490 	 * In the multirouting case, we need to replicate
6491 	 * the request as noted in the mcast cases above.
6492 	 */
6493 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6494 		ipaddr_t group;
6495 
6496 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6497 
6498 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6499 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6500 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6501 	} else {
6502 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6503 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6504 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6505 	}
6506 	if (ire != NULL) {
6507 		if (ire->ire_flags & RTF_MULTIRT) {
6508 			error = ip_multirt_apply_membership(optfn, ire, connp,
6509 			    checkonly, &v6group, fmode, &v6src);
6510 			done = B_TRUE;
6511 		}
6512 		ire_refrele(ire);
6513 	}
6514 	if (!done) {
6515 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6516 		    fmode, &v6src);
6517 	}
6518 	return (error);
6519 }
6520 
6521 /*
6522  * Given a destination address and a pointer to where to put the information
6523  * this routine fills in the mtuinfo.
6524  * The socket must be connected.
6525  * For sctp conn_faddr is the primary address.
6526  */
6527 int
6528 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6529 {
6530 	uint32_t	pmtu = IP_MAXPACKET;
6531 	uint_t		scopeid;
6532 
6533 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6534 		return (-1);
6535 
6536 	/* In case we never sent or called ip_set_destination_v4/v6 */
6537 	if (ixa->ixa_ire != NULL)
6538 		pmtu = ip_get_pmtu(ixa);
6539 
6540 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6541 		scopeid = ixa->ixa_scopeid;
6542 	else
6543 		scopeid = 0;
6544 
6545 	bzero(mtuinfo, sizeof (*mtuinfo));
6546 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6547 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6548 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6549 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6550 	mtuinfo->ip6m_mtu = pmtu;
6551 
6552 	return (sizeof (struct ip6_mtuinfo));
6553 }
6554 
6555 /*
6556  * When the src multihoming is changed from weak to [strong, preferred]
6557  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6558  * and identify routes that were created by user-applications in the
6559  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6560  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6561  * is selected by finding an interface route for the gateway.
6562  */
6563 /* ARGSUSED */
6564 void
6565 ip_ire_rebind_walker(ire_t *ire, void *notused)
6566 {
6567 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6568 		return;
6569 	ire_rebind(ire);
6570 	ire_delete(ire);
6571 }
6572 
6573 /*
6574  * When the src multihoming is changed from  [strong, preferred] to weak,
6575  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6576  * set any entries that were created by user-applications in the unbound state
6577  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6578  */
6579 /* ARGSUSED */
6580 void
6581 ip_ire_unbind_walker(ire_t *ire, void *notused)
6582 {
6583 	ire_t *new_ire;
6584 
6585 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6586 		return;
6587 	if (ire->ire_ipversion == IPV6_VERSION) {
6588 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6589 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6590 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6591 	} else {
6592 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6593 		    (uchar_t *)&ire->ire_mask,
6594 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6595 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6596 	}
6597 	if (new_ire == NULL)
6598 		return;
6599 	new_ire->ire_unbound = B_TRUE;
6600 	/*
6601 	 * The bound ire must first be deleted so that we don't return
6602 	 * the existing one on the attempt to add the unbound new_ire.
6603 	 */
6604 	ire_delete(ire);
6605 	new_ire = ire_add(new_ire);
6606 	if (new_ire != NULL)
6607 		ire_refrele(new_ire);
6608 }
6609 
6610 /*
6611  * When the settings of ip*_strict_src_multihoming tunables are changed,
6612  * all cached routes need to be recomputed. This recomputation needs to be
6613  * done when going from weaker to stronger modes so that the cached ire
6614  * for the connection does not violate the current ip*_strict_src_multihoming
6615  * setting. It also needs to be done when going from stronger to weaker modes,
6616  * so that we fall back to matching on the longest-matching-route (as opposed
6617  * to a shorter match that may have been selected in the strong mode
6618  * to satisfy src_multihoming settings).
6619  *
6620  * The cached ixa_ire entires for all conn_t entries are marked as
6621  * "verify" so that they will be recomputed for the next packet.
6622  */
6623 void
6624 conn_ire_revalidate(conn_t *connp, void *arg)
6625 {
6626 	boolean_t isv6 = (boolean_t)arg;
6627 
6628 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6629 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6630 		return;
6631 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6632 }
6633 
6634 /*
6635  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6636  * When an ipf is passed here for the first time, if
6637  * we already have in-order fragments on the queue, we convert from the fast-
6638  * path reassembly scheme to the hard-case scheme.  From then on, additional
6639  * fragments are reassembled here.  We keep track of the start and end offsets
6640  * of each piece, and the number of holes in the chain.  When the hole count
6641  * goes to zero, we are done!
6642  *
6643  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6644  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6645  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6646  * after the call to ip_reassemble().
6647  */
6648 int
6649 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6650     size_t msg_len)
6651 {
6652 	uint_t	end;
6653 	mblk_t	*next_mp;
6654 	mblk_t	*mp1;
6655 	uint_t	offset;
6656 	boolean_t incr_dups = B_TRUE;
6657 	boolean_t offset_zero_seen = B_FALSE;
6658 	boolean_t pkt_boundary_checked = B_FALSE;
6659 
6660 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6661 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6662 
6663 	/* Add in byte count */
6664 	ipf->ipf_count += msg_len;
6665 	if (ipf->ipf_end) {
6666 		/*
6667 		 * We were part way through in-order reassembly, but now there
6668 		 * is a hole.  We walk through messages already queued, and
6669 		 * mark them for hard case reassembly.  We know that up till
6670 		 * now they were in order starting from offset zero.
6671 		 */
6672 		offset = 0;
6673 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6674 			IP_REASS_SET_START(mp1, offset);
6675 			if (offset == 0) {
6676 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6677 				offset = -ipf->ipf_nf_hdr_len;
6678 			}
6679 			offset += mp1->b_wptr - mp1->b_rptr;
6680 			IP_REASS_SET_END(mp1, offset);
6681 		}
6682 		/* One hole at the end. */
6683 		ipf->ipf_hole_cnt = 1;
6684 		/* Brand it as a hard case, forever. */
6685 		ipf->ipf_end = 0;
6686 	}
6687 	/* Walk through all the new pieces. */
6688 	do {
6689 		end = start + (mp->b_wptr - mp->b_rptr);
6690 		/*
6691 		 * If start is 0, decrease 'end' only for the first mblk of
6692 		 * the fragment. Otherwise 'end' can get wrong value in the
6693 		 * second pass of the loop if first mblk is exactly the
6694 		 * size of ipf_nf_hdr_len.
6695 		 */
6696 		if (start == 0 && !offset_zero_seen) {
6697 			/* First segment */
6698 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6699 			end -= ipf->ipf_nf_hdr_len;
6700 			offset_zero_seen = B_TRUE;
6701 		}
6702 		next_mp = mp->b_cont;
6703 		/*
6704 		 * We are checking to see if there is any interesing data
6705 		 * to process.  If there isn't and the mblk isn't the
6706 		 * one which carries the unfragmentable header then we
6707 		 * drop it.  It's possible to have just the unfragmentable
6708 		 * header come through without any data.  That needs to be
6709 		 * saved.
6710 		 *
6711 		 * If the assert at the top of this function holds then the
6712 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6713 		 * is infrequently traveled enough that the test is left in
6714 		 * to protect against future code changes which break that
6715 		 * invariant.
6716 		 */
6717 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6718 			/* Empty.  Blast it. */
6719 			IP_REASS_SET_START(mp, 0);
6720 			IP_REASS_SET_END(mp, 0);
6721 			/*
6722 			 * If the ipf points to the mblk we are about to free,
6723 			 * update ipf to point to the next mblk (or NULL
6724 			 * if none).
6725 			 */
6726 			if (ipf->ipf_mp->b_cont == mp)
6727 				ipf->ipf_mp->b_cont = next_mp;
6728 			freeb(mp);
6729 			continue;
6730 		}
6731 		mp->b_cont = NULL;
6732 		IP_REASS_SET_START(mp, start);
6733 		IP_REASS_SET_END(mp, end);
6734 		if (!ipf->ipf_tail_mp) {
6735 			ipf->ipf_tail_mp = mp;
6736 			ipf->ipf_mp->b_cont = mp;
6737 			if (start == 0 || !more) {
6738 				ipf->ipf_hole_cnt = 1;
6739 				/*
6740 				 * if the first fragment comes in more than one
6741 				 * mblk, this loop will be executed for each
6742 				 * mblk. Need to adjust hole count so exiting
6743 				 * this routine will leave hole count at 1.
6744 				 */
6745 				if (next_mp)
6746 					ipf->ipf_hole_cnt++;
6747 			} else
6748 				ipf->ipf_hole_cnt = 2;
6749 			continue;
6750 		} else if (ipf->ipf_last_frag_seen && !more &&
6751 		    !pkt_boundary_checked) {
6752 			/*
6753 			 * We check datagram boundary only if this fragment
6754 			 * claims to be the last fragment and we have seen a
6755 			 * last fragment in the past too. We do this only
6756 			 * once for a given fragment.
6757 			 *
6758 			 * start cannot be 0 here as fragments with start=0
6759 			 * and MF=0 gets handled as a complete packet. These
6760 			 * fragments should not reach here.
6761 			 */
6762 
6763 			if (start + msgdsize(mp) !=
6764 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6765 				/*
6766 				 * We have two fragments both of which claim
6767 				 * to be the last fragment but gives conflicting
6768 				 * information about the whole datagram size.
6769 				 * Something fishy is going on. Drop the
6770 				 * fragment and free up the reassembly list.
6771 				 */
6772 				return (IP_REASS_FAILED);
6773 			}
6774 
6775 			/*
6776 			 * We shouldn't come to this code block again for this
6777 			 * particular fragment.
6778 			 */
6779 			pkt_boundary_checked = B_TRUE;
6780 		}
6781 
6782 		/* New stuff at or beyond tail? */
6783 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6784 		if (start >= offset) {
6785 			if (ipf->ipf_last_frag_seen) {
6786 				/* current fragment is beyond last fragment */
6787 				return (IP_REASS_FAILED);
6788 			}
6789 			/* Link it on end. */
6790 			ipf->ipf_tail_mp->b_cont = mp;
6791 			ipf->ipf_tail_mp = mp;
6792 			if (more) {
6793 				if (start != offset)
6794 					ipf->ipf_hole_cnt++;
6795 			} else if (start == offset && next_mp == NULL)
6796 					ipf->ipf_hole_cnt--;
6797 			continue;
6798 		}
6799 		mp1 = ipf->ipf_mp->b_cont;
6800 		offset = IP_REASS_START(mp1);
6801 		/* New stuff at the front? */
6802 		if (start < offset) {
6803 			if (start == 0) {
6804 				if (end >= offset) {
6805 					/* Nailed the hole at the begining. */
6806 					ipf->ipf_hole_cnt--;
6807 				}
6808 			} else if (end < offset) {
6809 				/*
6810 				 * A hole, stuff, and a hole where there used
6811 				 * to be just a hole.
6812 				 */
6813 				ipf->ipf_hole_cnt++;
6814 			}
6815 			mp->b_cont = mp1;
6816 			/* Check for overlap. */
6817 			while (end > offset) {
6818 				if (end < IP_REASS_END(mp1)) {
6819 					mp->b_wptr -= end - offset;
6820 					IP_REASS_SET_END(mp, offset);
6821 					BUMP_MIB(ill->ill_ip_mib,
6822 					    ipIfStatsReasmPartDups);
6823 					break;
6824 				}
6825 				/* Did we cover another hole? */
6826 				if ((mp1->b_cont &&
6827 				    IP_REASS_END(mp1) !=
6828 				    IP_REASS_START(mp1->b_cont) &&
6829 				    end >= IP_REASS_START(mp1->b_cont)) ||
6830 				    (!ipf->ipf_last_frag_seen && !more)) {
6831 					ipf->ipf_hole_cnt--;
6832 				}
6833 				/* Clip out mp1. */
6834 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6835 					/*
6836 					 * After clipping out mp1, this guy
6837 					 * is now hanging off the end.
6838 					 */
6839 					ipf->ipf_tail_mp = mp;
6840 				}
6841 				IP_REASS_SET_START(mp1, 0);
6842 				IP_REASS_SET_END(mp1, 0);
6843 				/* Subtract byte count */
6844 				ipf->ipf_count -= mp1->b_datap->db_lim -
6845 				    mp1->b_datap->db_base;
6846 				freeb(mp1);
6847 				BUMP_MIB(ill->ill_ip_mib,
6848 				    ipIfStatsReasmPartDups);
6849 				mp1 = mp->b_cont;
6850 				if (!mp1)
6851 					break;
6852 				offset = IP_REASS_START(mp1);
6853 			}
6854 			ipf->ipf_mp->b_cont = mp;
6855 			continue;
6856 		}
6857 		/*
6858 		 * The new piece starts somewhere between the start of the head
6859 		 * and before the end of the tail.
6860 		 */
6861 		for (; mp1; mp1 = mp1->b_cont) {
6862 			offset = IP_REASS_END(mp1);
6863 			if (start < offset) {
6864 				if (end <= offset) {
6865 					/* Nothing new. */
6866 					IP_REASS_SET_START(mp, 0);
6867 					IP_REASS_SET_END(mp, 0);
6868 					/* Subtract byte count */
6869 					ipf->ipf_count -= mp->b_datap->db_lim -
6870 					    mp->b_datap->db_base;
6871 					if (incr_dups) {
6872 						ipf->ipf_num_dups++;
6873 						incr_dups = B_FALSE;
6874 					}
6875 					freeb(mp);
6876 					BUMP_MIB(ill->ill_ip_mib,
6877 					    ipIfStatsReasmDuplicates);
6878 					break;
6879 				}
6880 				/*
6881 				 * Trim redundant stuff off beginning of new
6882 				 * piece.
6883 				 */
6884 				IP_REASS_SET_START(mp, offset);
6885 				mp->b_rptr += offset - start;
6886 				BUMP_MIB(ill->ill_ip_mib,
6887 				    ipIfStatsReasmPartDups);
6888 				start = offset;
6889 				if (!mp1->b_cont) {
6890 					/*
6891 					 * After trimming, this guy is now
6892 					 * hanging off the end.
6893 					 */
6894 					mp1->b_cont = mp;
6895 					ipf->ipf_tail_mp = mp;
6896 					if (!more) {
6897 						ipf->ipf_hole_cnt--;
6898 					}
6899 					break;
6900 				}
6901 			}
6902 			if (start >= IP_REASS_START(mp1->b_cont))
6903 				continue;
6904 			/* Fill a hole */
6905 			if (start > offset)
6906 				ipf->ipf_hole_cnt++;
6907 			mp->b_cont = mp1->b_cont;
6908 			mp1->b_cont = mp;
6909 			mp1 = mp->b_cont;
6910 			offset = IP_REASS_START(mp1);
6911 			if (end >= offset) {
6912 				ipf->ipf_hole_cnt--;
6913 				/* Check for overlap. */
6914 				while (end > offset) {
6915 					if (end < IP_REASS_END(mp1)) {
6916 						mp->b_wptr -= end - offset;
6917 						IP_REASS_SET_END(mp, offset);
6918 						/*
6919 						 * TODO we might bump
6920 						 * this up twice if there is
6921 						 * overlap at both ends.
6922 						 */
6923 						BUMP_MIB(ill->ill_ip_mib,
6924 						    ipIfStatsReasmPartDups);
6925 						break;
6926 					}
6927 					/* Did we cover another hole? */
6928 					if ((mp1->b_cont &&
6929 					    IP_REASS_END(mp1)
6930 					    != IP_REASS_START(mp1->b_cont) &&
6931 					    end >=
6932 					    IP_REASS_START(mp1->b_cont)) ||
6933 					    (!ipf->ipf_last_frag_seen &&
6934 					    !more)) {
6935 						ipf->ipf_hole_cnt--;
6936 					}
6937 					/* Clip out mp1. */
6938 					if ((mp->b_cont = mp1->b_cont) ==
6939 					    NULL) {
6940 						/*
6941 						 * After clipping out mp1,
6942 						 * this guy is now hanging
6943 						 * off the end.
6944 						 */
6945 						ipf->ipf_tail_mp = mp;
6946 					}
6947 					IP_REASS_SET_START(mp1, 0);
6948 					IP_REASS_SET_END(mp1, 0);
6949 					/* Subtract byte count */
6950 					ipf->ipf_count -=
6951 					    mp1->b_datap->db_lim -
6952 					    mp1->b_datap->db_base;
6953 					freeb(mp1);
6954 					BUMP_MIB(ill->ill_ip_mib,
6955 					    ipIfStatsReasmPartDups);
6956 					mp1 = mp->b_cont;
6957 					if (!mp1)
6958 						break;
6959 					offset = IP_REASS_START(mp1);
6960 				}
6961 			}
6962 			break;
6963 		}
6964 	} while (start = end, mp = next_mp);
6965 
6966 	/* Fragment just processed could be the last one. Remember this fact */
6967 	if (!more)
6968 		ipf->ipf_last_frag_seen = B_TRUE;
6969 
6970 	/* Still got holes? */
6971 	if (ipf->ipf_hole_cnt)
6972 		return (IP_REASS_PARTIAL);
6973 	/* Clean up overloaded fields to avoid upstream disasters. */
6974 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6975 		IP_REASS_SET_START(mp1, 0);
6976 		IP_REASS_SET_END(mp1, 0);
6977 	}
6978 	return (IP_REASS_COMPLETE);
6979 }
6980 
6981 /*
6982  * Fragmentation reassembly.  Each ILL has a hash table for
6983  * queuing packets undergoing reassembly for all IPIFs
6984  * associated with the ILL.  The hash is based on the packet
6985  * IP ident field.  The ILL frag hash table was allocated
6986  * as a timer block at the time the ILL was created.  Whenever
6987  * there is anything on the reassembly queue, the timer will
6988  * be running.  Returns the reassembled packet if reassembly completes.
6989  */
6990 mblk_t *
6991 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
6992 {
6993 	uint32_t	frag_offset_flags;
6994 	mblk_t		*t_mp;
6995 	ipaddr_t	dst;
6996 	uint8_t		proto = ipha->ipha_protocol;
6997 	uint32_t	sum_val;
6998 	uint16_t	sum_flags;
6999 	ipf_t		*ipf;
7000 	ipf_t		**ipfp;
7001 	ipfb_t		*ipfb;
7002 	uint16_t	ident;
7003 	uint32_t	offset;
7004 	ipaddr_t	src;
7005 	uint_t		hdr_length;
7006 	uint32_t	end;
7007 	mblk_t		*mp1;
7008 	mblk_t		*tail_mp;
7009 	size_t		count;
7010 	size_t		msg_len;
7011 	uint8_t		ecn_info = 0;
7012 	uint32_t	packet_size;
7013 	boolean_t	pruned = B_FALSE;
7014 	ill_t		*ill = ira->ira_ill;
7015 	ip_stack_t	*ipst = ill->ill_ipst;
7016 
7017 	/*
7018 	 * Drop the fragmented as early as possible, if
7019 	 * we don't have resource(s) to re-assemble.
7020 	 */
7021 	if (ipst->ips_ip_reass_queue_bytes == 0) {
7022 		freemsg(mp);
7023 		return (NULL);
7024 	}
7025 
7026 	/* Check for fragmentation offset; return if there's none */
7027 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7028 	    (IPH_MF | IPH_OFFSET)) == 0)
7029 		return (mp);
7030 
7031 	/*
7032 	 * We utilize hardware computed checksum info only for UDP since
7033 	 * IP fragmentation is a normal occurrence for the protocol.  In
7034 	 * addition, checksum offload support for IP fragments carrying
7035 	 * UDP payload is commonly implemented across network adapters.
7036 	 */
7037 	ASSERT(ira->ira_rill != NULL);
7038 	if (proto == IPPROTO_UDP && dohwcksum &&
7039 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7040 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7041 		mblk_t *mp1 = mp->b_cont;
7042 		int32_t len;
7043 
7044 		/* Record checksum information from the packet */
7045 		sum_val = (uint32_t)DB_CKSUM16(mp);
7046 		sum_flags = DB_CKSUMFLAGS(mp);
7047 
7048 		/* IP payload offset from beginning of mblk */
7049 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7050 
7051 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7052 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7053 		    offset >= DB_CKSUMSTART(mp) &&
7054 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7055 			uint32_t adj;
7056 			/*
7057 			 * Partial checksum has been calculated by hardware
7058 			 * and attached to the packet; in addition, any
7059 			 * prepended extraneous data is even byte aligned.
7060 			 * If any such data exists, we adjust the checksum;
7061 			 * this would also handle any postpended data.
7062 			 */
7063 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7064 			    mp, mp1, len, adj);
7065 
7066 			/* One's complement subtract extraneous checksum */
7067 			if (adj >= sum_val)
7068 				sum_val = ~(adj - sum_val) & 0xFFFF;
7069 			else
7070 				sum_val -= adj;
7071 		}
7072 	} else {
7073 		sum_val = 0;
7074 		sum_flags = 0;
7075 	}
7076 
7077 	/* Clear hardware checksumming flag */
7078 	DB_CKSUMFLAGS(mp) = 0;
7079 
7080 	ident = ipha->ipha_ident;
7081 	offset = (frag_offset_flags << 3) & 0xFFFF;
7082 	src = ipha->ipha_src;
7083 	dst = ipha->ipha_dst;
7084 	hdr_length = IPH_HDR_LENGTH(ipha);
7085 	end = ntohs(ipha->ipha_length) - hdr_length;
7086 
7087 	/* If end == 0 then we have a packet with no data, so just free it */
7088 	if (end == 0) {
7089 		freemsg(mp);
7090 		return (NULL);
7091 	}
7092 
7093 	/* Record the ECN field info. */
7094 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7095 	if (offset != 0) {
7096 		/*
7097 		 * If this isn't the first piece, strip the header, and
7098 		 * add the offset to the end value.
7099 		 */
7100 		mp->b_rptr += hdr_length;
7101 		end += offset;
7102 	}
7103 
7104 	/* Handle vnic loopback of fragments */
7105 	if (mp->b_datap->db_ref > 2)
7106 		msg_len = 0;
7107 	else
7108 		msg_len = MBLKSIZE(mp);
7109 
7110 	tail_mp = mp;
7111 	while (tail_mp->b_cont != NULL) {
7112 		tail_mp = tail_mp->b_cont;
7113 		if (tail_mp->b_datap->db_ref <= 2)
7114 			msg_len += MBLKSIZE(tail_mp);
7115 	}
7116 
7117 	/* If the reassembly list for this ILL will get too big, prune it */
7118 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7119 	    ipst->ips_ip_reass_queue_bytes) {
7120 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7121 		    uint_t, ill->ill_frag_count,
7122 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7123 		ill_frag_prune(ill,
7124 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7125 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7126 		pruned = B_TRUE;
7127 	}
7128 
7129 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7130 	mutex_enter(&ipfb->ipfb_lock);
7131 
7132 	ipfp = &ipfb->ipfb_ipf;
7133 	/* Try to find an existing fragment queue for this packet. */
7134 	for (;;) {
7135 		ipf = ipfp[0];
7136 		if (ipf != NULL) {
7137 			/*
7138 			 * It has to match on ident and src/dst address.
7139 			 */
7140 			if (ipf->ipf_ident == ident &&
7141 			    ipf->ipf_src == src &&
7142 			    ipf->ipf_dst == dst &&
7143 			    ipf->ipf_protocol == proto) {
7144 				/*
7145 				 * If we have received too many
7146 				 * duplicate fragments for this packet
7147 				 * free it.
7148 				 */
7149 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7150 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7151 					freemsg(mp);
7152 					mutex_exit(&ipfb->ipfb_lock);
7153 					return (NULL);
7154 				}
7155 				/* Found it. */
7156 				break;
7157 			}
7158 			ipfp = &ipf->ipf_hash_next;
7159 			continue;
7160 		}
7161 
7162 		/*
7163 		 * If we pruned the list, do we want to store this new
7164 		 * fragment?. We apply an optimization here based on the
7165 		 * fact that most fragments will be received in order.
7166 		 * So if the offset of this incoming fragment is zero,
7167 		 * it is the first fragment of a new packet. We will
7168 		 * keep it.  Otherwise drop the fragment, as we have
7169 		 * probably pruned the packet already (since the
7170 		 * packet cannot be found).
7171 		 */
7172 		if (pruned && offset != 0) {
7173 			mutex_exit(&ipfb->ipfb_lock);
7174 			freemsg(mp);
7175 			return (NULL);
7176 		}
7177 
7178 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7179 			/*
7180 			 * Too many fragmented packets in this hash
7181 			 * bucket. Free the oldest.
7182 			 */
7183 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7184 		}
7185 
7186 		/* New guy.  Allocate a frag message. */
7187 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7188 		if (mp1 == NULL) {
7189 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7190 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7191 			freemsg(mp);
7192 reass_done:
7193 			mutex_exit(&ipfb->ipfb_lock);
7194 			return (NULL);
7195 		}
7196 
7197 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7198 		mp1->b_cont = mp;
7199 
7200 		/* Initialize the fragment header. */
7201 		ipf = (ipf_t *)mp1->b_rptr;
7202 		ipf->ipf_mp = mp1;
7203 		ipf->ipf_ptphn = ipfp;
7204 		ipfp[0] = ipf;
7205 		ipf->ipf_hash_next = NULL;
7206 		ipf->ipf_ident = ident;
7207 		ipf->ipf_protocol = proto;
7208 		ipf->ipf_src = src;
7209 		ipf->ipf_dst = dst;
7210 		ipf->ipf_nf_hdr_len = 0;
7211 		/* Record reassembly start time. */
7212 		ipf->ipf_timestamp = gethrestime_sec();
7213 		/* Record ipf generation and account for frag header */
7214 		ipf->ipf_gen = ill->ill_ipf_gen++;
7215 		ipf->ipf_count = MBLKSIZE(mp1);
7216 		ipf->ipf_last_frag_seen = B_FALSE;
7217 		ipf->ipf_ecn = ecn_info;
7218 		ipf->ipf_num_dups = 0;
7219 		ipfb->ipfb_frag_pkts++;
7220 		ipf->ipf_checksum = 0;
7221 		ipf->ipf_checksum_flags = 0;
7222 
7223 		/* Store checksum value in fragment header */
7224 		if (sum_flags != 0) {
7225 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7226 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7227 			ipf->ipf_checksum = sum_val;
7228 			ipf->ipf_checksum_flags = sum_flags;
7229 		}
7230 
7231 		/*
7232 		 * We handle reassembly two ways.  In the easy case,
7233 		 * where all the fragments show up in order, we do
7234 		 * minimal bookkeeping, and just clip new pieces on
7235 		 * the end.  If we ever see a hole, then we go off
7236 		 * to ip_reassemble which has to mark the pieces and
7237 		 * keep track of the number of holes, etc.  Obviously,
7238 		 * the point of having both mechanisms is so we can
7239 		 * handle the easy case as efficiently as possible.
7240 		 */
7241 		if (offset == 0) {
7242 			/* Easy case, in-order reassembly so far. */
7243 			ipf->ipf_count += msg_len;
7244 			ipf->ipf_tail_mp = tail_mp;
7245 			/*
7246 			 * Keep track of next expected offset in
7247 			 * ipf_end.
7248 			 */
7249 			ipf->ipf_end = end;
7250 			ipf->ipf_nf_hdr_len = hdr_length;
7251 		} else {
7252 			/* Hard case, hole at the beginning. */
7253 			ipf->ipf_tail_mp = NULL;
7254 			/*
7255 			 * ipf_end == 0 means that we have given up
7256 			 * on easy reassembly.
7257 			 */
7258 			ipf->ipf_end = 0;
7259 
7260 			/* Forget checksum offload from now on */
7261 			ipf->ipf_checksum_flags = 0;
7262 
7263 			/*
7264 			 * ipf_hole_cnt is set by ip_reassemble.
7265 			 * ipf_count is updated by ip_reassemble.
7266 			 * No need to check for return value here
7267 			 * as we don't expect reassembly to complete
7268 			 * or fail for the first fragment itself.
7269 			 */
7270 			(void) ip_reassemble(mp, ipf,
7271 			    (frag_offset_flags & IPH_OFFSET) << 3,
7272 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7273 		}
7274 		/* Update per ipfb and ill byte counts */
7275 		ipfb->ipfb_count += ipf->ipf_count;
7276 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7277 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7278 		/* If the frag timer wasn't already going, start it. */
7279 		mutex_enter(&ill->ill_lock);
7280 		ill_frag_timer_start(ill);
7281 		mutex_exit(&ill->ill_lock);
7282 		goto reass_done;
7283 	}
7284 
7285 	/*
7286 	 * If the packet's flag has changed (it could be coming up
7287 	 * from an interface different than the previous, therefore
7288 	 * possibly different checksum capability), then forget about
7289 	 * any stored checksum states.  Otherwise add the value to
7290 	 * the existing one stored in the fragment header.
7291 	 */
7292 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7293 		sum_val += ipf->ipf_checksum;
7294 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7295 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7296 		ipf->ipf_checksum = sum_val;
7297 	} else if (ipf->ipf_checksum_flags != 0) {
7298 		/* Forget checksum offload from now on */
7299 		ipf->ipf_checksum_flags = 0;
7300 	}
7301 
7302 	/*
7303 	 * We have a new piece of a datagram which is already being
7304 	 * reassembled.  Update the ECN info if all IP fragments
7305 	 * are ECN capable.  If there is one which is not, clear
7306 	 * all the info.  If there is at least one which has CE
7307 	 * code point, IP needs to report that up to transport.
7308 	 */
7309 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7310 		if (ecn_info == IPH_ECN_CE)
7311 			ipf->ipf_ecn = IPH_ECN_CE;
7312 	} else {
7313 		ipf->ipf_ecn = IPH_ECN_NECT;
7314 	}
7315 	if (offset && ipf->ipf_end == offset) {
7316 		/* The new fragment fits at the end */
7317 		ipf->ipf_tail_mp->b_cont = mp;
7318 		/* Update the byte count */
7319 		ipf->ipf_count += msg_len;
7320 		/* Update per ipfb and ill byte counts */
7321 		ipfb->ipfb_count += msg_len;
7322 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7323 		atomic_add_32(&ill->ill_frag_count, msg_len);
7324 		if (frag_offset_flags & IPH_MF) {
7325 			/* More to come. */
7326 			ipf->ipf_end = end;
7327 			ipf->ipf_tail_mp = tail_mp;
7328 			goto reass_done;
7329 		}
7330 	} else {
7331 		/* Go do the hard cases. */
7332 		int ret;
7333 
7334 		if (offset == 0)
7335 			ipf->ipf_nf_hdr_len = hdr_length;
7336 
7337 		/* Save current byte count */
7338 		count = ipf->ipf_count;
7339 		ret = ip_reassemble(mp, ipf,
7340 		    (frag_offset_flags & IPH_OFFSET) << 3,
7341 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7342 		/* Count of bytes added and subtracted (freeb()ed) */
7343 		count = ipf->ipf_count - count;
7344 		if (count) {
7345 			/* Update per ipfb and ill byte counts */
7346 			ipfb->ipfb_count += count;
7347 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7348 			atomic_add_32(&ill->ill_frag_count, count);
7349 		}
7350 		if (ret == IP_REASS_PARTIAL) {
7351 			goto reass_done;
7352 		} else if (ret == IP_REASS_FAILED) {
7353 			/* Reassembly failed. Free up all resources */
7354 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7355 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7356 				IP_REASS_SET_START(t_mp, 0);
7357 				IP_REASS_SET_END(t_mp, 0);
7358 			}
7359 			freemsg(mp);
7360 			goto reass_done;
7361 		}
7362 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7363 	}
7364 	/*
7365 	 * We have completed reassembly.  Unhook the frag header from
7366 	 * the reassembly list.
7367 	 *
7368 	 * Before we free the frag header, record the ECN info
7369 	 * to report back to the transport.
7370 	 */
7371 	ecn_info = ipf->ipf_ecn;
7372 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7373 	ipfp = ipf->ipf_ptphn;
7374 
7375 	/* We need to supply these to caller */
7376 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7377 		sum_val = ipf->ipf_checksum;
7378 	else
7379 		sum_val = 0;
7380 
7381 	mp1 = ipf->ipf_mp;
7382 	count = ipf->ipf_count;
7383 	ipf = ipf->ipf_hash_next;
7384 	if (ipf != NULL)
7385 		ipf->ipf_ptphn = ipfp;
7386 	ipfp[0] = ipf;
7387 	atomic_add_32(&ill->ill_frag_count, -count);
7388 	ASSERT(ipfb->ipfb_count >= count);
7389 	ipfb->ipfb_count -= count;
7390 	ipfb->ipfb_frag_pkts--;
7391 	mutex_exit(&ipfb->ipfb_lock);
7392 	/* Ditch the frag header. */
7393 	mp = mp1->b_cont;
7394 
7395 	freeb(mp1);
7396 
7397 	/* Restore original IP length in header. */
7398 	packet_size = (uint32_t)msgdsize(mp);
7399 	if (packet_size > IP_MAXPACKET) {
7400 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7401 		ip_drop_input("Reassembled packet too large", mp, ill);
7402 		freemsg(mp);
7403 		return (NULL);
7404 	}
7405 
7406 	if (DB_REF(mp) > 1) {
7407 		mblk_t *mp2 = copymsg(mp);
7408 
7409 		if (mp2 == NULL) {
7410 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7411 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7412 			freemsg(mp);
7413 			return (NULL);
7414 		}
7415 		freemsg(mp);
7416 		mp = mp2;
7417 	}
7418 	ipha = (ipha_t *)mp->b_rptr;
7419 
7420 	ipha->ipha_length = htons((uint16_t)packet_size);
7421 	/* We're now complete, zip the frag state */
7422 	ipha->ipha_fragment_offset_and_flags = 0;
7423 	/* Record the ECN info. */
7424 	ipha->ipha_type_of_service &= 0xFC;
7425 	ipha->ipha_type_of_service |= ecn_info;
7426 
7427 	/* Update the receive attributes */
7428 	ira->ira_pktlen = packet_size;
7429 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7430 
7431 	/* Reassembly is successful; set checksum information in packet */
7432 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7433 	DB_CKSUMFLAGS(mp) = sum_flags;
7434 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7435 
7436 	return (mp);
7437 }
7438 
7439 /*
7440  * Pullup function that should be used for IP input in order to
7441  * ensure we do not loose the L2 source address; we need the l2 source
7442  * address for IP_RECVSLLA and for ndp_input.
7443  *
7444  * We return either NULL or b_rptr.
7445  */
7446 void *
7447 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7448 {
7449 	ill_t		*ill = ira->ira_ill;
7450 
7451 	if (ip_rput_pullups++ == 0) {
7452 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7453 		    "ip_pullup: %s forced us to "
7454 		    " pullup pkt, hdr len %ld, hdr addr %p",
7455 		    ill->ill_name, len, (void *)mp->b_rptr);
7456 	}
7457 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7458 		ip_setl2src(mp, ira, ira->ira_rill);
7459 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7460 	if (!pullupmsg(mp, len))
7461 		return (NULL);
7462 	else
7463 		return (mp->b_rptr);
7464 }
7465 
7466 /*
7467  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7468  * When called from the ULP ira_rill will be NULL hence the caller has to
7469  * pass in the ill.
7470  */
7471 /* ARGSUSED */
7472 void
7473 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7474 {
7475 	const uchar_t *addr;
7476 	int alen;
7477 
7478 	if (ira->ira_flags & IRAF_L2SRC_SET)
7479 		return;
7480 
7481 	ASSERT(ill != NULL);
7482 	alen = ill->ill_phys_addr_length;
7483 	ASSERT(alen <= sizeof (ira->ira_l2src));
7484 	if (ira->ira_mhip != NULL &&
7485 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7486 		bcopy(addr, ira->ira_l2src, alen);
7487 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7488 	    (addr = ill->ill_phys_addr) != NULL) {
7489 		bcopy(addr, ira->ira_l2src, alen);
7490 	} else {
7491 		bzero(ira->ira_l2src, alen);
7492 	}
7493 	ira->ira_flags |= IRAF_L2SRC_SET;
7494 }
7495 
7496 /*
7497  * check ip header length and align it.
7498  */
7499 mblk_t *
7500 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7501 {
7502 	ill_t	*ill = ira->ira_ill;
7503 	ssize_t len;
7504 
7505 	len = MBLKL(mp);
7506 
7507 	if (!OK_32PTR(mp->b_rptr))
7508 		IP_STAT(ill->ill_ipst, ip_notaligned);
7509 	else
7510 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7511 
7512 	/* Guard against bogus device drivers */
7513 	if (len < 0) {
7514 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7515 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7516 		freemsg(mp);
7517 		return (NULL);
7518 	}
7519 
7520 	if (len == 0) {
7521 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7522 		mblk_t *mp1 = mp->b_cont;
7523 
7524 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7525 			ip_setl2src(mp, ira, ira->ira_rill);
7526 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7527 
7528 		freeb(mp);
7529 		mp = mp1;
7530 		if (mp == NULL)
7531 			return (NULL);
7532 
7533 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7534 			return (mp);
7535 	}
7536 	if (ip_pullup(mp, min_size, ira) == NULL) {
7537 		if (msgdsize(mp) < min_size) {
7538 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7539 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7540 		} else {
7541 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7542 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7543 		}
7544 		freemsg(mp);
7545 		return (NULL);
7546 	}
7547 	return (mp);
7548 }
7549 
7550 /*
7551  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7552  */
7553 mblk_t *
7554 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7555     uint_t min_size, ip_recv_attr_t *ira)
7556 {
7557 	ill_t	*ill = ira->ira_ill;
7558 
7559 	/*
7560 	 * Make sure we have data length consistent
7561 	 * with the IP header.
7562 	 */
7563 	if (mp->b_cont == NULL) {
7564 		/* pkt_len is based on ipha_len, not the mblk length */
7565 		if (pkt_len < min_size) {
7566 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7567 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7568 			freemsg(mp);
7569 			return (NULL);
7570 		}
7571 		if (len < 0) {
7572 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7573 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7574 			freemsg(mp);
7575 			return (NULL);
7576 		}
7577 		/* Drop any pad */
7578 		mp->b_wptr = rptr + pkt_len;
7579 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7580 		ASSERT(pkt_len >= min_size);
7581 		if (pkt_len < min_size) {
7582 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7583 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7584 			freemsg(mp);
7585 			return (NULL);
7586 		}
7587 		if (len < 0) {
7588 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7589 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7590 			freemsg(mp);
7591 			return (NULL);
7592 		}
7593 		/* Drop any pad */
7594 		(void) adjmsg(mp, -len);
7595 		/*
7596 		 * adjmsg may have freed an mblk from the chain, hence
7597 		 * invalidate any hw checksum here. This will force IP to
7598 		 * calculate the checksum in sw, but only for this packet.
7599 		 */
7600 		DB_CKSUMFLAGS(mp) = 0;
7601 		IP_STAT(ill->ill_ipst, ip_multimblk);
7602 	}
7603 	return (mp);
7604 }
7605 
7606 /*
7607  * Check that the IPv4 opt_len is consistent with the packet and pullup
7608  * the options.
7609  */
7610 mblk_t *
7611 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7612     ip_recv_attr_t *ira)
7613 {
7614 	ill_t	*ill = ira->ira_ill;
7615 	ssize_t len;
7616 
7617 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7618 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7619 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7620 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7621 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7622 		freemsg(mp);
7623 		return (NULL);
7624 	}
7625 
7626 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7627 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7628 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7629 		freemsg(mp);
7630 		return (NULL);
7631 	}
7632 	/*
7633 	 * Recompute complete header length and make sure we
7634 	 * have access to all of it.
7635 	 */
7636 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7637 	if (len > (mp->b_wptr - mp->b_rptr)) {
7638 		if (len > pkt_len) {
7639 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7640 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7641 			freemsg(mp);
7642 			return (NULL);
7643 		}
7644 		if (ip_pullup(mp, len, ira) == NULL) {
7645 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7646 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7647 			freemsg(mp);
7648 			return (NULL);
7649 		}
7650 	}
7651 	return (mp);
7652 }
7653 
7654 /*
7655  * Returns a new ire, or the same ire, or NULL.
7656  * If a different IRE is returned, then it is held; the caller
7657  * needs to release it.
7658  * In no case is there any hold/release on the ire argument.
7659  */
7660 ire_t *
7661 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7662 {
7663 	ire_t		*new_ire;
7664 	ill_t		*ire_ill;
7665 	uint_t		ifindex;
7666 	ip_stack_t	*ipst = ill->ill_ipst;
7667 	boolean_t	strict_check = B_FALSE;
7668 
7669 	/*
7670 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7671 	 * issue (e.g. packet received on an underlying interface matched an
7672 	 * IRE_LOCAL on its associated group interface).
7673 	 */
7674 	ASSERT(ire->ire_ill != NULL);
7675 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7676 		return (ire);
7677 
7678 	/*
7679 	 * Do another ire lookup here, using the ingress ill, to see if the
7680 	 * interface is in a usesrc group.
7681 	 * As long as the ills belong to the same group, we don't consider
7682 	 * them to be arriving on the wrong interface. Thus, if the switch
7683 	 * is doing inbound load spreading, we won't drop packets when the
7684 	 * ip*_strict_dst_multihoming switch is on.
7685 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7686 	 * where the local address may not be unique. In this case we were
7687 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7688 	 * actually returned. The new lookup, which is more specific, should
7689 	 * only find the IRE_LOCAL associated with the ingress ill if one
7690 	 * exists.
7691 	 */
7692 	if (ire->ire_ipversion == IPV4_VERSION) {
7693 		if (ipst->ips_ip_strict_dst_multihoming)
7694 			strict_check = B_TRUE;
7695 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7696 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7697 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7698 	} else {
7699 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7700 		if (ipst->ips_ipv6_strict_dst_multihoming)
7701 			strict_check = B_TRUE;
7702 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7703 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7704 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7705 	}
7706 	/*
7707 	 * If the same ire that was returned in ip_input() is found then this
7708 	 * is an indication that usesrc groups are in use. The packet
7709 	 * arrived on a different ill in the group than the one associated with
7710 	 * the destination address.  If a different ire was found then the same
7711 	 * IP address must be hosted on multiple ills. This is possible with
7712 	 * unnumbered point2point interfaces. We switch to use this new ire in
7713 	 * order to have accurate interface statistics.
7714 	 */
7715 	if (new_ire != NULL) {
7716 		/* Note: held in one case but not the other? Caller handles */
7717 		if (new_ire != ire)
7718 			return (new_ire);
7719 		/* Unchanged */
7720 		ire_refrele(new_ire);
7721 		return (ire);
7722 	}
7723 
7724 	/*
7725 	 * Chase pointers once and store locally.
7726 	 */
7727 	ASSERT(ire->ire_ill != NULL);
7728 	ire_ill = ire->ire_ill;
7729 	ifindex = ill->ill_usesrc_ifindex;
7730 
7731 	/*
7732 	 * Check if it's a legal address on the 'usesrc' interface.
7733 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7734 	 * can just check phyint_ifindex.
7735 	 */
7736 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7737 		return (ire);
7738 	}
7739 
7740 	/*
7741 	 * If the ip*_strict_dst_multihoming switch is on then we can
7742 	 * only accept this packet if the interface is marked as routing.
7743 	 */
7744 	if (!(strict_check))
7745 		return (ire);
7746 
7747 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7748 		return (ire);
7749 	}
7750 	return (NULL);
7751 }
7752 
7753 /*
7754  * This function is used to construct a mac_header_info_s from a
7755  * DL_UNITDATA_IND message.
7756  * The address fields in the mhi structure points into the message,
7757  * thus the caller can't use those fields after freeing the message.
7758  *
7759  * We determine whether the packet received is a non-unicast packet
7760  * and in doing so, determine whether or not it is broadcast vs multicast.
7761  * For it to be a broadcast packet, we must have the appropriate mblk_t
7762  * hanging off the ill_t.  If this is either not present or doesn't match
7763  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7764  * to be multicast.  Thus NICs that have no broadcast address (or no
7765  * capability for one, such as point to point links) cannot return as
7766  * the packet being broadcast.
7767  */
7768 void
7769 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7770 {
7771 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7772 	mblk_t *bmp;
7773 	uint_t extra_offset;
7774 
7775 	bzero(mhip, sizeof (struct mac_header_info_s));
7776 
7777 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7778 
7779 	if (ill->ill_sap_length < 0)
7780 		extra_offset = 0;
7781 	else
7782 		extra_offset = ill->ill_sap_length;
7783 
7784 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7785 	    extra_offset;
7786 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7787 	    extra_offset;
7788 
7789 	if (!ind->dl_group_address)
7790 		return;
7791 
7792 	/* Multicast or broadcast */
7793 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7794 
7795 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7796 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7797 	    (bmp = ill->ill_bcast_mp) != NULL) {
7798 		dl_unitdata_req_t *dlur;
7799 		uint8_t *bphys_addr;
7800 
7801 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7802 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7803 		    extra_offset;
7804 
7805 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7806 		    ind->dl_dest_addr_length) == 0)
7807 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7808 	}
7809 }
7810 
7811 /*
7812  * This function is used to construct a mac_header_info_s from a
7813  * M_DATA fastpath message from a DLPI driver.
7814  * The address fields in the mhi structure points into the message,
7815  * thus the caller can't use those fields after freeing the message.
7816  *
7817  * We determine whether the packet received is a non-unicast packet
7818  * and in doing so, determine whether or not it is broadcast vs multicast.
7819  * For it to be a broadcast packet, we must have the appropriate mblk_t
7820  * hanging off the ill_t.  If this is either not present or doesn't match
7821  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7822  * to be multicast.  Thus NICs that have no broadcast address (or no
7823  * capability for one, such as point to point links) cannot return as
7824  * the packet being broadcast.
7825  */
7826 void
7827 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7828 {
7829 	mblk_t *bmp;
7830 	struct ether_header *pether;
7831 
7832 	bzero(mhip, sizeof (struct mac_header_info_s));
7833 
7834 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7835 
7836 	pether = (struct ether_header *)((char *)mp->b_rptr
7837 	    - sizeof (struct ether_header));
7838 
7839 	/*
7840 	 * Make sure the interface is an ethernet type, since we don't
7841 	 * know the header format for anything but Ethernet. Also make
7842 	 * sure we are pointing correctly above db_base.
7843 	 */
7844 	if (ill->ill_type != IFT_ETHER)
7845 		return;
7846 
7847 retry:
7848 	if ((uchar_t *)pether < mp->b_datap->db_base)
7849 		return;
7850 
7851 	/* Is there a VLAN tag? */
7852 	if (ill->ill_isv6) {
7853 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7854 			pether = (struct ether_header *)((char *)pether - 4);
7855 			goto retry;
7856 		}
7857 	} else {
7858 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7859 			pether = (struct ether_header *)((char *)pether - 4);
7860 			goto retry;
7861 		}
7862 	}
7863 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7864 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7865 
7866 	if (!(mhip->mhi_daddr[0] & 0x01))
7867 		return;
7868 
7869 	/* Multicast or broadcast */
7870 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7871 
7872 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7873 		dl_unitdata_req_t *dlur;
7874 		uint8_t *bphys_addr;
7875 		uint_t	addrlen;
7876 
7877 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7878 		addrlen = dlur->dl_dest_addr_length;
7879 		if (ill->ill_sap_length < 0) {
7880 			bphys_addr = (uchar_t *)dlur +
7881 			    dlur->dl_dest_addr_offset;
7882 			addrlen += ill->ill_sap_length;
7883 		} else {
7884 			bphys_addr = (uchar_t *)dlur +
7885 			    dlur->dl_dest_addr_offset +
7886 			    ill->ill_sap_length;
7887 			addrlen -= ill->ill_sap_length;
7888 		}
7889 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7890 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7891 	}
7892 }
7893 
7894 /*
7895  * Handle anything but M_DATA messages
7896  * We see the DL_UNITDATA_IND which are part
7897  * of the data path, and also the other messages from the driver.
7898  */
7899 void
7900 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7901 {
7902 	mblk_t		*first_mp;
7903 	struct iocblk   *iocp;
7904 	struct mac_header_info_s mhi;
7905 
7906 	switch (DB_TYPE(mp)) {
7907 	case M_PROTO:
7908 	case M_PCPROTO: {
7909 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7910 		    DL_UNITDATA_IND) {
7911 			/* Go handle anything other than data elsewhere. */
7912 			ip_rput_dlpi(ill, mp);
7913 			return;
7914 		}
7915 
7916 		first_mp = mp;
7917 		mp = first_mp->b_cont;
7918 		first_mp->b_cont = NULL;
7919 
7920 		if (mp == NULL) {
7921 			freeb(first_mp);
7922 			return;
7923 		}
7924 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7925 		if (ill->ill_isv6)
7926 			ip_input_v6(ill, NULL, mp, &mhi);
7927 		else
7928 			ip_input(ill, NULL, mp, &mhi);
7929 
7930 		/* Ditch the DLPI header. */
7931 		freeb(first_mp);
7932 		return;
7933 	}
7934 	case M_IOCACK:
7935 		iocp = (struct iocblk *)mp->b_rptr;
7936 		switch (iocp->ioc_cmd) {
7937 		case DL_IOC_HDR_INFO:
7938 			ill_fastpath_ack(ill, mp);
7939 			return;
7940 		default:
7941 			putnext(ill->ill_rq, mp);
7942 			return;
7943 		}
7944 		/* FALLTHRU */
7945 	case M_ERROR:
7946 	case M_HANGUP:
7947 		mutex_enter(&ill->ill_lock);
7948 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7949 			mutex_exit(&ill->ill_lock);
7950 			freemsg(mp);
7951 			return;
7952 		}
7953 		ill_refhold_locked(ill);
7954 		mutex_exit(&ill->ill_lock);
7955 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7956 		    B_FALSE);
7957 		return;
7958 	case M_CTL:
7959 		putnext(ill->ill_rq, mp);
7960 		return;
7961 	case M_IOCNAK:
7962 		ip1dbg(("got iocnak "));
7963 		iocp = (struct iocblk *)mp->b_rptr;
7964 		switch (iocp->ioc_cmd) {
7965 		case DL_IOC_HDR_INFO:
7966 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7967 			return;
7968 		default:
7969 			break;
7970 		}
7971 		/* FALLTHRU */
7972 	default:
7973 		putnext(ill->ill_rq, mp);
7974 		return;
7975 	}
7976 }
7977 
7978 /* Read side put procedure.  Packets coming from the wire arrive here. */
7979 void
7980 ip_rput(queue_t *q, mblk_t *mp)
7981 {
7982 	ill_t	*ill;
7983 	union DL_primitives *dl;
7984 
7985 	ill = (ill_t *)q->q_ptr;
7986 
7987 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
7988 		/*
7989 		 * If things are opening or closing, only accept high-priority
7990 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
7991 		 * created; on close, things hanging off the ill may have been
7992 		 * freed already.)
7993 		 */
7994 		dl = (union DL_primitives *)mp->b_rptr;
7995 		if (DB_TYPE(mp) != M_PCPROTO ||
7996 		    dl->dl_primitive == DL_UNITDATA_IND) {
7997 			inet_freemsg(mp);
7998 			return;
7999 		}
8000 	}
8001 	if (DB_TYPE(mp) == M_DATA) {
8002 		struct mac_header_info_s mhi;
8003 
8004 		ip_mdata_to_mhi(ill, mp, &mhi);
8005 		ip_input(ill, NULL, mp, &mhi);
8006 	} else {
8007 		ip_rput_notdata(ill, mp);
8008 	}
8009 }
8010 
8011 /*
8012  * Move the information to a copy.
8013  */
8014 mblk_t *
8015 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8016 {
8017 	mblk_t		*mp1;
8018 	ill_t		*ill = ira->ira_ill;
8019 	ip_stack_t	*ipst = ill->ill_ipst;
8020 
8021 	IP_STAT(ipst, ip_db_ref);
8022 
8023 	/* Make sure we have ira_l2src before we loose the original mblk */
8024 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
8025 		ip_setl2src(mp, ira, ira->ira_rill);
8026 
8027 	mp1 = copymsg(mp);
8028 	if (mp1 == NULL) {
8029 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8030 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
8031 		freemsg(mp);
8032 		return (NULL);
8033 	}
8034 	/* preserve the hardware checksum flags and data, if present */
8035 	if (DB_CKSUMFLAGS(mp) != 0) {
8036 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8037 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8038 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8039 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8040 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8041 	}
8042 	freemsg(mp);
8043 	return (mp1);
8044 }
8045 
8046 static void
8047 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8048     t_uscalar_t err)
8049 {
8050 	if (dl_err == DL_SYSERR) {
8051 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8052 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8053 		    ill->ill_name, dl_primstr(prim), err);
8054 		return;
8055 	}
8056 
8057 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8058 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8059 	    dl_errstr(dl_err));
8060 }
8061 
8062 /*
8063  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8064  * than DL_UNITDATA_IND messages. If we need to process this message
8065  * exclusively, we call qwriter_ip, in which case we also need to call
8066  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8067  */
8068 void
8069 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8070 {
8071 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8072 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8073 	queue_t		*q = ill->ill_rq;
8074 	t_uscalar_t	prim = dloa->dl_primitive;
8075 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8076 
8077 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8078 	    char *, dl_primstr(prim), ill_t *, ill);
8079 	ip1dbg(("ip_rput_dlpi"));
8080 
8081 	/*
8082 	 * If we received an ACK but didn't send a request for it, then it
8083 	 * can't be part of any pending operation; discard up-front.
8084 	 */
8085 	switch (prim) {
8086 	case DL_ERROR_ACK:
8087 		reqprim = dlea->dl_error_primitive;
8088 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8089 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8090 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8091 		    dlea->dl_unix_errno));
8092 		break;
8093 	case DL_OK_ACK:
8094 		reqprim = dloa->dl_correct_primitive;
8095 		break;
8096 	case DL_INFO_ACK:
8097 		reqprim = DL_INFO_REQ;
8098 		break;
8099 	case DL_BIND_ACK:
8100 		reqprim = DL_BIND_REQ;
8101 		break;
8102 	case DL_PHYS_ADDR_ACK:
8103 		reqprim = DL_PHYS_ADDR_REQ;
8104 		break;
8105 	case DL_NOTIFY_ACK:
8106 		reqprim = DL_NOTIFY_REQ;
8107 		break;
8108 	case DL_CAPABILITY_ACK:
8109 		reqprim = DL_CAPABILITY_REQ;
8110 		break;
8111 	}
8112 
8113 	if (prim != DL_NOTIFY_IND) {
8114 		if (reqprim == DL_PRIM_INVAL ||
8115 		    !ill_dlpi_pending(ill, reqprim)) {
8116 			/* Not a DLPI message we support or expected */
8117 			freemsg(mp);
8118 			return;
8119 		}
8120 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8121 		    dl_primstr(reqprim)));
8122 	}
8123 
8124 	switch (reqprim) {
8125 	case DL_UNBIND_REQ:
8126 		/*
8127 		 * NOTE: we mark the unbind as complete even if we got a
8128 		 * DL_ERROR_ACK, since there's not much else we can do.
8129 		 */
8130 		mutex_enter(&ill->ill_lock);
8131 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8132 		cv_signal(&ill->ill_cv);
8133 		mutex_exit(&ill->ill_lock);
8134 		break;
8135 
8136 	case DL_ENABMULTI_REQ:
8137 		if (prim == DL_OK_ACK) {
8138 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8139 				ill->ill_dlpi_multicast_state = IDS_OK;
8140 		}
8141 		break;
8142 	}
8143 
8144 	/*
8145 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8146 	 * need to become writer to continue to process it.  Because an
8147 	 * exclusive operation doesn't complete until replies to all queued
8148 	 * DLPI messages have been received, we know we're in the middle of an
8149 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8150 	 *
8151 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8152 	 * Since this is on the ill stream we unconditionally bump up the
8153 	 * refcount without doing ILL_CAN_LOOKUP().
8154 	 */
8155 	ill_refhold(ill);
8156 	if (prim == DL_NOTIFY_IND)
8157 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8158 	else
8159 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8160 }
8161 
8162 /*
8163  * Handling of DLPI messages that require exclusive access to the ipsq.
8164  *
8165  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8166  * happen here. (along with mi_copy_done)
8167  */
8168 /* ARGSUSED */
8169 static void
8170 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8171 {
8172 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8173 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8174 	int		err = 0;
8175 	ill_t		*ill = (ill_t *)q->q_ptr;
8176 	ipif_t		*ipif = NULL;
8177 	mblk_t		*mp1 = NULL;
8178 	conn_t		*connp = NULL;
8179 	t_uscalar_t	paddrreq;
8180 	mblk_t		*mp_hw;
8181 	boolean_t	success;
8182 	boolean_t	ioctl_aborted = B_FALSE;
8183 	boolean_t	log = B_TRUE;
8184 
8185 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8186 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8187 
8188 	ip1dbg(("ip_rput_dlpi_writer .."));
8189 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8190 	ASSERT(IAM_WRITER_ILL(ill));
8191 
8192 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8193 	/*
8194 	 * The current ioctl could have been aborted by the user and a new
8195 	 * ioctl to bring up another ill could have started. We could still
8196 	 * get a response from the driver later.
8197 	 */
8198 	if (ipif != NULL && ipif->ipif_ill != ill)
8199 		ioctl_aborted = B_TRUE;
8200 
8201 	switch (dloa->dl_primitive) {
8202 	case DL_ERROR_ACK:
8203 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8204 		    dl_primstr(dlea->dl_error_primitive)));
8205 
8206 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8207 		    char *, dl_primstr(dlea->dl_error_primitive),
8208 		    ill_t *, ill);
8209 
8210 		switch (dlea->dl_error_primitive) {
8211 		case DL_DISABMULTI_REQ:
8212 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8213 			break;
8214 		case DL_PROMISCON_REQ:
8215 		case DL_PROMISCOFF_REQ:
8216 		case DL_UNBIND_REQ:
8217 		case DL_ATTACH_REQ:
8218 		case DL_INFO_REQ:
8219 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8220 			break;
8221 		case DL_NOTIFY_REQ:
8222 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8223 			log = B_FALSE;
8224 			break;
8225 		case DL_PHYS_ADDR_REQ:
8226 			/*
8227 			 * For IPv6 only, there are two additional
8228 			 * phys_addr_req's sent to the driver to get the
8229 			 * IPv6 token and lla. This allows IP to acquire
8230 			 * the hardware address format for a given interface
8231 			 * without having built in knowledge of the hardware
8232 			 * address. ill_phys_addr_pend keeps track of the last
8233 			 * DL_PAR sent so we know which response we are
8234 			 * dealing with. ill_dlpi_done will update
8235 			 * ill_phys_addr_pend when it sends the next req.
8236 			 * We don't complete the IOCTL until all three DL_PARs
8237 			 * have been attempted, so set *_len to 0 and break.
8238 			 */
8239 			paddrreq = ill->ill_phys_addr_pend;
8240 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8241 			if (paddrreq == DL_IPV6_TOKEN) {
8242 				ill->ill_token_length = 0;
8243 				log = B_FALSE;
8244 				break;
8245 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8246 				ill->ill_nd_lla_len = 0;
8247 				log = B_FALSE;
8248 				break;
8249 			}
8250 			/*
8251 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8252 			 * We presumably have an IOCTL hanging out waiting
8253 			 * for completion. Find it and complete the IOCTL
8254 			 * with the error noted.
8255 			 * However, ill_dl_phys was called on an ill queue
8256 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8257 			 * set. But the ioctl is known to be pending on ill_wq.
8258 			 */
8259 			if (!ill->ill_ifname_pending)
8260 				break;
8261 			ill->ill_ifname_pending = 0;
8262 			if (!ioctl_aborted)
8263 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8264 			if (mp1 != NULL) {
8265 				/*
8266 				 * This operation (SIOCSLIFNAME) must have
8267 				 * happened on the ill. Assert there is no conn
8268 				 */
8269 				ASSERT(connp == NULL);
8270 				q = ill->ill_wq;
8271 			}
8272 			break;
8273 		case DL_BIND_REQ:
8274 			ill_dlpi_done(ill, DL_BIND_REQ);
8275 			if (ill->ill_ifname_pending)
8276 				break;
8277 			mutex_enter(&ill->ill_lock);
8278 			ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8279 			mutex_exit(&ill->ill_lock);
8280 			/*
8281 			 * Something went wrong with the bind.  We presumably
8282 			 * have an IOCTL hanging out waiting for completion.
8283 			 * Find it, take down the interface that was coming
8284 			 * up, and complete the IOCTL with the error noted.
8285 			 */
8286 			if (!ioctl_aborted)
8287 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8288 			if (mp1 != NULL) {
8289 				/*
8290 				 * This might be a result of a DL_NOTE_REPLUMB
8291 				 * notification. In that case, connp is NULL.
8292 				 */
8293 				if (connp != NULL)
8294 					q = CONNP_TO_WQ(connp);
8295 
8296 				(void) ipif_down(ipif, NULL, NULL);
8297 				/* error is set below the switch */
8298 			}
8299 			break;
8300 		case DL_ENABMULTI_REQ:
8301 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8302 
8303 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8304 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8305 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8306 
8307 				printf("ip: joining multicasts failed (%d)"
8308 				    " on %s - will use link layer "
8309 				    "broadcasts for multicast\n",
8310 				    dlea->dl_errno, ill->ill_name);
8311 
8312 				/*
8313 				 * Set up for multi_bcast; We are the
8314 				 * writer, so ok to access ill->ill_ipif
8315 				 * without any lock.
8316 				 */
8317 				mutex_enter(&ill->ill_phyint->phyint_lock);
8318 				ill->ill_phyint->phyint_flags |=
8319 				    PHYI_MULTI_BCAST;
8320 				mutex_exit(&ill->ill_phyint->phyint_lock);
8321 
8322 			}
8323 			freemsg(mp);	/* Don't want to pass this up */
8324 			return;
8325 		case DL_CAPABILITY_REQ:
8326 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8327 			    "DL_CAPABILITY REQ\n"));
8328 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8329 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8330 			ill_capability_done(ill);
8331 			freemsg(mp);
8332 			return;
8333 		}
8334 		/*
8335 		 * Note the error for IOCTL completion (mp1 is set when
8336 		 * ready to complete ioctl). If ill_ifname_pending_err is
8337 		 * set, an error occured during plumbing (ill_ifname_pending),
8338 		 * so we want to report that error.
8339 		 *
8340 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8341 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8342 		 * expected to get errack'd if the driver doesn't support
8343 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8344 		 * if these error conditions are encountered.
8345 		 */
8346 		if (mp1 != NULL) {
8347 			if (ill->ill_ifname_pending_err != 0)  {
8348 				err = ill->ill_ifname_pending_err;
8349 				ill->ill_ifname_pending_err = 0;
8350 			} else {
8351 				err = dlea->dl_unix_errno ?
8352 				    dlea->dl_unix_errno : ENXIO;
8353 			}
8354 		/*
8355 		 * If we're plumbing an interface and an error hasn't already
8356 		 * been saved, set ill_ifname_pending_err to the error passed
8357 		 * up. Ignore the error if log is B_FALSE (see comment above).
8358 		 */
8359 		} else if (log && ill->ill_ifname_pending &&
8360 		    ill->ill_ifname_pending_err == 0) {
8361 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8362 			    dlea->dl_unix_errno : ENXIO;
8363 		}
8364 
8365 		if (log)
8366 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8367 			    dlea->dl_errno, dlea->dl_unix_errno);
8368 		break;
8369 	case DL_CAPABILITY_ACK:
8370 		ill_capability_ack(ill, mp);
8371 		/*
8372 		 * The message has been handed off to ill_capability_ack
8373 		 * and must not be freed below
8374 		 */
8375 		mp = NULL;
8376 		break;
8377 
8378 	case DL_INFO_ACK:
8379 		/* Call a routine to handle this one. */
8380 		ill_dlpi_done(ill, DL_INFO_REQ);
8381 		ip_ll_subnet_defaults(ill, mp);
8382 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8383 		return;
8384 	case DL_BIND_ACK:
8385 		/*
8386 		 * We should have an IOCTL waiting on this unless
8387 		 * sent by ill_dl_phys, in which case just return
8388 		 */
8389 		ill_dlpi_done(ill, DL_BIND_REQ);
8390 
8391 		if (ill->ill_ifname_pending) {
8392 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8393 			    ill_t *, ill, mblk_t *, mp);
8394 			break;
8395 		}
8396 		mutex_enter(&ill->ill_lock);
8397 		ill->ill_dl_up = 1;
8398 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8399 		mutex_exit(&ill->ill_lock);
8400 
8401 		if (!ioctl_aborted)
8402 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8403 		if (mp1 == NULL) {
8404 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8405 			break;
8406 		}
8407 		/*
8408 		 * mp1 was added by ill_dl_up(). if that is a result of
8409 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8410 		 */
8411 		if (connp != NULL)
8412 			q = CONNP_TO_WQ(connp);
8413 		/*
8414 		 * We are exclusive. So nothing can change even after
8415 		 * we get the pending mp.
8416 		 */
8417 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8418 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8419 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8420 
8421 		/*
8422 		 * Now bring up the resolver; when that is complete, we'll
8423 		 * create IREs.  Note that we intentionally mirror what
8424 		 * ipif_up() would have done, because we got here by way of
8425 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8426 		 */
8427 		if (ill->ill_isv6) {
8428 			/*
8429 			 * v6 interfaces.
8430 			 * Unlike ARP which has to do another bind
8431 			 * and attach, once we get here we are
8432 			 * done with NDP
8433 			 */
8434 			(void) ipif_resolver_up(ipif, Res_act_initial);
8435 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8436 				err = ipif_up_done_v6(ipif);
8437 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8438 			/*
8439 			 * ARP and other v4 external resolvers.
8440 			 * Leave the pending mblk intact so that
8441 			 * the ioctl completes in ip_rput().
8442 			 */
8443 			if (connp != NULL)
8444 				mutex_enter(&connp->conn_lock);
8445 			mutex_enter(&ill->ill_lock);
8446 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8447 			mutex_exit(&ill->ill_lock);
8448 			if (connp != NULL)
8449 				mutex_exit(&connp->conn_lock);
8450 			if (success) {
8451 				err = ipif_resolver_up(ipif, Res_act_initial);
8452 				if (err == EINPROGRESS) {
8453 					freemsg(mp);
8454 					return;
8455 				}
8456 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8457 			} else {
8458 				/* The conn has started closing */
8459 				err = EINTR;
8460 			}
8461 		} else {
8462 			/*
8463 			 * This one is complete. Reply to pending ioctl.
8464 			 */
8465 			(void) ipif_resolver_up(ipif, Res_act_initial);
8466 			err = ipif_up_done(ipif);
8467 		}
8468 
8469 		if ((err == 0) && (ill->ill_up_ipifs)) {
8470 			err = ill_up_ipifs(ill, q, mp1);
8471 			if (err == EINPROGRESS) {
8472 				freemsg(mp);
8473 				return;
8474 			}
8475 		}
8476 
8477 		/*
8478 		 * If we have a moved ipif to bring up, and everything has
8479 		 * succeeded to this point, bring it up on the IPMP ill.
8480 		 * Otherwise, leave it down -- the admin can try to bring it
8481 		 * up by hand if need be.
8482 		 */
8483 		if (ill->ill_move_ipif != NULL) {
8484 			if (err != 0) {
8485 				ill->ill_move_ipif = NULL;
8486 			} else {
8487 				ipif = ill->ill_move_ipif;
8488 				ill->ill_move_ipif = NULL;
8489 				err = ipif_up(ipif, q, mp1);
8490 				if (err == EINPROGRESS) {
8491 					freemsg(mp);
8492 					return;
8493 				}
8494 			}
8495 		}
8496 		break;
8497 
8498 	case DL_NOTIFY_IND: {
8499 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8500 		uint_t orig_mtu, orig_mc_mtu;
8501 
8502 		switch (notify->dl_notification) {
8503 		case DL_NOTE_PHYS_ADDR:
8504 			err = ill_set_phys_addr(ill, mp);
8505 			break;
8506 
8507 		case DL_NOTE_REPLUMB:
8508 			/*
8509 			 * Directly return after calling ill_replumb().
8510 			 * Note that we should not free mp as it is reused
8511 			 * in the ill_replumb() function.
8512 			 */
8513 			err = ill_replumb(ill, mp);
8514 			return;
8515 
8516 		case DL_NOTE_FASTPATH_FLUSH:
8517 			nce_flush(ill, B_FALSE);
8518 			break;
8519 
8520 		case DL_NOTE_SDU_SIZE:
8521 		case DL_NOTE_SDU_SIZE2:
8522 			/*
8523 			 * The dce and fragmentation code can cope with
8524 			 * this changing while packets are being sent.
8525 			 * When packets are sent ip_output will discover
8526 			 * a change.
8527 			 *
8528 			 * Change the MTU size of the interface.
8529 			 */
8530 			mutex_enter(&ill->ill_lock);
8531 			orig_mtu = ill->ill_mtu;
8532 			orig_mc_mtu = ill->ill_mc_mtu;
8533 			switch (notify->dl_notification) {
8534 			case DL_NOTE_SDU_SIZE:
8535 				ill->ill_current_frag =
8536 				    (uint_t)notify->dl_data;
8537 				ill->ill_mc_mtu = (uint_t)notify->dl_data;
8538 				break;
8539 			case DL_NOTE_SDU_SIZE2:
8540 				ill->ill_current_frag =
8541 				    (uint_t)notify->dl_data1;
8542 				ill->ill_mc_mtu = (uint_t)notify->dl_data2;
8543 				break;
8544 			}
8545 			if (ill->ill_current_frag > ill->ill_max_frag)
8546 				ill->ill_max_frag = ill->ill_current_frag;
8547 
8548 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8549 				ill->ill_mtu = ill->ill_current_frag;
8550 
8551 				/*
8552 				 * If ill_user_mtu was set (via
8553 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8554 				 */
8555 				if (ill->ill_user_mtu != 0 &&
8556 				    ill->ill_user_mtu < ill->ill_mtu)
8557 					ill->ill_mtu = ill->ill_user_mtu;
8558 
8559 				if (ill->ill_user_mtu != 0 &&
8560 				    ill->ill_user_mtu < ill->ill_mc_mtu)
8561 					ill->ill_mc_mtu = ill->ill_user_mtu;
8562 
8563 				if (ill->ill_isv6) {
8564 					if (ill->ill_mtu < IPV6_MIN_MTU)
8565 						ill->ill_mtu = IPV6_MIN_MTU;
8566 					if (ill->ill_mc_mtu < IPV6_MIN_MTU)
8567 						ill->ill_mc_mtu = IPV6_MIN_MTU;
8568 				} else {
8569 					if (ill->ill_mtu < IP_MIN_MTU)
8570 						ill->ill_mtu = IP_MIN_MTU;
8571 					if (ill->ill_mc_mtu < IP_MIN_MTU)
8572 						ill->ill_mc_mtu = IP_MIN_MTU;
8573 				}
8574 			} else if (ill->ill_mc_mtu > ill->ill_mtu) {
8575 				ill->ill_mc_mtu = ill->ill_mtu;
8576 			}
8577 
8578 			mutex_exit(&ill->ill_lock);
8579 			/*
8580 			 * Make sure all dce_generation checks find out
8581 			 * that ill_mtu/ill_mc_mtu has changed.
8582 			 */
8583 			if (orig_mtu != ill->ill_mtu ||
8584 			    orig_mc_mtu != ill->ill_mc_mtu) {
8585 				dce_increment_all_generations(ill->ill_isv6,
8586 				    ill->ill_ipst);
8587 			}
8588 
8589 			/*
8590 			 * Refresh IPMP meta-interface MTU if necessary.
8591 			 */
8592 			if (IS_UNDER_IPMP(ill))
8593 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8594 			break;
8595 
8596 		case DL_NOTE_LINK_UP:
8597 		case DL_NOTE_LINK_DOWN: {
8598 			/*
8599 			 * We are writer. ill / phyint / ipsq assocs stable.
8600 			 * The RUNNING flag reflects the state of the link.
8601 			 */
8602 			phyint_t *phyint = ill->ill_phyint;
8603 			uint64_t new_phyint_flags;
8604 			boolean_t changed = B_FALSE;
8605 			boolean_t went_up;
8606 
8607 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8608 			mutex_enter(&phyint->phyint_lock);
8609 
8610 			new_phyint_flags = went_up ?
8611 			    phyint->phyint_flags | PHYI_RUNNING :
8612 			    phyint->phyint_flags & ~PHYI_RUNNING;
8613 
8614 			if (IS_IPMP(ill)) {
8615 				new_phyint_flags = went_up ?
8616 				    new_phyint_flags & ~PHYI_FAILED :
8617 				    new_phyint_flags | PHYI_FAILED;
8618 			}
8619 
8620 			if (new_phyint_flags != phyint->phyint_flags) {
8621 				phyint->phyint_flags = new_phyint_flags;
8622 				changed = B_TRUE;
8623 			}
8624 			mutex_exit(&phyint->phyint_lock);
8625 			/*
8626 			 * ill_restart_dad handles the DAD restart and routing
8627 			 * socket notification logic.
8628 			 */
8629 			if (changed) {
8630 				ill_restart_dad(phyint->phyint_illv4, went_up);
8631 				ill_restart_dad(phyint->phyint_illv6, went_up);
8632 			}
8633 			break;
8634 		}
8635 		case DL_NOTE_PROMISC_ON_PHYS: {
8636 			phyint_t *phyint = ill->ill_phyint;
8637 
8638 			mutex_enter(&phyint->phyint_lock);
8639 			phyint->phyint_flags |= PHYI_PROMISC;
8640 			mutex_exit(&phyint->phyint_lock);
8641 			break;
8642 		}
8643 		case DL_NOTE_PROMISC_OFF_PHYS: {
8644 			phyint_t *phyint = ill->ill_phyint;
8645 
8646 			mutex_enter(&phyint->phyint_lock);
8647 			phyint->phyint_flags &= ~PHYI_PROMISC;
8648 			mutex_exit(&phyint->phyint_lock);
8649 			break;
8650 		}
8651 		case DL_NOTE_CAPAB_RENEG:
8652 			/*
8653 			 * Something changed on the driver side.
8654 			 * It wants us to renegotiate the capabilities
8655 			 * on this ill. One possible cause is the aggregation
8656 			 * interface under us where a port got added or
8657 			 * went away.
8658 			 *
8659 			 * If the capability negotiation is already done
8660 			 * or is in progress, reset the capabilities and
8661 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8662 			 * so that when the ack comes back, we can start
8663 			 * the renegotiation process.
8664 			 *
8665 			 * Note that if ill_capab_reneg is already B_TRUE
8666 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8667 			 * the capability resetting request has been sent
8668 			 * and the renegotiation has not been started yet;
8669 			 * nothing needs to be done in this case.
8670 			 */
8671 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8672 			ill_capability_reset(ill, B_TRUE);
8673 			ipsq_current_finish(ipsq);
8674 			break;
8675 
8676 		case DL_NOTE_ALLOWED_IPS:
8677 			ill_set_allowed_ips(ill, mp);
8678 			break;
8679 		default:
8680 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8681 			    "type 0x%x for DL_NOTIFY_IND\n",
8682 			    notify->dl_notification));
8683 			break;
8684 		}
8685 
8686 		/*
8687 		 * As this is an asynchronous operation, we
8688 		 * should not call ill_dlpi_done
8689 		 */
8690 		break;
8691 	}
8692 	case DL_NOTIFY_ACK: {
8693 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8694 
8695 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8696 			ill->ill_note_link = 1;
8697 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8698 		break;
8699 	}
8700 	case DL_PHYS_ADDR_ACK: {
8701 		/*
8702 		 * As part of plumbing the interface via SIOCSLIFNAME,
8703 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8704 		 * whose answers we receive here.  As each answer is received,
8705 		 * we call ill_dlpi_done() to dispatch the next request as
8706 		 * we're processing the current one.  Once all answers have
8707 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8708 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8709 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8710 		 * available, but we know the ioctl is pending on ill_wq.)
8711 		 */
8712 		uint_t	paddrlen, paddroff;
8713 		uint8_t	*addr;
8714 
8715 		paddrreq = ill->ill_phys_addr_pend;
8716 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8717 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8718 		addr = mp->b_rptr + paddroff;
8719 
8720 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8721 		if (paddrreq == DL_IPV6_TOKEN) {
8722 			/*
8723 			 * bcopy to low-order bits of ill_token
8724 			 *
8725 			 * XXX Temporary hack - currently, all known tokens
8726 			 * are 64 bits, so I'll cheat for the moment.
8727 			 */
8728 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8729 			ill->ill_token_length = paddrlen;
8730 			break;
8731 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8732 			ASSERT(ill->ill_nd_lla_mp == NULL);
8733 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8734 			mp = NULL;
8735 			break;
8736 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8737 			ASSERT(ill->ill_dest_addr_mp == NULL);
8738 			ill->ill_dest_addr_mp = mp;
8739 			ill->ill_dest_addr = addr;
8740 			mp = NULL;
8741 			if (ill->ill_isv6) {
8742 				ill_setdesttoken(ill);
8743 				ipif_setdestlinklocal(ill->ill_ipif);
8744 			}
8745 			break;
8746 		}
8747 
8748 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8749 		ASSERT(ill->ill_phys_addr_mp == NULL);
8750 		if (!ill->ill_ifname_pending)
8751 			break;
8752 		ill->ill_ifname_pending = 0;
8753 		if (!ioctl_aborted)
8754 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8755 		if (mp1 != NULL) {
8756 			ASSERT(connp == NULL);
8757 			q = ill->ill_wq;
8758 		}
8759 		/*
8760 		 * If any error acks received during the plumbing sequence,
8761 		 * ill_ifname_pending_err will be set. Break out and send up
8762 		 * the error to the pending ioctl.
8763 		 */
8764 		if (ill->ill_ifname_pending_err != 0) {
8765 			err = ill->ill_ifname_pending_err;
8766 			ill->ill_ifname_pending_err = 0;
8767 			break;
8768 		}
8769 
8770 		ill->ill_phys_addr_mp = mp;
8771 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8772 		mp = NULL;
8773 
8774 		/*
8775 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8776 		 * provider doesn't support physical addresses.  We check both
8777 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8778 		 * not have physical addresses, but historically adversises a
8779 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8780 		 * its DL_PHYS_ADDR_ACK.
8781 		 */
8782 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8783 			ill->ill_phys_addr = NULL;
8784 		} else if (paddrlen != ill->ill_phys_addr_length) {
8785 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8786 			    paddrlen, ill->ill_phys_addr_length));
8787 			err = EINVAL;
8788 			break;
8789 		}
8790 
8791 		if (ill->ill_nd_lla_mp == NULL) {
8792 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8793 				err = ENOMEM;
8794 				break;
8795 			}
8796 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8797 		}
8798 
8799 		if (ill->ill_isv6) {
8800 			ill_setdefaulttoken(ill);
8801 			ipif_setlinklocal(ill->ill_ipif);
8802 		}
8803 		break;
8804 	}
8805 	case DL_OK_ACK:
8806 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8807 		    dl_primstr((int)dloa->dl_correct_primitive),
8808 		    dloa->dl_correct_primitive));
8809 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8810 		    char *, dl_primstr(dloa->dl_correct_primitive),
8811 		    ill_t *, ill);
8812 
8813 		switch (dloa->dl_correct_primitive) {
8814 		case DL_ENABMULTI_REQ:
8815 		case DL_DISABMULTI_REQ:
8816 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8817 			break;
8818 		case DL_PROMISCON_REQ:
8819 		case DL_PROMISCOFF_REQ:
8820 		case DL_UNBIND_REQ:
8821 		case DL_ATTACH_REQ:
8822 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8823 			break;
8824 		}
8825 		break;
8826 	default:
8827 		break;
8828 	}
8829 
8830 	freemsg(mp);
8831 	if (mp1 == NULL)
8832 		return;
8833 
8834 	/*
8835 	 * The operation must complete without EINPROGRESS since
8836 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8837 	 * the operation will be stuck forever inside the IPSQ.
8838 	 */
8839 	ASSERT(err != EINPROGRESS);
8840 
8841 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8842 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8843 	    ipif_t *, NULL);
8844 
8845 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8846 	case 0:
8847 		ipsq_current_finish(ipsq);
8848 		break;
8849 
8850 	case SIOCSLIFNAME:
8851 	case IF_UNITSEL: {
8852 		ill_t *ill_other = ILL_OTHER(ill);
8853 
8854 		/*
8855 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8856 		 * ill has a peer which is in an IPMP group, then place ill
8857 		 * into the same group.  One catch: although ifconfig plumbs
8858 		 * the appropriate IPMP meta-interface prior to plumbing this
8859 		 * ill, it is possible for multiple ifconfig applications to
8860 		 * race (or for another application to adjust plumbing), in
8861 		 * which case the IPMP meta-interface we need will be missing.
8862 		 * If so, kick the phyint out of the group.
8863 		 */
8864 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8865 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8866 			ipmp_illgrp_t	*illg;
8867 
8868 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8869 			if (illg == NULL)
8870 				ipmp_phyint_leave_grp(ill->ill_phyint);
8871 			else
8872 				ipmp_ill_join_illgrp(ill, illg);
8873 		}
8874 
8875 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8876 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8877 		else
8878 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8879 		break;
8880 	}
8881 	case SIOCLIFADDIF:
8882 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8883 		break;
8884 
8885 	default:
8886 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8887 		break;
8888 	}
8889 }
8890 
8891 /*
8892  * ip_rput_other is called by ip_rput to handle messages modifying the global
8893  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8894  */
8895 /* ARGSUSED */
8896 void
8897 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8898 {
8899 	ill_t		*ill = q->q_ptr;
8900 	struct iocblk	*iocp;
8901 
8902 	ip1dbg(("ip_rput_other "));
8903 	if (ipsq != NULL) {
8904 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8905 		ASSERT(ipsq->ipsq_xop ==
8906 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8907 	}
8908 
8909 	switch (mp->b_datap->db_type) {
8910 	case M_ERROR:
8911 	case M_HANGUP:
8912 		/*
8913 		 * The device has a problem.  We force the ILL down.  It can
8914 		 * be brought up again manually using SIOCSIFFLAGS (via
8915 		 * ifconfig or equivalent).
8916 		 */
8917 		ASSERT(ipsq != NULL);
8918 		if (mp->b_rptr < mp->b_wptr)
8919 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8920 		if (ill->ill_error == 0)
8921 			ill->ill_error = ENXIO;
8922 		if (!ill_down_start(q, mp))
8923 			return;
8924 		ipif_all_down_tail(ipsq, q, mp, NULL);
8925 		break;
8926 	case M_IOCNAK: {
8927 		iocp = (struct iocblk *)mp->b_rptr;
8928 
8929 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8930 		/*
8931 		 * If this was the first attempt, turn off the fastpath
8932 		 * probing.
8933 		 */
8934 		mutex_enter(&ill->ill_lock);
8935 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8936 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8937 			mutex_exit(&ill->ill_lock);
8938 			/*
8939 			 * don't flush the nce_t entries: we use them
8940 			 * as an index to the ncec itself.
8941 			 */
8942 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8943 			    ill->ill_name));
8944 		} else {
8945 			mutex_exit(&ill->ill_lock);
8946 		}
8947 		freemsg(mp);
8948 		break;
8949 	}
8950 	default:
8951 		ASSERT(0);
8952 		break;
8953 	}
8954 }
8955 
8956 /*
8957  * Update any source route, record route or timestamp options
8958  * When it fails it has consumed the message and BUMPed the MIB.
8959  */
8960 boolean_t
8961 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8962     ip_recv_attr_t *ira)
8963 {
8964 	ipoptp_t	opts;
8965 	uchar_t		*opt;
8966 	uint8_t		optval;
8967 	uint8_t		optlen;
8968 	ipaddr_t	dst;
8969 	ipaddr_t	ifaddr;
8970 	uint32_t	ts;
8971 	timestruc_t	now;
8972 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
8973 
8974 	ip2dbg(("ip_forward_options\n"));
8975 	dst = ipha->ipha_dst;
8976 	for (optval = ipoptp_first(&opts, ipha);
8977 	    optval != IPOPT_EOL;
8978 	    optval = ipoptp_next(&opts)) {
8979 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
8980 		opt = opts.ipoptp_cur;
8981 		optlen = opts.ipoptp_len;
8982 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
8983 		    optval, opts.ipoptp_len));
8984 		switch (optval) {
8985 			uint32_t off;
8986 		case IPOPT_SSRR:
8987 		case IPOPT_LSRR:
8988 			/* Check if adminstratively disabled */
8989 			if (!ipst->ips_ip_forward_src_routed) {
8990 				BUMP_MIB(dst_ill->ill_ip_mib,
8991 				    ipIfStatsForwProhibits);
8992 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
8993 				    mp, dst_ill);
8994 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
8995 				    ira);
8996 				return (B_FALSE);
8997 			}
8998 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8999 				/*
9000 				 * Must be partial since ip_input_options
9001 				 * checked for strict.
9002 				 */
9003 				break;
9004 			}
9005 			off = opt[IPOPT_OFFSET];
9006 			off--;
9007 		redo_srr:
9008 			if (optlen < IP_ADDR_LEN ||
9009 			    off > optlen - IP_ADDR_LEN) {
9010 				/* End of source route */
9011 				ip1dbg((
9012 				    "ip_forward_options: end of SR\n"));
9013 				break;
9014 			}
9015 			/* Pick a reasonable address on the outbound if */
9016 			ASSERT(dst_ill != NULL);
9017 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9018 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9019 			    NULL) != 0) {
9020 				/* No source! Shouldn't happen */
9021 				ifaddr = INADDR_ANY;
9022 			}
9023 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9024 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9025 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
9026 			    ntohl(dst)));
9027 
9028 			/*
9029 			 * Check if our address is present more than
9030 			 * once as consecutive hops in source route.
9031 			 */
9032 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9033 				off += IP_ADDR_LEN;
9034 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9035 				goto redo_srr;
9036 			}
9037 			ipha->ipha_dst = dst;
9038 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9039 			break;
9040 		case IPOPT_RR:
9041 			off = opt[IPOPT_OFFSET];
9042 			off--;
9043 			if (optlen < IP_ADDR_LEN ||
9044 			    off > optlen - IP_ADDR_LEN) {
9045 				/* No more room - ignore */
9046 				ip1dbg((
9047 				    "ip_forward_options: end of RR\n"));
9048 				break;
9049 			}
9050 			/* Pick a reasonable address on the outbound if */
9051 			ASSERT(dst_ill != NULL);
9052 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9053 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9054 			    NULL) != 0) {
9055 				/* No source! Shouldn't happen */
9056 				ifaddr = INADDR_ANY;
9057 			}
9058 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9059 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9060 			break;
9061 		case IPOPT_TS:
9062 			/* Insert timestamp if there is room */
9063 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9064 			case IPOPT_TS_TSONLY:
9065 				off = IPOPT_TS_TIMELEN;
9066 				break;
9067 			case IPOPT_TS_PRESPEC:
9068 			case IPOPT_TS_PRESPEC_RFC791:
9069 				/* Verify that the address matched */
9070 				off = opt[IPOPT_OFFSET] - 1;
9071 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9072 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9073 					/* Not for us */
9074 					break;
9075 				}
9076 				/* FALLTHRU */
9077 			case IPOPT_TS_TSANDADDR:
9078 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9079 				break;
9080 			default:
9081 				/*
9082 				 * ip_*put_options should have already
9083 				 * dropped this packet.
9084 				 */
9085 				cmn_err(CE_PANIC, "ip_forward_options: "
9086 				    "unknown IT - bug in ip_input_options?\n");
9087 				return (B_TRUE);	/* Keep "lint" happy */
9088 			}
9089 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9090 				/* Increase overflow counter */
9091 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9092 				opt[IPOPT_POS_OV_FLG] =
9093 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9094 				    (off << 4));
9095 				break;
9096 			}
9097 			off = opt[IPOPT_OFFSET] - 1;
9098 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9099 			case IPOPT_TS_PRESPEC:
9100 			case IPOPT_TS_PRESPEC_RFC791:
9101 			case IPOPT_TS_TSANDADDR:
9102 				/* Pick a reasonable addr on the outbound if */
9103 				ASSERT(dst_ill != NULL);
9104 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9105 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9106 				    NULL, NULL) != 0) {
9107 					/* No source! Shouldn't happen */
9108 					ifaddr = INADDR_ANY;
9109 				}
9110 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9111 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9112 				/* FALLTHRU */
9113 			case IPOPT_TS_TSONLY:
9114 				off = opt[IPOPT_OFFSET] - 1;
9115 				/* Compute # of milliseconds since midnight */
9116 				gethrestime(&now);
9117 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9118 				    now.tv_nsec / (NANOSEC / MILLISEC);
9119 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9120 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9121 				break;
9122 			}
9123 			break;
9124 		}
9125 	}
9126 	return (B_TRUE);
9127 }
9128 
9129 /*
9130  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9131  * returns 'true' if there are still fragments left on the queue, in
9132  * which case we restart the timer.
9133  */
9134 void
9135 ill_frag_timer(void *arg)
9136 {
9137 	ill_t	*ill = (ill_t *)arg;
9138 	boolean_t frag_pending;
9139 	ip_stack_t *ipst = ill->ill_ipst;
9140 	time_t	timeout;
9141 
9142 	mutex_enter(&ill->ill_lock);
9143 	ASSERT(!ill->ill_fragtimer_executing);
9144 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9145 		ill->ill_frag_timer_id = 0;
9146 		mutex_exit(&ill->ill_lock);
9147 		return;
9148 	}
9149 	ill->ill_fragtimer_executing = 1;
9150 	mutex_exit(&ill->ill_lock);
9151 
9152 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9153 	    ipst->ips_ip_reassembly_timeout);
9154 
9155 	frag_pending = ill_frag_timeout(ill, timeout);
9156 
9157 	/*
9158 	 * Restart the timer, if we have fragments pending or if someone
9159 	 * wanted us to be scheduled again.
9160 	 */
9161 	mutex_enter(&ill->ill_lock);
9162 	ill->ill_fragtimer_executing = 0;
9163 	ill->ill_frag_timer_id = 0;
9164 	if (frag_pending || ill->ill_fragtimer_needrestart)
9165 		ill_frag_timer_start(ill);
9166 	mutex_exit(&ill->ill_lock);
9167 }
9168 
9169 void
9170 ill_frag_timer_start(ill_t *ill)
9171 {
9172 	ip_stack_t *ipst = ill->ill_ipst;
9173 	clock_t	timeo_ms;
9174 
9175 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9176 
9177 	/* If the ill is closing or opening don't proceed */
9178 	if (ill->ill_state_flags & ILL_CONDEMNED)
9179 		return;
9180 
9181 	if (ill->ill_fragtimer_executing) {
9182 		/*
9183 		 * ill_frag_timer is currently executing. Just record the
9184 		 * the fact that we want the timer to be restarted.
9185 		 * ill_frag_timer will post a timeout before it returns,
9186 		 * ensuring it will be called again.
9187 		 */
9188 		ill->ill_fragtimer_needrestart = 1;
9189 		return;
9190 	}
9191 
9192 	if (ill->ill_frag_timer_id == 0) {
9193 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9194 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9195 
9196 		/*
9197 		 * The timer is neither running nor is the timeout handler
9198 		 * executing. Post a timeout so that ill_frag_timer will be
9199 		 * called
9200 		 */
9201 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9202 		    MSEC_TO_TICK(timeo_ms >> 1));
9203 		ill->ill_fragtimer_needrestart = 0;
9204 	}
9205 }
9206 
9207 /*
9208  * Update any source route, record route or timestamp options.
9209  * Check that we are at end of strict source route.
9210  * The options have already been checked for sanity in ip_input_options().
9211  */
9212 boolean_t
9213 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9214 {
9215 	ipoptp_t	opts;
9216 	uchar_t		*opt;
9217 	uint8_t		optval;
9218 	uint8_t		optlen;
9219 	ipaddr_t	dst;
9220 	ipaddr_t	ifaddr;
9221 	uint32_t	ts;
9222 	timestruc_t	now;
9223 	ill_t		*ill = ira->ira_ill;
9224 	ip_stack_t	*ipst = ill->ill_ipst;
9225 
9226 	ip2dbg(("ip_input_local_options\n"));
9227 
9228 	for (optval = ipoptp_first(&opts, ipha);
9229 	    optval != IPOPT_EOL;
9230 	    optval = ipoptp_next(&opts)) {
9231 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9232 		opt = opts.ipoptp_cur;
9233 		optlen = opts.ipoptp_len;
9234 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9235 		    optval, optlen));
9236 		switch (optval) {
9237 			uint32_t off;
9238 		case IPOPT_SSRR:
9239 		case IPOPT_LSRR:
9240 			off = opt[IPOPT_OFFSET];
9241 			off--;
9242 			if (optlen < IP_ADDR_LEN ||
9243 			    off > optlen - IP_ADDR_LEN) {
9244 				/* End of source route */
9245 				ip1dbg(("ip_input_local_options: end of SR\n"));
9246 				break;
9247 			}
9248 			/*
9249 			 * This will only happen if two consecutive entries
9250 			 * in the source route contains our address or if
9251 			 * it is a packet with a loose source route which
9252 			 * reaches us before consuming the whole source route
9253 			 */
9254 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9255 			if (optval == IPOPT_SSRR) {
9256 				goto bad_src_route;
9257 			}
9258 			/*
9259 			 * Hack: instead of dropping the packet truncate the
9260 			 * source route to what has been used by filling the
9261 			 * rest with IPOPT_NOP.
9262 			 */
9263 			opt[IPOPT_OLEN] = (uint8_t)off;
9264 			while (off < optlen) {
9265 				opt[off++] = IPOPT_NOP;
9266 			}
9267 			break;
9268 		case IPOPT_RR:
9269 			off = opt[IPOPT_OFFSET];
9270 			off--;
9271 			if (optlen < IP_ADDR_LEN ||
9272 			    off > optlen - IP_ADDR_LEN) {
9273 				/* No more room - ignore */
9274 				ip1dbg((
9275 				    "ip_input_local_options: end of RR\n"));
9276 				break;
9277 			}
9278 			/* Pick a reasonable address on the outbound if */
9279 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9280 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9281 			    NULL) != 0) {
9282 				/* No source! Shouldn't happen */
9283 				ifaddr = INADDR_ANY;
9284 			}
9285 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9286 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9287 			break;
9288 		case IPOPT_TS:
9289 			/* Insert timestamp if there is romm */
9290 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9291 			case IPOPT_TS_TSONLY:
9292 				off = IPOPT_TS_TIMELEN;
9293 				break;
9294 			case IPOPT_TS_PRESPEC:
9295 			case IPOPT_TS_PRESPEC_RFC791:
9296 				/* Verify that the address matched */
9297 				off = opt[IPOPT_OFFSET] - 1;
9298 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9299 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9300 					/* Not for us */
9301 					break;
9302 				}
9303 				/* FALLTHRU */
9304 			case IPOPT_TS_TSANDADDR:
9305 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9306 				break;
9307 			default:
9308 				/*
9309 				 * ip_*put_options should have already
9310 				 * dropped this packet.
9311 				 */
9312 				cmn_err(CE_PANIC, "ip_input_local_options: "
9313 				    "unknown IT - bug in ip_input_options?\n");
9314 				return (B_TRUE);	/* Keep "lint" happy */
9315 			}
9316 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9317 				/* Increase overflow counter */
9318 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9319 				opt[IPOPT_POS_OV_FLG] =
9320 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9321 				    (off << 4));
9322 				break;
9323 			}
9324 			off = opt[IPOPT_OFFSET] - 1;
9325 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9326 			case IPOPT_TS_PRESPEC:
9327 			case IPOPT_TS_PRESPEC_RFC791:
9328 			case IPOPT_TS_TSANDADDR:
9329 				/* Pick a reasonable addr on the outbound if */
9330 				if (ip_select_source_v4(ill, INADDR_ANY,
9331 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9332 				    &ifaddr, NULL, NULL) != 0) {
9333 					/* No source! Shouldn't happen */
9334 					ifaddr = INADDR_ANY;
9335 				}
9336 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9337 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9338 				/* FALLTHRU */
9339 			case IPOPT_TS_TSONLY:
9340 				off = opt[IPOPT_OFFSET] - 1;
9341 				/* Compute # of milliseconds since midnight */
9342 				gethrestime(&now);
9343 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9344 				    now.tv_nsec / (NANOSEC / MILLISEC);
9345 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9346 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9347 				break;
9348 			}
9349 			break;
9350 		}
9351 	}
9352 	return (B_TRUE);
9353 
9354 bad_src_route:
9355 	/* make sure we clear any indication of a hardware checksum */
9356 	DB_CKSUMFLAGS(mp) = 0;
9357 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9358 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9359 	return (B_FALSE);
9360 
9361 }
9362 
9363 /*
9364  * Process IP options in an inbound packet.  Always returns the nexthop.
9365  * Normally this is the passed in nexthop, but if there is an option
9366  * that effects the nexthop (such as a source route) that will be returned.
9367  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9368  * and mp freed.
9369  */
9370 ipaddr_t
9371 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9372     ip_recv_attr_t *ira, int *errorp)
9373 {
9374 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9375 	ipoptp_t	opts;
9376 	uchar_t		*opt;
9377 	uint8_t		optval;
9378 	uint8_t		optlen;
9379 	intptr_t	code = 0;
9380 	ire_t		*ire;
9381 
9382 	ip2dbg(("ip_input_options\n"));
9383 	*errorp = 0;
9384 	for (optval = ipoptp_first(&opts, ipha);
9385 	    optval != IPOPT_EOL;
9386 	    optval = ipoptp_next(&opts)) {
9387 		opt = opts.ipoptp_cur;
9388 		optlen = opts.ipoptp_len;
9389 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9390 		    optval, optlen));
9391 		/*
9392 		 * Note: we need to verify the checksum before we
9393 		 * modify anything thus this routine only extracts the next
9394 		 * hop dst from any source route.
9395 		 */
9396 		switch (optval) {
9397 			uint32_t off;
9398 		case IPOPT_SSRR:
9399 		case IPOPT_LSRR:
9400 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9401 				if (optval == IPOPT_SSRR) {
9402 					ip1dbg(("ip_input_options: not next"
9403 					    " strict source route 0x%x\n",
9404 					    ntohl(dst)));
9405 					code = (char *)&ipha->ipha_dst -
9406 					    (char *)ipha;
9407 					goto param_prob; /* RouterReq's */
9408 				}
9409 				ip2dbg(("ip_input_options: "
9410 				    "not next source route 0x%x\n",
9411 				    ntohl(dst)));
9412 				break;
9413 			}
9414 
9415 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9416 				ip1dbg((
9417 				    "ip_input_options: bad option offset\n"));
9418 				code = (char *)&opt[IPOPT_OLEN] -
9419 				    (char *)ipha;
9420 				goto param_prob;
9421 			}
9422 			off = opt[IPOPT_OFFSET];
9423 			off--;
9424 		redo_srr:
9425 			if (optlen < IP_ADDR_LEN ||
9426 			    off > optlen - IP_ADDR_LEN) {
9427 				/* End of source route */
9428 				ip1dbg(("ip_input_options: end of SR\n"));
9429 				break;
9430 			}
9431 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9432 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9433 			    ntohl(dst)));
9434 
9435 			/*
9436 			 * Check if our address is present more than
9437 			 * once as consecutive hops in source route.
9438 			 * XXX verify per-interface ip_forwarding
9439 			 * for source route?
9440 			 */
9441 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9442 				off += IP_ADDR_LEN;
9443 				goto redo_srr;
9444 			}
9445 
9446 			if (dst == htonl(INADDR_LOOPBACK)) {
9447 				ip1dbg(("ip_input_options: loopback addr in "
9448 				    "source route!\n"));
9449 				goto bad_src_route;
9450 			}
9451 			/*
9452 			 * For strict: verify that dst is directly
9453 			 * reachable.
9454 			 */
9455 			if (optval == IPOPT_SSRR) {
9456 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9457 				    IRE_INTERFACE, NULL, ALL_ZONES,
9458 				    ira->ira_tsl,
9459 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9460 				    NULL);
9461 				if (ire == NULL) {
9462 					ip1dbg(("ip_input_options: SSRR not "
9463 					    "directly reachable: 0x%x\n",
9464 					    ntohl(dst)));
9465 					goto bad_src_route;
9466 				}
9467 				ire_refrele(ire);
9468 			}
9469 			/*
9470 			 * Defer update of the offset and the record route
9471 			 * until the packet is forwarded.
9472 			 */
9473 			break;
9474 		case IPOPT_RR:
9475 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9476 				ip1dbg((
9477 				    "ip_input_options: bad option offset\n"));
9478 				code = (char *)&opt[IPOPT_OLEN] -
9479 				    (char *)ipha;
9480 				goto param_prob;
9481 			}
9482 			break;
9483 		case IPOPT_TS:
9484 			/*
9485 			 * Verify that length >= 5 and that there is either
9486 			 * room for another timestamp or that the overflow
9487 			 * counter is not maxed out.
9488 			 */
9489 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9490 			if (optlen < IPOPT_MINLEN_IT) {
9491 				goto param_prob;
9492 			}
9493 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9494 				ip1dbg((
9495 				    "ip_input_options: bad option offset\n"));
9496 				code = (char *)&opt[IPOPT_OFFSET] -
9497 				    (char *)ipha;
9498 				goto param_prob;
9499 			}
9500 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9501 			case IPOPT_TS_TSONLY:
9502 				off = IPOPT_TS_TIMELEN;
9503 				break;
9504 			case IPOPT_TS_TSANDADDR:
9505 			case IPOPT_TS_PRESPEC:
9506 			case IPOPT_TS_PRESPEC_RFC791:
9507 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9508 				break;
9509 			default:
9510 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9511 				    (char *)ipha;
9512 				goto param_prob;
9513 			}
9514 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9515 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9516 				/*
9517 				 * No room and the overflow counter is 15
9518 				 * already.
9519 				 */
9520 				goto param_prob;
9521 			}
9522 			break;
9523 		}
9524 	}
9525 
9526 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9527 		return (dst);
9528 	}
9529 
9530 	ip1dbg(("ip_input_options: error processing IP options."));
9531 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9532 
9533 param_prob:
9534 	/* make sure we clear any indication of a hardware checksum */
9535 	DB_CKSUMFLAGS(mp) = 0;
9536 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9537 	icmp_param_problem(mp, (uint8_t)code, ira);
9538 	*errorp = -1;
9539 	return (dst);
9540 
9541 bad_src_route:
9542 	/* make sure we clear any indication of a hardware checksum */
9543 	DB_CKSUMFLAGS(mp) = 0;
9544 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9545 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9546 	*errorp = -1;
9547 	return (dst);
9548 }
9549 
9550 /*
9551  * IP & ICMP info in >=14 msg's ...
9552  *  - ip fixed part (mib2_ip_t)
9553  *  - icmp fixed part (mib2_icmp_t)
9554  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9555  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9556  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9557  *  - ipRouteAttributeTable (ip 102)	labeled routes
9558  *  - ip multicast membership (ip_member_t)
9559  *  - ip multicast source filtering (ip_grpsrc_t)
9560  *  - igmp fixed part (struct igmpstat)
9561  *  - multicast routing stats (struct mrtstat)
9562  *  - multicast routing vifs (array of struct vifctl)
9563  *  - multicast routing routes (array of struct mfcctl)
9564  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9565  *					One per ill plus one generic
9566  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9567  *					One per ill plus one generic
9568  *  - ipv6RouteEntry			all IPv6 IREs
9569  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9570  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9571  *  - ipv6AddrEntry			all IPv6 ipifs
9572  *  - ipv6 multicast membership (ipv6_member_t)
9573  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9574  *
9575  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9576  * already filled in by the caller.
9577  * If legacy_req is true then MIB structures needs to be truncated to their
9578  * legacy sizes before being returned.
9579  * Return value of 0 indicates that no messages were sent and caller
9580  * should free mpctl.
9581  */
9582 int
9583 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level, boolean_t legacy_req)
9584 {
9585 	ip_stack_t *ipst;
9586 	sctp_stack_t *sctps;
9587 
9588 	if (q->q_next != NULL) {
9589 		ipst = ILLQ_TO_IPST(q);
9590 	} else {
9591 		ipst = CONNQ_TO_IPST(q);
9592 	}
9593 	ASSERT(ipst != NULL);
9594 	sctps = ipst->ips_netstack->netstack_sctp;
9595 
9596 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9597 		return (0);
9598 	}
9599 
9600 	/*
9601 	 * For the purposes of the (broken) packet shell use
9602 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9603 	 * to make TCP and UDP appear first in the list of mib items.
9604 	 * TBD: We could expand this and use it in netstat so that
9605 	 * the kernel doesn't have to produce large tables (connections,
9606 	 * routes, etc) when netstat only wants the statistics or a particular
9607 	 * table.
9608 	 */
9609 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9610 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9611 			return (1);
9612 		}
9613 	}
9614 
9615 	if (level != MIB2_TCP) {
9616 		if ((mpctl = udp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9617 			return (1);
9618 		}
9619 	}
9620 
9621 	if (level != MIB2_UDP) {
9622 		if ((mpctl = tcp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9623 			return (1);
9624 		}
9625 	}
9626 
9627 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9628 	    ipst, legacy_req)) == NULL) {
9629 		return (1);
9630 	}
9631 
9632 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst,
9633 	    legacy_req)) == NULL) {
9634 		return (1);
9635 	}
9636 
9637 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9638 		return (1);
9639 	}
9640 
9641 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9642 		return (1);
9643 	}
9644 
9645 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9646 		return (1);
9647 	}
9648 
9649 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9650 		return (1);
9651 	}
9652 
9653 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst,
9654 	    legacy_req)) == NULL) {
9655 		return (1);
9656 	}
9657 
9658 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst,
9659 	    legacy_req)) == NULL) {
9660 		return (1);
9661 	}
9662 
9663 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9664 		return (1);
9665 	}
9666 
9667 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9668 		return (1);
9669 	}
9670 
9671 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9672 		return (1);
9673 	}
9674 
9675 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9676 		return (1);
9677 	}
9678 
9679 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9680 		return (1);
9681 	}
9682 
9683 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9684 		return (1);
9685 	}
9686 
9687 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9688 	if (mpctl == NULL)
9689 		return (1);
9690 
9691 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9692 	if (mpctl == NULL)
9693 		return (1);
9694 
9695 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9696 		return (1);
9697 	}
9698 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9699 		return (1);
9700 	}
9701 	freemsg(mpctl);
9702 	return (1);
9703 }
9704 
9705 /* Get global (legacy) IPv4 statistics */
9706 static mblk_t *
9707 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9708     ip_stack_t *ipst, boolean_t legacy_req)
9709 {
9710 	mib2_ip_t		old_ip_mib;
9711 	struct opthdr		*optp;
9712 	mblk_t			*mp2ctl;
9713 	mib2_ipAddrEntry_t	mae;
9714 
9715 	/*
9716 	 * make a copy of the original message
9717 	 */
9718 	mp2ctl = copymsg(mpctl);
9719 
9720 	/* fixed length IP structure... */
9721 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9722 	optp->level = MIB2_IP;
9723 	optp->name = 0;
9724 	SET_MIB(old_ip_mib.ipForwarding,
9725 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9726 	SET_MIB(old_ip_mib.ipDefaultTTL,
9727 	    (uint32_t)ipst->ips_ip_def_ttl);
9728 	SET_MIB(old_ip_mib.ipReasmTimeout,
9729 	    ipst->ips_ip_reassembly_timeout);
9730 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9731 	    (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9732 	    sizeof (mib2_ipAddrEntry_t));
9733 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9734 	    sizeof (mib2_ipRouteEntry_t));
9735 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9736 	    sizeof (mib2_ipNetToMediaEntry_t));
9737 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9738 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9739 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9740 	    sizeof (mib2_ipAttributeEntry_t));
9741 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9742 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9743 
9744 	/*
9745 	 * Grab the statistics from the new IP MIB
9746 	 */
9747 	SET_MIB(old_ip_mib.ipInReceives,
9748 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9749 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9750 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9751 	SET_MIB(old_ip_mib.ipForwDatagrams,
9752 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9753 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9754 	    ipmib->ipIfStatsInUnknownProtos);
9755 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9756 	SET_MIB(old_ip_mib.ipInDelivers,
9757 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9758 	SET_MIB(old_ip_mib.ipOutRequests,
9759 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9760 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9761 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9762 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9763 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9764 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9765 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9766 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9767 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9768 
9769 	/* ipRoutingDiscards is not being used */
9770 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9771 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9772 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9773 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9774 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9775 	    ipmib->ipIfStatsReasmDuplicates);
9776 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9777 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9778 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9779 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9780 	SET_MIB(old_ip_mib.rawipInOverflows,
9781 	    ipmib->rawipIfStatsInOverflows);
9782 
9783 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9784 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9785 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9786 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9787 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9788 	    ipmib->ipIfStatsOutSwitchIPVersion);
9789 
9790 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9791 	    (int)sizeof (old_ip_mib))) {
9792 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9793 		    (uint_t)sizeof (old_ip_mib)));
9794 	}
9795 
9796 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9797 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9798 	    (int)optp->level, (int)optp->name, (int)optp->len));
9799 	qreply(q, mpctl);
9800 	return (mp2ctl);
9801 }
9802 
9803 /* Per interface IPv4 statistics */
9804 static mblk_t *
9805 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9806     boolean_t legacy_req)
9807 {
9808 	struct opthdr		*optp;
9809 	mblk_t			*mp2ctl;
9810 	ill_t			*ill;
9811 	ill_walk_context_t	ctx;
9812 	mblk_t			*mp_tail = NULL;
9813 	mib2_ipIfStatsEntry_t	global_ip_mib;
9814 	mib2_ipAddrEntry_t	mae;
9815 
9816 	/*
9817 	 * Make a copy of the original message
9818 	 */
9819 	mp2ctl = copymsg(mpctl);
9820 
9821 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9822 	optp->level = MIB2_IP;
9823 	optp->name = MIB2_IP_TRAFFIC_STATS;
9824 	/* Include "unknown interface" ip_mib */
9825 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9826 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9827 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9828 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9829 	    (ipst->ips_ip_forwarding ? 1 : 2));
9830 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9831 	    (uint32_t)ipst->ips_ip_def_ttl);
9832 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9833 	    sizeof (mib2_ipIfStatsEntry_t));
9834 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9835 	    sizeof (mib2_ipAddrEntry_t));
9836 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9837 	    sizeof (mib2_ipRouteEntry_t));
9838 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9839 	    sizeof (mib2_ipNetToMediaEntry_t));
9840 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9841 	    sizeof (ip_member_t));
9842 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9843 	    sizeof (ip_grpsrc_t));
9844 
9845 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9846 
9847 	if (legacy_req) {
9848 		SET_MIB(global_ip_mib.ipIfStatsAddrEntrySize,
9849 		    LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t));
9850 	}
9851 
9852 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9853 	    (char *)&global_ip_mib, (int)sizeof (global_ip_mib))) {
9854 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9855 		    "failed to allocate %u bytes\n",
9856 		    (uint_t)sizeof (global_ip_mib)));
9857 	}
9858 
9859 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9860 	ill = ILL_START_WALK_V4(&ctx, ipst);
9861 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9862 		ill->ill_ip_mib->ipIfStatsIfIndex =
9863 		    ill->ill_phyint->phyint_ifindex;
9864 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9865 		    (ipst->ips_ip_forwarding ? 1 : 2));
9866 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9867 		    (uint32_t)ipst->ips_ip_def_ttl);
9868 
9869 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9870 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9871 		    (char *)ill->ill_ip_mib,
9872 		    (int)sizeof (*ill->ill_ip_mib))) {
9873 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9874 			    "failed to allocate %u bytes\n",
9875 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9876 		}
9877 	}
9878 	rw_exit(&ipst->ips_ill_g_lock);
9879 
9880 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9881 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9882 	    "level %d, name %d, len %d\n",
9883 	    (int)optp->level, (int)optp->name, (int)optp->len));
9884 	qreply(q, mpctl);
9885 
9886 	if (mp2ctl == NULL)
9887 		return (NULL);
9888 
9889 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst,
9890 	    legacy_req));
9891 }
9892 
9893 /* Global IPv4 ICMP statistics */
9894 static mblk_t *
9895 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9896 {
9897 	struct opthdr		*optp;
9898 	mblk_t			*mp2ctl;
9899 
9900 	/*
9901 	 * Make a copy of the original message
9902 	 */
9903 	mp2ctl = copymsg(mpctl);
9904 
9905 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9906 	optp->level = MIB2_ICMP;
9907 	optp->name = 0;
9908 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9909 	    (int)sizeof (ipst->ips_icmp_mib))) {
9910 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9911 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9912 	}
9913 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9914 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9915 	    (int)optp->level, (int)optp->name, (int)optp->len));
9916 	qreply(q, mpctl);
9917 	return (mp2ctl);
9918 }
9919 
9920 /* Global IPv4 IGMP statistics */
9921 static mblk_t *
9922 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9923 {
9924 	struct opthdr		*optp;
9925 	mblk_t			*mp2ctl;
9926 
9927 	/*
9928 	 * make a copy of the original message
9929 	 */
9930 	mp2ctl = copymsg(mpctl);
9931 
9932 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9933 	optp->level = EXPER_IGMP;
9934 	optp->name = 0;
9935 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9936 	    (int)sizeof (ipst->ips_igmpstat))) {
9937 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9938 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9939 	}
9940 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9941 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9942 	    (int)optp->level, (int)optp->name, (int)optp->len));
9943 	qreply(q, mpctl);
9944 	return (mp2ctl);
9945 }
9946 
9947 /* Global IPv4 Multicast Routing statistics */
9948 static mblk_t *
9949 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9950 {
9951 	struct opthdr		*optp;
9952 	mblk_t			*mp2ctl;
9953 
9954 	/*
9955 	 * make a copy of the original message
9956 	 */
9957 	mp2ctl = copymsg(mpctl);
9958 
9959 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9960 	optp->level = EXPER_DVMRP;
9961 	optp->name = 0;
9962 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9963 		ip0dbg(("ip_mroute_stats: failed\n"));
9964 	}
9965 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9966 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9967 	    (int)optp->level, (int)optp->name, (int)optp->len));
9968 	qreply(q, mpctl);
9969 	return (mp2ctl);
9970 }
9971 
9972 /* IPv4 address information */
9973 static mblk_t *
9974 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9975     boolean_t legacy_req)
9976 {
9977 	struct opthdr		*optp;
9978 	mblk_t			*mp2ctl;
9979 	mblk_t			*mp_tail = NULL;
9980 	ill_t			*ill;
9981 	ipif_t			*ipif;
9982 	uint_t			bitval;
9983 	mib2_ipAddrEntry_t	mae;
9984 	size_t			mae_size;
9985 	zoneid_t		zoneid;
9986 	ill_walk_context_t	ctx;
9987 
9988 	/*
9989 	 * make a copy of the original message
9990 	 */
9991 	mp2ctl = copymsg(mpctl);
9992 
9993 	mae_size = (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9994 	    sizeof (mib2_ipAddrEntry_t);
9995 
9996 	/* ipAddrEntryTable */
9997 
9998 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9999 	optp->level = MIB2_IP;
10000 	optp->name = MIB2_IP_ADDR;
10001 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10002 
10003 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10004 	ill = ILL_START_WALK_V4(&ctx, ipst);
10005 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10006 		for (ipif = ill->ill_ipif; ipif != NULL;
10007 		    ipif = ipif->ipif_next) {
10008 			if (ipif->ipif_zoneid != zoneid &&
10009 			    ipif->ipif_zoneid != ALL_ZONES)
10010 				continue;
10011 			/* Sum of count from dead IRE_LO* and our current */
10012 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10013 			if (ipif->ipif_ire_local != NULL) {
10014 				mae.ipAdEntInfo.ae_ibcnt +=
10015 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10016 			}
10017 			mae.ipAdEntInfo.ae_obcnt = 0;
10018 			mae.ipAdEntInfo.ae_focnt = 0;
10019 
10020 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
10021 			    OCTET_LENGTH);
10022 			mae.ipAdEntIfIndex.o_length =
10023 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
10024 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
10025 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
10026 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
10027 			mae.ipAdEntInfo.ae_subnet_len =
10028 			    ip_mask_to_plen(ipif->ipif_net_mask);
10029 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
10030 			for (bitval = 1;
10031 			    bitval &&
10032 			    !(bitval & ipif->ipif_brd_addr);
10033 			    bitval <<= 1)
10034 				noop;
10035 			mae.ipAdEntBcastAddr = bitval;
10036 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10037 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10038 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
10039 			mae.ipAdEntInfo.ae_broadcast_addr =
10040 			    ipif->ipif_brd_addr;
10041 			mae.ipAdEntInfo.ae_pp_dst_addr =
10042 			    ipif->ipif_pp_dst_addr;
10043 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10044 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10045 			mae.ipAdEntRetransmitTime =
10046 			    ill->ill_reachable_retrans_time;
10047 
10048 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10049 			    (char *)&mae, (int)mae_size)) {
10050 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10051 				    "allocate %u bytes\n", (uint_t)mae_size));
10052 			}
10053 		}
10054 	}
10055 	rw_exit(&ipst->ips_ill_g_lock);
10056 
10057 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10058 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10059 	    (int)optp->level, (int)optp->name, (int)optp->len));
10060 	qreply(q, mpctl);
10061 	return (mp2ctl);
10062 }
10063 
10064 /* IPv6 address information */
10065 static mblk_t *
10066 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10067     boolean_t legacy_req)
10068 {
10069 	struct opthdr		*optp;
10070 	mblk_t			*mp2ctl;
10071 	mblk_t			*mp_tail = NULL;
10072 	ill_t			*ill;
10073 	ipif_t			*ipif;
10074 	mib2_ipv6AddrEntry_t	mae6;
10075 	size_t			mae6_size;
10076 	zoneid_t		zoneid;
10077 	ill_walk_context_t	ctx;
10078 
10079 	/*
10080 	 * make a copy of the original message
10081 	 */
10082 	mp2ctl = copymsg(mpctl);
10083 
10084 	mae6_size = (legacy_req) ?
10085 	    LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t) :
10086 	    sizeof (mib2_ipv6AddrEntry_t);
10087 
10088 	/* ipv6AddrEntryTable */
10089 
10090 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10091 	optp->level = MIB2_IP6;
10092 	optp->name = MIB2_IP6_ADDR;
10093 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10094 
10095 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10096 	ill = ILL_START_WALK_V6(&ctx, ipst);
10097 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10098 		for (ipif = ill->ill_ipif; ipif != NULL;
10099 		    ipif = ipif->ipif_next) {
10100 			if (ipif->ipif_zoneid != zoneid &&
10101 			    ipif->ipif_zoneid != ALL_ZONES)
10102 				continue;
10103 			/* Sum of count from dead IRE_LO* and our current */
10104 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10105 			if (ipif->ipif_ire_local != NULL) {
10106 				mae6.ipv6AddrInfo.ae_ibcnt +=
10107 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10108 			}
10109 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10110 			mae6.ipv6AddrInfo.ae_focnt = 0;
10111 
10112 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10113 			    OCTET_LENGTH);
10114 			mae6.ipv6AddrIfIndex.o_length =
10115 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10116 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10117 			mae6.ipv6AddrPfxLength =
10118 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10119 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10120 			mae6.ipv6AddrInfo.ae_subnet_len =
10121 			    mae6.ipv6AddrPfxLength;
10122 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10123 
10124 			/* Type: stateless(1), stateful(2), unknown(3) */
10125 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10126 				mae6.ipv6AddrType = 1;
10127 			else
10128 				mae6.ipv6AddrType = 2;
10129 			/* Anycast: true(1), false(2) */
10130 			if (ipif->ipif_flags & IPIF_ANYCAST)
10131 				mae6.ipv6AddrAnycastFlag = 1;
10132 			else
10133 				mae6.ipv6AddrAnycastFlag = 2;
10134 
10135 			/*
10136 			 * Address status: preferred(1), deprecated(2),
10137 			 * invalid(3), inaccessible(4), unknown(5)
10138 			 */
10139 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10140 				mae6.ipv6AddrStatus = 3;
10141 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10142 				mae6.ipv6AddrStatus = 2;
10143 			else
10144 				mae6.ipv6AddrStatus = 1;
10145 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10146 			mae6.ipv6AddrInfo.ae_metric  =
10147 			    ipif->ipif_ill->ill_metric;
10148 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10149 			    ipif->ipif_v6pp_dst_addr;
10150 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10151 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10152 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10153 			mae6.ipv6AddrIdentifier = ill->ill_token;
10154 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10155 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10156 			mae6.ipv6AddrRetransmitTime =
10157 			    ill->ill_reachable_retrans_time;
10158 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10159 			    (char *)&mae6, (int)mae6_size)) {
10160 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10161 				    "allocate %u bytes\n",
10162 				    (uint_t)mae6_size));
10163 			}
10164 		}
10165 	}
10166 	rw_exit(&ipst->ips_ill_g_lock);
10167 
10168 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10169 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10170 	    (int)optp->level, (int)optp->name, (int)optp->len));
10171 	qreply(q, mpctl);
10172 	return (mp2ctl);
10173 }
10174 
10175 /* IPv4 multicast group membership. */
10176 static mblk_t *
10177 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10178 {
10179 	struct opthdr		*optp;
10180 	mblk_t			*mp2ctl;
10181 	ill_t			*ill;
10182 	ipif_t			*ipif;
10183 	ilm_t			*ilm;
10184 	ip_member_t		ipm;
10185 	mblk_t			*mp_tail = NULL;
10186 	ill_walk_context_t	ctx;
10187 	zoneid_t		zoneid;
10188 
10189 	/*
10190 	 * make a copy of the original message
10191 	 */
10192 	mp2ctl = copymsg(mpctl);
10193 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10194 
10195 	/* ipGroupMember table */
10196 	optp = (struct opthdr *)&mpctl->b_rptr[
10197 	    sizeof (struct T_optmgmt_ack)];
10198 	optp->level = MIB2_IP;
10199 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10200 
10201 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10202 	ill = ILL_START_WALK_V4(&ctx, ipst);
10203 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10204 		/* Make sure the ill isn't going away. */
10205 		if (!ill_check_and_refhold(ill))
10206 			continue;
10207 		rw_exit(&ipst->ips_ill_g_lock);
10208 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10209 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10210 			if (ilm->ilm_zoneid != zoneid &&
10211 			    ilm->ilm_zoneid != ALL_ZONES)
10212 				continue;
10213 
10214 			/* Is there an ipif for ilm_ifaddr? */
10215 			for (ipif = ill->ill_ipif; ipif != NULL;
10216 			    ipif = ipif->ipif_next) {
10217 				if (!IPIF_IS_CONDEMNED(ipif) &&
10218 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10219 				    ilm->ilm_ifaddr != INADDR_ANY)
10220 					break;
10221 			}
10222 			if (ipif != NULL) {
10223 				ipif_get_name(ipif,
10224 				    ipm.ipGroupMemberIfIndex.o_bytes,
10225 				    OCTET_LENGTH);
10226 			} else {
10227 				ill_get_name(ill,
10228 				    ipm.ipGroupMemberIfIndex.o_bytes,
10229 				    OCTET_LENGTH);
10230 			}
10231 			ipm.ipGroupMemberIfIndex.o_length =
10232 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10233 
10234 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10235 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10236 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10237 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10238 			    (char *)&ipm, (int)sizeof (ipm))) {
10239 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10240 				    "failed to allocate %u bytes\n",
10241 				    (uint_t)sizeof (ipm)));
10242 			}
10243 		}
10244 		rw_exit(&ill->ill_mcast_lock);
10245 		ill_refrele(ill);
10246 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10247 	}
10248 	rw_exit(&ipst->ips_ill_g_lock);
10249 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10250 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10251 	    (int)optp->level, (int)optp->name, (int)optp->len));
10252 	qreply(q, mpctl);
10253 	return (mp2ctl);
10254 }
10255 
10256 /* IPv6 multicast group membership. */
10257 static mblk_t *
10258 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10259 {
10260 	struct opthdr		*optp;
10261 	mblk_t			*mp2ctl;
10262 	ill_t			*ill;
10263 	ilm_t			*ilm;
10264 	ipv6_member_t		ipm6;
10265 	mblk_t			*mp_tail = NULL;
10266 	ill_walk_context_t	ctx;
10267 	zoneid_t		zoneid;
10268 
10269 	/*
10270 	 * make a copy of the original message
10271 	 */
10272 	mp2ctl = copymsg(mpctl);
10273 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10274 
10275 	/* ip6GroupMember table */
10276 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10277 	optp->level = MIB2_IP6;
10278 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10279 
10280 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10281 	ill = ILL_START_WALK_V6(&ctx, ipst);
10282 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10283 		/* Make sure the ill isn't going away. */
10284 		if (!ill_check_and_refhold(ill))
10285 			continue;
10286 		rw_exit(&ipst->ips_ill_g_lock);
10287 		/*
10288 		 * Normally we don't have any members on under IPMP interfaces.
10289 		 * We report them as a debugging aid.
10290 		 */
10291 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10292 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10293 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10294 			if (ilm->ilm_zoneid != zoneid &&
10295 			    ilm->ilm_zoneid != ALL_ZONES)
10296 				continue;	/* not this zone */
10297 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10298 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10299 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10300 			if (!snmp_append_data2(mpctl->b_cont,
10301 			    &mp_tail,
10302 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10303 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10304 				    "failed to allocate %u bytes\n",
10305 				    (uint_t)sizeof (ipm6)));
10306 			}
10307 		}
10308 		rw_exit(&ill->ill_mcast_lock);
10309 		ill_refrele(ill);
10310 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10311 	}
10312 	rw_exit(&ipst->ips_ill_g_lock);
10313 
10314 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10315 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10316 	    (int)optp->level, (int)optp->name, (int)optp->len));
10317 	qreply(q, mpctl);
10318 	return (mp2ctl);
10319 }
10320 
10321 /* IP multicast filtered sources */
10322 static mblk_t *
10323 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10324 {
10325 	struct opthdr		*optp;
10326 	mblk_t			*mp2ctl;
10327 	ill_t			*ill;
10328 	ipif_t			*ipif;
10329 	ilm_t			*ilm;
10330 	ip_grpsrc_t		ips;
10331 	mblk_t			*mp_tail = NULL;
10332 	ill_walk_context_t	ctx;
10333 	zoneid_t		zoneid;
10334 	int			i;
10335 	slist_t			*sl;
10336 
10337 	/*
10338 	 * make a copy of the original message
10339 	 */
10340 	mp2ctl = copymsg(mpctl);
10341 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10342 
10343 	/* ipGroupSource table */
10344 	optp = (struct opthdr *)&mpctl->b_rptr[
10345 	    sizeof (struct T_optmgmt_ack)];
10346 	optp->level = MIB2_IP;
10347 	optp->name = EXPER_IP_GROUP_SOURCES;
10348 
10349 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10350 	ill = ILL_START_WALK_V4(&ctx, ipst);
10351 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10352 		/* Make sure the ill isn't going away. */
10353 		if (!ill_check_and_refhold(ill))
10354 			continue;
10355 		rw_exit(&ipst->ips_ill_g_lock);
10356 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10357 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10358 			sl = ilm->ilm_filter;
10359 			if (ilm->ilm_zoneid != zoneid &&
10360 			    ilm->ilm_zoneid != ALL_ZONES)
10361 				continue;
10362 			if (SLIST_IS_EMPTY(sl))
10363 				continue;
10364 
10365 			/* Is there an ipif for ilm_ifaddr? */
10366 			for (ipif = ill->ill_ipif; ipif != NULL;
10367 			    ipif = ipif->ipif_next) {
10368 				if (!IPIF_IS_CONDEMNED(ipif) &&
10369 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10370 				    ilm->ilm_ifaddr != INADDR_ANY)
10371 					break;
10372 			}
10373 			if (ipif != NULL) {
10374 				ipif_get_name(ipif,
10375 				    ips.ipGroupSourceIfIndex.o_bytes,
10376 				    OCTET_LENGTH);
10377 			} else {
10378 				ill_get_name(ill,
10379 				    ips.ipGroupSourceIfIndex.o_bytes,
10380 				    OCTET_LENGTH);
10381 			}
10382 			ips.ipGroupSourceIfIndex.o_length =
10383 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10384 
10385 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10386 			for (i = 0; i < sl->sl_numsrc; i++) {
10387 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10388 					continue;
10389 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10390 				    ips.ipGroupSourceAddress);
10391 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10392 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10393 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10394 					    " failed to allocate %u bytes\n",
10395 					    (uint_t)sizeof (ips)));
10396 				}
10397 			}
10398 		}
10399 		rw_exit(&ill->ill_mcast_lock);
10400 		ill_refrele(ill);
10401 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10402 	}
10403 	rw_exit(&ipst->ips_ill_g_lock);
10404 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10405 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10406 	    (int)optp->level, (int)optp->name, (int)optp->len));
10407 	qreply(q, mpctl);
10408 	return (mp2ctl);
10409 }
10410 
10411 /* IPv6 multicast filtered sources. */
10412 static mblk_t *
10413 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10414 {
10415 	struct opthdr		*optp;
10416 	mblk_t			*mp2ctl;
10417 	ill_t			*ill;
10418 	ilm_t			*ilm;
10419 	ipv6_grpsrc_t		ips6;
10420 	mblk_t			*mp_tail = NULL;
10421 	ill_walk_context_t	ctx;
10422 	zoneid_t		zoneid;
10423 	int			i;
10424 	slist_t			*sl;
10425 
10426 	/*
10427 	 * make a copy of the original message
10428 	 */
10429 	mp2ctl = copymsg(mpctl);
10430 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10431 
10432 	/* ip6GroupMember table */
10433 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10434 	optp->level = MIB2_IP6;
10435 	optp->name = EXPER_IP6_GROUP_SOURCES;
10436 
10437 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10438 	ill = ILL_START_WALK_V6(&ctx, ipst);
10439 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10440 		/* Make sure the ill isn't going away. */
10441 		if (!ill_check_and_refhold(ill))
10442 			continue;
10443 		rw_exit(&ipst->ips_ill_g_lock);
10444 		/*
10445 		 * Normally we don't have any members on under IPMP interfaces.
10446 		 * We report them as a debugging aid.
10447 		 */
10448 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10449 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10450 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10451 			sl = ilm->ilm_filter;
10452 			if (ilm->ilm_zoneid != zoneid &&
10453 			    ilm->ilm_zoneid != ALL_ZONES)
10454 				continue;
10455 			if (SLIST_IS_EMPTY(sl))
10456 				continue;
10457 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10458 			for (i = 0; i < sl->sl_numsrc; i++) {
10459 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10460 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10461 				    (char *)&ips6, (int)sizeof (ips6))) {
10462 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10463 					    "group_src: failed to allocate "
10464 					    "%u bytes\n",
10465 					    (uint_t)sizeof (ips6)));
10466 				}
10467 			}
10468 		}
10469 		rw_exit(&ill->ill_mcast_lock);
10470 		ill_refrele(ill);
10471 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10472 	}
10473 	rw_exit(&ipst->ips_ill_g_lock);
10474 
10475 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10476 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10477 	    (int)optp->level, (int)optp->name, (int)optp->len));
10478 	qreply(q, mpctl);
10479 	return (mp2ctl);
10480 }
10481 
10482 /* Multicast routing virtual interface table. */
10483 static mblk_t *
10484 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10485 {
10486 	struct opthdr		*optp;
10487 	mblk_t			*mp2ctl;
10488 
10489 	/*
10490 	 * make a copy of the original message
10491 	 */
10492 	mp2ctl = copymsg(mpctl);
10493 
10494 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10495 	optp->level = EXPER_DVMRP;
10496 	optp->name = EXPER_DVMRP_VIF;
10497 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10498 		ip0dbg(("ip_mroute_vif: failed\n"));
10499 	}
10500 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10501 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10502 	    (int)optp->level, (int)optp->name, (int)optp->len));
10503 	qreply(q, mpctl);
10504 	return (mp2ctl);
10505 }
10506 
10507 /* Multicast routing table. */
10508 static mblk_t *
10509 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10510 {
10511 	struct opthdr		*optp;
10512 	mblk_t			*mp2ctl;
10513 
10514 	/*
10515 	 * make a copy of the original message
10516 	 */
10517 	mp2ctl = copymsg(mpctl);
10518 
10519 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10520 	optp->level = EXPER_DVMRP;
10521 	optp->name = EXPER_DVMRP_MRT;
10522 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10523 		ip0dbg(("ip_mroute_mrt: failed\n"));
10524 	}
10525 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10526 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10527 	    (int)optp->level, (int)optp->name, (int)optp->len));
10528 	qreply(q, mpctl);
10529 	return (mp2ctl);
10530 }
10531 
10532 /*
10533  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10534  * in one IRE walk.
10535  */
10536 static mblk_t *
10537 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10538     ip_stack_t *ipst)
10539 {
10540 	struct opthdr	*optp;
10541 	mblk_t		*mp2ctl;	/* Returned */
10542 	mblk_t		*mp3ctl;	/* nettomedia */
10543 	mblk_t		*mp4ctl;	/* routeattrs */
10544 	iproutedata_t	ird;
10545 	zoneid_t	zoneid;
10546 
10547 	/*
10548 	 * make copies of the original message
10549 	 *	- mp2ctl is returned unchanged to the caller for his use
10550 	 *	- mpctl is sent upstream as ipRouteEntryTable
10551 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10552 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10553 	 */
10554 	mp2ctl = copymsg(mpctl);
10555 	mp3ctl = copymsg(mpctl);
10556 	mp4ctl = copymsg(mpctl);
10557 	if (mp3ctl == NULL || mp4ctl == NULL) {
10558 		freemsg(mp4ctl);
10559 		freemsg(mp3ctl);
10560 		freemsg(mp2ctl);
10561 		freemsg(mpctl);
10562 		return (NULL);
10563 	}
10564 
10565 	bzero(&ird, sizeof (ird));
10566 
10567 	ird.ird_route.lp_head = mpctl->b_cont;
10568 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10569 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10570 	/*
10571 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10572 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10573 	 * intended a temporary solution until a proper MIB API is provided
10574 	 * that provides complete filtering/caller-opt-in.
10575 	 */
10576 	if (level == EXPER_IP_AND_ALL_IRES)
10577 		ird.ird_flags |= IRD_REPORT_ALL;
10578 
10579 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10580 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10581 
10582 	/* ipRouteEntryTable in mpctl */
10583 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10584 	optp->level = MIB2_IP;
10585 	optp->name = MIB2_IP_ROUTE;
10586 	optp->len = msgdsize(ird.ird_route.lp_head);
10587 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10588 	    (int)optp->level, (int)optp->name, (int)optp->len));
10589 	qreply(q, mpctl);
10590 
10591 	/* ipNetToMediaEntryTable in mp3ctl */
10592 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10593 
10594 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10595 	optp->level = MIB2_IP;
10596 	optp->name = MIB2_IP_MEDIA;
10597 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10598 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10599 	    (int)optp->level, (int)optp->name, (int)optp->len));
10600 	qreply(q, mp3ctl);
10601 
10602 	/* ipRouteAttributeTable in mp4ctl */
10603 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10604 	optp->level = MIB2_IP;
10605 	optp->name = EXPER_IP_RTATTR;
10606 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10607 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10608 	    (int)optp->level, (int)optp->name, (int)optp->len));
10609 	if (optp->len == 0)
10610 		freemsg(mp4ctl);
10611 	else
10612 		qreply(q, mp4ctl);
10613 
10614 	return (mp2ctl);
10615 }
10616 
10617 /*
10618  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10619  * ipv6NetToMediaEntryTable in an NDP walk.
10620  */
10621 static mblk_t *
10622 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10623     ip_stack_t *ipst)
10624 {
10625 	struct opthdr	*optp;
10626 	mblk_t		*mp2ctl;	/* Returned */
10627 	mblk_t		*mp3ctl;	/* nettomedia */
10628 	mblk_t		*mp4ctl;	/* routeattrs */
10629 	iproutedata_t	ird;
10630 	zoneid_t	zoneid;
10631 
10632 	/*
10633 	 * make copies of the original message
10634 	 *	- mp2ctl is returned unchanged to the caller for his use
10635 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10636 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10637 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10638 	 */
10639 	mp2ctl = copymsg(mpctl);
10640 	mp3ctl = copymsg(mpctl);
10641 	mp4ctl = copymsg(mpctl);
10642 	if (mp3ctl == NULL || mp4ctl == NULL) {
10643 		freemsg(mp4ctl);
10644 		freemsg(mp3ctl);
10645 		freemsg(mp2ctl);
10646 		freemsg(mpctl);
10647 		return (NULL);
10648 	}
10649 
10650 	bzero(&ird, sizeof (ird));
10651 
10652 	ird.ird_route.lp_head = mpctl->b_cont;
10653 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10654 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10655 	/*
10656 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10657 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10658 	 * intended a temporary solution until a proper MIB API is provided
10659 	 * that provides complete filtering/caller-opt-in.
10660 	 */
10661 	if (level == EXPER_IP_AND_ALL_IRES)
10662 		ird.ird_flags |= IRD_REPORT_ALL;
10663 
10664 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10665 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10666 
10667 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10668 	optp->level = MIB2_IP6;
10669 	optp->name = MIB2_IP6_ROUTE;
10670 	optp->len = msgdsize(ird.ird_route.lp_head);
10671 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10672 	    (int)optp->level, (int)optp->name, (int)optp->len));
10673 	qreply(q, mpctl);
10674 
10675 	/* ipv6NetToMediaEntryTable in mp3ctl */
10676 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10677 
10678 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10679 	optp->level = MIB2_IP6;
10680 	optp->name = MIB2_IP6_MEDIA;
10681 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10682 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10683 	    (int)optp->level, (int)optp->name, (int)optp->len));
10684 	qreply(q, mp3ctl);
10685 
10686 	/* ipv6RouteAttributeTable in mp4ctl */
10687 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10688 	optp->level = MIB2_IP6;
10689 	optp->name = EXPER_IP_RTATTR;
10690 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10691 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10692 	    (int)optp->level, (int)optp->name, (int)optp->len));
10693 	if (optp->len == 0)
10694 		freemsg(mp4ctl);
10695 	else
10696 		qreply(q, mp4ctl);
10697 
10698 	return (mp2ctl);
10699 }
10700 
10701 /*
10702  * IPv6 mib: One per ill
10703  */
10704 static mblk_t *
10705 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10706     boolean_t legacy_req)
10707 {
10708 	struct opthdr		*optp;
10709 	mblk_t			*mp2ctl;
10710 	ill_t			*ill;
10711 	ill_walk_context_t	ctx;
10712 	mblk_t			*mp_tail = NULL;
10713 	mib2_ipv6AddrEntry_t	mae6;
10714 	mib2_ipIfStatsEntry_t	*ise;
10715 	size_t			ise_size, iae_size;
10716 
10717 	/*
10718 	 * Make a copy of the original message
10719 	 */
10720 	mp2ctl = copymsg(mpctl);
10721 
10722 	/* fixed length IPv6 structure ... */
10723 
10724 	if (legacy_req) {
10725 		ise_size = LEGACY_MIB_SIZE(&ipst->ips_ip6_mib,
10726 		    mib2_ipIfStatsEntry_t);
10727 		iae_size = LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t);
10728 	} else {
10729 		ise_size = sizeof (mib2_ipIfStatsEntry_t);
10730 		iae_size = sizeof (mib2_ipv6AddrEntry_t);
10731 	}
10732 
10733 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10734 	optp->level = MIB2_IP6;
10735 	optp->name = 0;
10736 	/* Include "unknown interface" ip6_mib */
10737 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10738 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10739 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10740 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10741 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10742 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10743 	    ipst->ips_ipv6_def_hops);
10744 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10745 	    sizeof (mib2_ipIfStatsEntry_t));
10746 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10747 	    sizeof (mib2_ipv6AddrEntry_t));
10748 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10749 	    sizeof (mib2_ipv6RouteEntry_t));
10750 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10751 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10752 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10753 	    sizeof (ipv6_member_t));
10754 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10755 	    sizeof (ipv6_grpsrc_t));
10756 
10757 	/*
10758 	 * Synchronize 64- and 32-bit counters
10759 	 */
10760 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10761 	    ipIfStatsHCInReceives);
10762 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10763 	    ipIfStatsHCInDelivers);
10764 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10765 	    ipIfStatsHCOutRequests);
10766 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10767 	    ipIfStatsHCOutForwDatagrams);
10768 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10769 	    ipIfStatsHCOutMcastPkts);
10770 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10771 	    ipIfStatsHCInMcastPkts);
10772 
10773 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10774 	    (char *)&ipst->ips_ip6_mib, (int)ise_size)) {
10775 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10776 		    (uint_t)ise_size));
10777 	} else if (legacy_req) {
10778 		/* Adjust the EntrySize fields for legacy requests. */
10779 		ise =
10780 		    (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr - (int)ise_size);
10781 		SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10782 		SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10783 	}
10784 
10785 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10786 	ill = ILL_START_WALK_V6(&ctx, ipst);
10787 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10788 		ill->ill_ip_mib->ipIfStatsIfIndex =
10789 		    ill->ill_phyint->phyint_ifindex;
10790 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10791 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10792 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10793 		    ill->ill_max_hops);
10794 
10795 		/*
10796 		 * Synchronize 64- and 32-bit counters
10797 		 */
10798 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10799 		    ipIfStatsHCInReceives);
10800 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10801 		    ipIfStatsHCInDelivers);
10802 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10803 		    ipIfStatsHCOutRequests);
10804 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10805 		    ipIfStatsHCOutForwDatagrams);
10806 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10807 		    ipIfStatsHCOutMcastPkts);
10808 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10809 		    ipIfStatsHCInMcastPkts);
10810 
10811 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10812 		    (char *)ill->ill_ip_mib, (int)ise_size)) {
10813 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10814 			"%u bytes\n", (uint_t)ise_size));
10815 		} else if (legacy_req) {
10816 			/* Adjust the EntrySize fields for legacy requests. */
10817 			ise = (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr -
10818 			    (int)ise_size);
10819 			SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10820 			SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10821 		}
10822 	}
10823 	rw_exit(&ipst->ips_ill_g_lock);
10824 
10825 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10826 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10827 	    (int)optp->level, (int)optp->name, (int)optp->len));
10828 	qreply(q, mpctl);
10829 	return (mp2ctl);
10830 }
10831 
10832 /*
10833  * ICMPv6 mib: One per ill
10834  */
10835 static mblk_t *
10836 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10837 {
10838 	struct opthdr		*optp;
10839 	mblk_t			*mp2ctl;
10840 	ill_t			*ill;
10841 	ill_walk_context_t	ctx;
10842 	mblk_t			*mp_tail = NULL;
10843 	/*
10844 	 * Make a copy of the original message
10845 	 */
10846 	mp2ctl = copymsg(mpctl);
10847 
10848 	/* fixed length ICMPv6 structure ... */
10849 
10850 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10851 	optp->level = MIB2_ICMP6;
10852 	optp->name = 0;
10853 	/* Include "unknown interface" icmp6_mib */
10854 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10855 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10856 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10857 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10858 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10859 	    (char *)&ipst->ips_icmp6_mib,
10860 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10861 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10862 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10863 	}
10864 
10865 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10866 	ill = ILL_START_WALK_V6(&ctx, ipst);
10867 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10868 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10869 		    ill->ill_phyint->phyint_ifindex;
10870 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10871 		    (char *)ill->ill_icmp6_mib,
10872 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10873 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10874 			    "%u bytes\n",
10875 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10876 		}
10877 	}
10878 	rw_exit(&ipst->ips_ill_g_lock);
10879 
10880 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10881 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10882 	    (int)optp->level, (int)optp->name, (int)optp->len));
10883 	qreply(q, mpctl);
10884 	return (mp2ctl);
10885 }
10886 
10887 /*
10888  * ire_walk routine to create both ipRouteEntryTable and
10889  * ipRouteAttributeTable in one IRE walk
10890  */
10891 static void
10892 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10893 {
10894 	ill_t				*ill;
10895 	mib2_ipRouteEntry_t		*re;
10896 	mib2_ipAttributeEntry_t		iaes;
10897 	tsol_ire_gw_secattr_t		*attrp;
10898 	tsol_gc_t			*gc = NULL;
10899 	tsol_gcgrp_t			*gcgrp = NULL;
10900 	ip_stack_t			*ipst = ire->ire_ipst;
10901 
10902 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10903 
10904 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10905 		if (ire->ire_testhidden)
10906 			return;
10907 		if (ire->ire_type & IRE_IF_CLONE)
10908 			return;
10909 	}
10910 
10911 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10912 		return;
10913 
10914 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10915 		mutex_enter(&attrp->igsa_lock);
10916 		if ((gc = attrp->igsa_gc) != NULL) {
10917 			gcgrp = gc->gc_grp;
10918 			ASSERT(gcgrp != NULL);
10919 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10920 		}
10921 		mutex_exit(&attrp->igsa_lock);
10922 	}
10923 	/*
10924 	 * Return all IRE types for route table... let caller pick and choose
10925 	 */
10926 	re->ipRouteDest = ire->ire_addr;
10927 	ill = ire->ire_ill;
10928 	re->ipRouteIfIndex.o_length = 0;
10929 	if (ill != NULL) {
10930 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10931 		re->ipRouteIfIndex.o_length =
10932 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10933 	}
10934 	re->ipRouteMetric1 = -1;
10935 	re->ipRouteMetric2 = -1;
10936 	re->ipRouteMetric3 = -1;
10937 	re->ipRouteMetric4 = -1;
10938 
10939 	re->ipRouteNextHop = ire->ire_gateway_addr;
10940 	/* indirect(4), direct(3), or invalid(2) */
10941 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10942 		re->ipRouteType = 2;
10943 	else if (ire->ire_type & IRE_ONLINK)
10944 		re->ipRouteType = 3;
10945 	else
10946 		re->ipRouteType = 4;
10947 
10948 	re->ipRouteProto = -1;
10949 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10950 	re->ipRouteMask = ire->ire_mask;
10951 	re->ipRouteMetric5 = -1;
10952 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10953 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10954 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10955 
10956 	re->ipRouteInfo.re_frag_flag	= 0;
10957 	re->ipRouteInfo.re_rtt		= 0;
10958 	re->ipRouteInfo.re_src_addr	= 0;
10959 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
10960 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10961 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10962 	re->ipRouteInfo.re_flags	= ire->ire_flags;
10963 
10964 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10965 	if (ire->ire_type & IRE_INTERFACE) {
10966 		ire_t *child;
10967 
10968 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10969 		child = ire->ire_dep_children;
10970 		while (child != NULL) {
10971 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10972 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10973 			child = child->ire_dep_sib_next;
10974 		}
10975 		rw_exit(&ipst->ips_ire_dep_lock);
10976 	}
10977 
10978 	if (ire->ire_flags & RTF_DYNAMIC) {
10979 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10980 	} else {
10981 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
10982 	}
10983 
10984 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10985 	    (char *)re, (int)sizeof (*re))) {
10986 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
10987 		    (uint_t)sizeof (*re)));
10988 	}
10989 
10990 	if (gc != NULL) {
10991 		iaes.iae_routeidx = ird->ird_idx;
10992 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10993 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10994 
10995 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10996 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10997 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
10998 			    "bytes\n", (uint_t)sizeof (iaes)));
10999 		}
11000 	}
11001 
11002 	/* bump route index for next pass */
11003 	ird->ird_idx++;
11004 
11005 	kmem_free(re, sizeof (*re));
11006 	if (gcgrp != NULL)
11007 		rw_exit(&gcgrp->gcgrp_rwlock);
11008 }
11009 
11010 /*
11011  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
11012  */
11013 static void
11014 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
11015 {
11016 	ill_t				*ill;
11017 	mib2_ipv6RouteEntry_t		*re;
11018 	mib2_ipAttributeEntry_t		iaes;
11019 	tsol_ire_gw_secattr_t		*attrp;
11020 	tsol_gc_t			*gc = NULL;
11021 	tsol_gcgrp_t			*gcgrp = NULL;
11022 	ip_stack_t			*ipst = ire->ire_ipst;
11023 
11024 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
11025 
11026 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11027 		if (ire->ire_testhidden)
11028 			return;
11029 		if (ire->ire_type & IRE_IF_CLONE)
11030 			return;
11031 	}
11032 
11033 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11034 		return;
11035 
11036 	if ((attrp = ire->ire_gw_secattr) != NULL) {
11037 		mutex_enter(&attrp->igsa_lock);
11038 		if ((gc = attrp->igsa_gc) != NULL) {
11039 			gcgrp = gc->gc_grp;
11040 			ASSERT(gcgrp != NULL);
11041 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11042 		}
11043 		mutex_exit(&attrp->igsa_lock);
11044 	}
11045 	/*
11046 	 * Return all IRE types for route table... let caller pick and choose
11047 	 */
11048 	re->ipv6RouteDest = ire->ire_addr_v6;
11049 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11050 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
11051 	re->ipv6RouteIfIndex.o_length = 0;
11052 	ill = ire->ire_ill;
11053 	if (ill != NULL) {
11054 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11055 		re->ipv6RouteIfIndex.o_length =
11056 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11057 	}
11058 
11059 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
11060 
11061 	mutex_enter(&ire->ire_lock);
11062 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11063 	mutex_exit(&ire->ire_lock);
11064 
11065 	/* remote(4), local(3), or discard(2) */
11066 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11067 		re->ipv6RouteType = 2;
11068 	else if (ire->ire_type & IRE_ONLINK)
11069 		re->ipv6RouteType = 3;
11070 	else
11071 		re->ipv6RouteType = 4;
11072 
11073 	re->ipv6RouteProtocol	= -1;
11074 	re->ipv6RoutePolicy	= 0;
11075 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
11076 	re->ipv6RouteNextHopRDI	= 0;
11077 	re->ipv6RouteWeight	= 0;
11078 	re->ipv6RouteMetric	= 0;
11079 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11080 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11081 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11082 
11083 	re->ipv6RouteInfo.re_frag_flag	= 0;
11084 	re->ipv6RouteInfo.re_rtt	= 0;
11085 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
11086 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11087 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11088 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
11089 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
11090 
11091 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11092 	if (ire->ire_type & IRE_INTERFACE) {
11093 		ire_t *child;
11094 
11095 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11096 		child = ire->ire_dep_children;
11097 		while (child != NULL) {
11098 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11099 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11100 			child = child->ire_dep_sib_next;
11101 		}
11102 		rw_exit(&ipst->ips_ire_dep_lock);
11103 	}
11104 	if (ire->ire_flags & RTF_DYNAMIC) {
11105 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11106 	} else {
11107 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
11108 	}
11109 
11110 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11111 	    (char *)re, (int)sizeof (*re))) {
11112 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11113 		    (uint_t)sizeof (*re)));
11114 	}
11115 
11116 	if (gc != NULL) {
11117 		iaes.iae_routeidx = ird->ird_idx;
11118 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11119 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11120 
11121 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11122 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11123 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11124 			    "bytes\n", (uint_t)sizeof (iaes)));
11125 		}
11126 	}
11127 
11128 	/* bump route index for next pass */
11129 	ird->ird_idx++;
11130 
11131 	kmem_free(re, sizeof (*re));
11132 	if (gcgrp != NULL)
11133 		rw_exit(&gcgrp->gcgrp_rwlock);
11134 }
11135 
11136 /*
11137  * ncec_walk routine to create ipv6NetToMediaEntryTable
11138  */
11139 static int
11140 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11141 {
11142 	ill_t				*ill;
11143 	mib2_ipv6NetToMediaEntry_t	ntme;
11144 
11145 	ill = ncec->ncec_ill;
11146 	/* skip arpce entries, and loopback ncec entries */
11147 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11148 		return (0);
11149 	/*
11150 	 * Neighbor cache entry attached to IRE with on-link
11151 	 * destination.
11152 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11153 	 */
11154 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11155 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11156 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11157 	if (ncec->ncec_lladdr != NULL) {
11158 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11159 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11160 	}
11161 	/*
11162 	 * Note: Returns ND_* states. Should be:
11163 	 * reachable(1), stale(2), delay(3), probe(4),
11164 	 * invalid(5), unknown(6)
11165 	 */
11166 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11167 	ntme.ipv6NetToMediaLastUpdated = 0;
11168 
11169 	/* other(1), dynamic(2), static(3), local(4) */
11170 	if (NCE_MYADDR(ncec)) {
11171 		ntme.ipv6NetToMediaType = 4;
11172 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11173 		ntme.ipv6NetToMediaType = 1; /* proxy */
11174 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11175 		ntme.ipv6NetToMediaType = 3;
11176 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11177 		ntme.ipv6NetToMediaType = 1;
11178 	} else {
11179 		ntme.ipv6NetToMediaType = 2;
11180 	}
11181 
11182 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11183 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11184 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11185 		    (uint_t)sizeof (ntme)));
11186 	}
11187 	return (0);
11188 }
11189 
11190 int
11191 nce2ace(ncec_t *ncec)
11192 {
11193 	int flags = 0;
11194 
11195 	if (NCE_ISREACHABLE(ncec))
11196 		flags |= ACE_F_RESOLVED;
11197 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11198 		flags |= ACE_F_AUTHORITY;
11199 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11200 		flags |= ACE_F_PUBLISH;
11201 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11202 		flags |= ACE_F_PERMANENT;
11203 	if (NCE_MYADDR(ncec))
11204 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11205 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11206 		flags |= ACE_F_UNVERIFIED;
11207 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11208 		flags |= ACE_F_AUTHORITY;
11209 	if (ncec->ncec_flags & NCE_F_DELAYED)
11210 		flags |= ACE_F_DELAYED;
11211 	return (flags);
11212 }
11213 
11214 /*
11215  * ncec_walk routine to create ipNetToMediaEntryTable
11216  */
11217 static int
11218 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11219 {
11220 	ill_t				*ill;
11221 	mib2_ipNetToMediaEntry_t	ntme;
11222 	const char			*name = "unknown";
11223 	ipaddr_t			ncec_addr;
11224 
11225 	ill = ncec->ncec_ill;
11226 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11227 	    ill->ill_net_type == IRE_LOOPBACK)
11228 		return (0);
11229 
11230 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11231 	name = ill->ill_name;
11232 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11233 	if (NCE_MYADDR(ncec)) {
11234 		ntme.ipNetToMediaType = 4;
11235 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11236 		ntme.ipNetToMediaType = 1;
11237 	} else {
11238 		ntme.ipNetToMediaType = 3;
11239 	}
11240 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11241 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11242 	    ntme.ipNetToMediaIfIndex.o_length);
11243 
11244 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11245 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11246 
11247 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11248 	ncec_addr = INADDR_BROADCAST;
11249 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11250 	    sizeof (ncec_addr));
11251 	/*
11252 	 * map all the flags to the ACE counterpart.
11253 	 */
11254 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11255 
11256 	ntme.ipNetToMediaPhysAddress.o_length =
11257 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11258 
11259 	if (!NCE_ISREACHABLE(ncec))
11260 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11261 	else {
11262 		if (ncec->ncec_lladdr != NULL) {
11263 			bcopy(ncec->ncec_lladdr,
11264 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11265 			    ntme.ipNetToMediaPhysAddress.o_length);
11266 		}
11267 	}
11268 
11269 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11270 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11271 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11272 		    (uint_t)sizeof (ntme)));
11273 	}
11274 	return (0);
11275 }
11276 
11277 /*
11278  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11279  */
11280 /* ARGSUSED */
11281 int
11282 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11283 {
11284 	switch (level) {
11285 	case MIB2_IP:
11286 	case MIB2_ICMP:
11287 		switch (name) {
11288 		default:
11289 			break;
11290 		}
11291 		return (1);
11292 	default:
11293 		return (1);
11294 	}
11295 }
11296 
11297 /*
11298  * When there exists both a 64- and 32-bit counter of a particular type
11299  * (i.e., InReceives), only the 64-bit counters are added.
11300  */
11301 void
11302 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11303 {
11304 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11305 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11306 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11307 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11308 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11309 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11310 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11311 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11312 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11313 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11314 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11315 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11316 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11317 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11318 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11319 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11320 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11321 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11322 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11323 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11324 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11325 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11326 	    o2->ipIfStatsInWrongIPVersion);
11327 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11328 	    o2->ipIfStatsInWrongIPVersion);
11329 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11330 	    o2->ipIfStatsOutSwitchIPVersion);
11331 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11332 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11333 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11334 	    o2->ipIfStatsHCInForwDatagrams);
11335 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11336 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11337 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11338 	    o2->ipIfStatsHCOutForwDatagrams);
11339 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11340 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11341 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11342 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11343 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11344 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11345 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11346 	    o2->ipIfStatsHCOutMcastOctets);
11347 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11348 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11349 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11350 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11351 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11352 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11353 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11354 }
11355 
11356 void
11357 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11358 {
11359 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11360 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11361 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11362 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11363 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11364 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11365 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11366 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11367 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11368 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11369 	    o2->ipv6IfIcmpInRouterSolicits);
11370 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11371 	    o2->ipv6IfIcmpInRouterAdvertisements);
11372 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11373 	    o2->ipv6IfIcmpInNeighborSolicits);
11374 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11375 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11376 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11377 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11378 	    o2->ipv6IfIcmpInGroupMembQueries);
11379 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11380 	    o2->ipv6IfIcmpInGroupMembResponses);
11381 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11382 	    o2->ipv6IfIcmpInGroupMembReductions);
11383 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11384 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11385 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11386 	    o2->ipv6IfIcmpOutDestUnreachs);
11387 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11388 	    o2->ipv6IfIcmpOutAdminProhibs);
11389 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11390 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11391 	    o2->ipv6IfIcmpOutParmProblems);
11392 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11393 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11394 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11395 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11396 	    o2->ipv6IfIcmpOutRouterSolicits);
11397 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11398 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11399 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11400 	    o2->ipv6IfIcmpOutNeighborSolicits);
11401 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11402 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11403 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11404 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11405 	    o2->ipv6IfIcmpOutGroupMembQueries);
11406 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11407 	    o2->ipv6IfIcmpOutGroupMembResponses);
11408 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11409 	    o2->ipv6IfIcmpOutGroupMembReductions);
11410 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11411 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11412 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11413 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11414 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11415 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11416 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11417 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11418 	    o2->ipv6IfIcmpInGroupMembTotal);
11419 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11420 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11421 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11422 	    o2->ipv6IfIcmpInGroupMembBadReports);
11423 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11424 	    o2->ipv6IfIcmpInGroupMembOurReports);
11425 }
11426 
11427 /*
11428  * Called before the options are updated to check if this packet will
11429  * be source routed from here.
11430  * This routine assumes that the options are well formed i.e. that they
11431  * have already been checked.
11432  */
11433 boolean_t
11434 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11435 {
11436 	ipoptp_t	opts;
11437 	uchar_t		*opt;
11438 	uint8_t		optval;
11439 	uint8_t		optlen;
11440 	ipaddr_t	dst;
11441 
11442 	if (IS_SIMPLE_IPH(ipha)) {
11443 		ip2dbg(("not source routed\n"));
11444 		return (B_FALSE);
11445 	}
11446 	dst = ipha->ipha_dst;
11447 	for (optval = ipoptp_first(&opts, ipha);
11448 	    optval != IPOPT_EOL;
11449 	    optval = ipoptp_next(&opts)) {
11450 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11451 		opt = opts.ipoptp_cur;
11452 		optlen = opts.ipoptp_len;
11453 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11454 		    optval, optlen));
11455 		switch (optval) {
11456 			uint32_t off;
11457 		case IPOPT_SSRR:
11458 		case IPOPT_LSRR:
11459 			/*
11460 			 * If dst is one of our addresses and there are some
11461 			 * entries left in the source route return (true).
11462 			 */
11463 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11464 				ip2dbg(("ip_source_routed: not next"
11465 				    " source route 0x%x\n",
11466 				    ntohl(dst)));
11467 				return (B_FALSE);
11468 			}
11469 			off = opt[IPOPT_OFFSET];
11470 			off--;
11471 			if (optlen < IP_ADDR_LEN ||
11472 			    off > optlen - IP_ADDR_LEN) {
11473 				/* End of source route */
11474 				ip1dbg(("ip_source_routed: end of SR\n"));
11475 				return (B_FALSE);
11476 			}
11477 			return (B_TRUE);
11478 		}
11479 	}
11480 	ip2dbg(("not source routed\n"));
11481 	return (B_FALSE);
11482 }
11483 
11484 /*
11485  * ip_unbind is called by the transports to remove a conn from
11486  * the fanout table.
11487  */
11488 void
11489 ip_unbind(conn_t *connp)
11490 {
11491 
11492 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11493 
11494 	if (is_system_labeled() && connp->conn_anon_port) {
11495 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11496 		    connp->conn_mlp_type, connp->conn_proto,
11497 		    ntohs(connp->conn_lport), B_FALSE);
11498 		connp->conn_anon_port = 0;
11499 	}
11500 	connp->conn_mlp_type = mlptSingle;
11501 
11502 	ipcl_hash_remove(connp);
11503 }
11504 
11505 /*
11506  * Used for deciding the MSS size for the upper layer. Thus
11507  * we need to check the outbound policy values in the conn.
11508  */
11509 int
11510 conn_ipsec_length(conn_t *connp)
11511 {
11512 	ipsec_latch_t *ipl;
11513 
11514 	ipl = connp->conn_latch;
11515 	if (ipl == NULL)
11516 		return (0);
11517 
11518 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11519 		return (0);
11520 
11521 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11522 }
11523 
11524 /*
11525  * Returns an estimate of the IPsec headers size. This is used if
11526  * we don't want to call into IPsec to get the exact size.
11527  */
11528 int
11529 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11530 {
11531 	ipsec_action_t *a;
11532 
11533 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11534 		return (0);
11535 
11536 	a = ixa->ixa_ipsec_action;
11537 	if (a == NULL) {
11538 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11539 		a = ixa->ixa_ipsec_policy->ipsp_act;
11540 	}
11541 	ASSERT(a != NULL);
11542 
11543 	return (a->ipa_ovhd);
11544 }
11545 
11546 /*
11547  * If there are any source route options, return the true final
11548  * destination. Otherwise, return the destination.
11549  */
11550 ipaddr_t
11551 ip_get_dst(ipha_t *ipha)
11552 {
11553 	ipoptp_t	opts;
11554 	uchar_t		*opt;
11555 	uint8_t		optval;
11556 	uint8_t		optlen;
11557 	ipaddr_t	dst;
11558 	uint32_t off;
11559 
11560 	dst = ipha->ipha_dst;
11561 
11562 	if (IS_SIMPLE_IPH(ipha))
11563 		return (dst);
11564 
11565 	for (optval = ipoptp_first(&opts, ipha);
11566 	    optval != IPOPT_EOL;
11567 	    optval = ipoptp_next(&opts)) {
11568 		opt = opts.ipoptp_cur;
11569 		optlen = opts.ipoptp_len;
11570 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11571 		switch (optval) {
11572 		case IPOPT_SSRR:
11573 		case IPOPT_LSRR:
11574 			off = opt[IPOPT_OFFSET];
11575 			/*
11576 			 * If one of the conditions is true, it means
11577 			 * end of options and dst already has the right
11578 			 * value.
11579 			 */
11580 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11581 				off = optlen - IP_ADDR_LEN;
11582 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11583 			}
11584 			return (dst);
11585 		default:
11586 			break;
11587 		}
11588 	}
11589 
11590 	return (dst);
11591 }
11592 
11593 /*
11594  * Outbound IP fragmentation routine.
11595  * Assumes the caller has checked whether or not fragmentation should
11596  * be allowed. Here we copy the DF bit from the header to all the generated
11597  * fragments.
11598  */
11599 int
11600 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11601     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11602     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11603 {
11604 	int		i1;
11605 	int		hdr_len;
11606 	mblk_t		*hdr_mp;
11607 	ipha_t		*ipha;
11608 	int		ip_data_end;
11609 	int		len;
11610 	mblk_t		*mp = mp_orig;
11611 	int		offset;
11612 	ill_t		*ill = nce->nce_ill;
11613 	ip_stack_t	*ipst = ill->ill_ipst;
11614 	mblk_t		*carve_mp;
11615 	uint32_t	frag_flag;
11616 	uint_t		priority = mp->b_band;
11617 	int		error = 0;
11618 
11619 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11620 
11621 	if (pkt_len != msgdsize(mp)) {
11622 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11623 		    pkt_len, msgdsize(mp)));
11624 		freemsg(mp);
11625 		return (EINVAL);
11626 	}
11627 
11628 	if (max_frag == 0) {
11629 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11630 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11631 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11632 		freemsg(mp);
11633 		return (EINVAL);
11634 	}
11635 
11636 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11637 	ipha = (ipha_t *)mp->b_rptr;
11638 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11639 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11640 
11641 	/*
11642 	 * Establish the starting offset.  May not be zero if we are fragging
11643 	 * a fragment that is being forwarded.
11644 	 */
11645 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11646 
11647 	/* TODO why is this test needed? */
11648 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11649 		/* TODO: notify ulp somehow */
11650 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11651 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11652 		freemsg(mp);
11653 		return (EINVAL);
11654 	}
11655 
11656 	hdr_len = IPH_HDR_LENGTH(ipha);
11657 	ipha->ipha_hdr_checksum = 0;
11658 
11659 	/*
11660 	 * Establish the number of bytes maximum per frag, after putting
11661 	 * in the header.
11662 	 */
11663 	len = (max_frag - hdr_len) & ~7;
11664 
11665 	/* Get a copy of the header for the trailing frags */
11666 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11667 	    mp);
11668 	if (hdr_mp == NULL) {
11669 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11670 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11671 		freemsg(mp);
11672 		return (ENOBUFS);
11673 	}
11674 
11675 	/* Store the starting offset, with the MoreFrags flag. */
11676 	i1 = offset | IPH_MF | frag_flag;
11677 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11678 
11679 	/* Establish the ending byte offset, based on the starting offset. */
11680 	offset <<= 3;
11681 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11682 
11683 	/* Store the length of the first fragment in the IP header. */
11684 	i1 = len + hdr_len;
11685 	ASSERT(i1 <= IP_MAXPACKET);
11686 	ipha->ipha_length = htons((uint16_t)i1);
11687 
11688 	/*
11689 	 * Compute the IP header checksum for the first frag.  We have to
11690 	 * watch out that we stop at the end of the header.
11691 	 */
11692 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11693 
11694 	/*
11695 	 * Now carve off the first frag.  Note that this will include the
11696 	 * original IP header.
11697 	 */
11698 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11699 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11700 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11701 		freeb(hdr_mp);
11702 		freemsg(mp_orig);
11703 		return (ENOBUFS);
11704 	}
11705 
11706 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11707 
11708 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11709 	    ixa_cookie);
11710 	if (error != 0 && error != EWOULDBLOCK) {
11711 		/* No point in sending the other fragments */
11712 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11713 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11714 		freeb(hdr_mp);
11715 		freemsg(mp_orig);
11716 		return (error);
11717 	}
11718 
11719 	/* No need to redo state machine in loop */
11720 	ixaflags &= ~IXAF_REACH_CONF;
11721 
11722 	/* Advance the offset to the second frag starting point. */
11723 	offset += len;
11724 	/*
11725 	 * Update hdr_len from the copied header - there might be less options
11726 	 * in the later fragments.
11727 	 */
11728 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11729 	/* Loop until done. */
11730 	for (;;) {
11731 		uint16_t	offset_and_flags;
11732 		uint16_t	ip_len;
11733 
11734 		if (ip_data_end - offset > len) {
11735 			/*
11736 			 * Carve off the appropriate amount from the original
11737 			 * datagram.
11738 			 */
11739 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11740 				mp = NULL;
11741 				break;
11742 			}
11743 			/*
11744 			 * More frags after this one.  Get another copy
11745 			 * of the header.
11746 			 */
11747 			if (carve_mp->b_datap->db_ref == 1 &&
11748 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11749 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11750 				/* Inline IP header */
11751 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11752 				    hdr_mp->b_rptr;
11753 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11754 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11755 				mp = carve_mp;
11756 			} else {
11757 				if (!(mp = copyb(hdr_mp))) {
11758 					freemsg(carve_mp);
11759 					break;
11760 				}
11761 				/* Get priority marking, if any. */
11762 				mp->b_band = priority;
11763 				mp->b_cont = carve_mp;
11764 			}
11765 			ipha = (ipha_t *)mp->b_rptr;
11766 			offset_and_flags = IPH_MF;
11767 		} else {
11768 			/*
11769 			 * Last frag.  Consume the header. Set len to
11770 			 * the length of this last piece.
11771 			 */
11772 			len = ip_data_end - offset;
11773 
11774 			/*
11775 			 * Carve off the appropriate amount from the original
11776 			 * datagram.
11777 			 */
11778 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11779 				mp = NULL;
11780 				break;
11781 			}
11782 			if (carve_mp->b_datap->db_ref == 1 &&
11783 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11784 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11785 				/* Inline IP header */
11786 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11787 				    hdr_mp->b_rptr;
11788 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11789 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11790 				mp = carve_mp;
11791 				freeb(hdr_mp);
11792 				hdr_mp = mp;
11793 			} else {
11794 				mp = hdr_mp;
11795 				/* Get priority marking, if any. */
11796 				mp->b_band = priority;
11797 				mp->b_cont = carve_mp;
11798 			}
11799 			ipha = (ipha_t *)mp->b_rptr;
11800 			/* A frag of a frag might have IPH_MF non-zero */
11801 			offset_and_flags =
11802 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11803 			    IPH_MF;
11804 		}
11805 		offset_and_flags |= (uint16_t)(offset >> 3);
11806 		offset_and_flags |= (uint16_t)frag_flag;
11807 		/* Store the offset and flags in the IP header. */
11808 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11809 
11810 		/* Store the length in the IP header. */
11811 		ip_len = (uint16_t)(len + hdr_len);
11812 		ipha->ipha_length = htons(ip_len);
11813 
11814 		/*
11815 		 * Set the IP header checksum.	Note that mp is just
11816 		 * the header, so this is easy to pass to ip_csum.
11817 		 */
11818 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11819 
11820 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11821 
11822 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11823 		    nolzid, ixa_cookie);
11824 		/* All done if we just consumed the hdr_mp. */
11825 		if (mp == hdr_mp) {
11826 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11827 			return (error);
11828 		}
11829 		if (error != 0 && error != EWOULDBLOCK) {
11830 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11831 			    mblk_t *, hdr_mp);
11832 			/* No point in sending the other fragments */
11833 			break;
11834 		}
11835 
11836 		/* Otherwise, advance and loop. */
11837 		offset += len;
11838 	}
11839 	/* Clean up following allocation failure. */
11840 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11841 	ip_drop_output("FragFails: loop ended", NULL, ill);
11842 	if (mp != hdr_mp)
11843 		freeb(hdr_mp);
11844 	if (mp != mp_orig)
11845 		freemsg(mp_orig);
11846 	return (error);
11847 }
11848 
11849 /*
11850  * Copy the header plus those options which have the copy bit set
11851  */
11852 static mblk_t *
11853 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11854     mblk_t *src)
11855 {
11856 	mblk_t	*mp;
11857 	uchar_t	*up;
11858 
11859 	/*
11860 	 * Quick check if we need to look for options without the copy bit
11861 	 * set
11862 	 */
11863 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11864 	if (!mp)
11865 		return (mp);
11866 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11867 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11868 		bcopy(rptr, mp->b_rptr, hdr_len);
11869 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11870 		return (mp);
11871 	}
11872 	up  = mp->b_rptr;
11873 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11874 	up += IP_SIMPLE_HDR_LENGTH;
11875 	rptr += IP_SIMPLE_HDR_LENGTH;
11876 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11877 	while (hdr_len > 0) {
11878 		uint32_t optval;
11879 		uint32_t optlen;
11880 
11881 		optval = *rptr;
11882 		if (optval == IPOPT_EOL)
11883 			break;
11884 		if (optval == IPOPT_NOP)
11885 			optlen = 1;
11886 		else
11887 			optlen = rptr[1];
11888 		if (optval & IPOPT_COPY) {
11889 			bcopy(rptr, up, optlen);
11890 			up += optlen;
11891 		}
11892 		rptr += optlen;
11893 		hdr_len -= optlen;
11894 	}
11895 	/*
11896 	 * Make sure that we drop an even number of words by filling
11897 	 * with EOL to the next word boundary.
11898 	 */
11899 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11900 	    hdr_len & 0x3; hdr_len++)
11901 		*up++ = IPOPT_EOL;
11902 	mp->b_wptr = up;
11903 	/* Update header length */
11904 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11905 	return (mp);
11906 }
11907 
11908 /*
11909  * Update any source route, record route, or timestamp options when
11910  * sending a packet back to ourselves.
11911  * Check that we are at end of strict source route.
11912  * The options have been sanity checked by ip_output_options().
11913  */
11914 void
11915 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11916 {
11917 	ipoptp_t	opts;
11918 	uchar_t		*opt;
11919 	uint8_t		optval;
11920 	uint8_t		optlen;
11921 	ipaddr_t	dst;
11922 	uint32_t	ts;
11923 	timestruc_t	now;
11924 
11925 	for (optval = ipoptp_first(&opts, ipha);
11926 	    optval != IPOPT_EOL;
11927 	    optval = ipoptp_next(&opts)) {
11928 		opt = opts.ipoptp_cur;
11929 		optlen = opts.ipoptp_len;
11930 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11931 		switch (optval) {
11932 			uint32_t off;
11933 		case IPOPT_SSRR:
11934 		case IPOPT_LSRR:
11935 			off = opt[IPOPT_OFFSET];
11936 			off--;
11937 			if (optlen < IP_ADDR_LEN ||
11938 			    off > optlen - IP_ADDR_LEN) {
11939 				/* End of source route */
11940 				break;
11941 			}
11942 			/*
11943 			 * This will only happen if two consecutive entries
11944 			 * in the source route contains our address or if
11945 			 * it is a packet with a loose source route which
11946 			 * reaches us before consuming the whole source route
11947 			 */
11948 
11949 			if (optval == IPOPT_SSRR) {
11950 				return;
11951 			}
11952 			/*
11953 			 * Hack: instead of dropping the packet truncate the
11954 			 * source route to what has been used by filling the
11955 			 * rest with IPOPT_NOP.
11956 			 */
11957 			opt[IPOPT_OLEN] = (uint8_t)off;
11958 			while (off < optlen) {
11959 				opt[off++] = IPOPT_NOP;
11960 			}
11961 			break;
11962 		case IPOPT_RR:
11963 			off = opt[IPOPT_OFFSET];
11964 			off--;
11965 			if (optlen < IP_ADDR_LEN ||
11966 			    off > optlen - IP_ADDR_LEN) {
11967 				/* No more room - ignore */
11968 				ip1dbg((
11969 				    "ip_output_local_options: end of RR\n"));
11970 				break;
11971 			}
11972 			dst = htonl(INADDR_LOOPBACK);
11973 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11974 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11975 			break;
11976 		case IPOPT_TS:
11977 			/* Insert timestamp if there is romm */
11978 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11979 			case IPOPT_TS_TSONLY:
11980 				off = IPOPT_TS_TIMELEN;
11981 				break;
11982 			case IPOPT_TS_PRESPEC:
11983 			case IPOPT_TS_PRESPEC_RFC791:
11984 				/* Verify that the address matched */
11985 				off = opt[IPOPT_OFFSET] - 1;
11986 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
11987 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11988 					/* Not for us */
11989 					break;
11990 				}
11991 				/* FALLTHRU */
11992 			case IPOPT_TS_TSANDADDR:
11993 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
11994 				break;
11995 			default:
11996 				/*
11997 				 * ip_*put_options should have already
11998 				 * dropped this packet.
11999 				 */
12000 				cmn_err(CE_PANIC, "ip_output_local_options: "
12001 				    "unknown IT - bug in ip_output_options?\n");
12002 				return;	/* Keep "lint" happy */
12003 			}
12004 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
12005 				/* Increase overflow counter */
12006 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
12007 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
12008 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
12009 				    (off << 4);
12010 				break;
12011 			}
12012 			off = opt[IPOPT_OFFSET] - 1;
12013 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12014 			case IPOPT_TS_PRESPEC:
12015 			case IPOPT_TS_PRESPEC_RFC791:
12016 			case IPOPT_TS_TSANDADDR:
12017 				dst = htonl(INADDR_LOOPBACK);
12018 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12019 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12020 				/* FALLTHRU */
12021 			case IPOPT_TS_TSONLY:
12022 				off = opt[IPOPT_OFFSET] - 1;
12023 				/* Compute # of milliseconds since midnight */
12024 				gethrestime(&now);
12025 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
12026 				    now.tv_nsec / (NANOSEC / MILLISEC);
12027 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
12028 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
12029 				break;
12030 			}
12031 			break;
12032 		}
12033 	}
12034 }
12035 
12036 /*
12037  * Prepend an M_DATA fastpath header, and if none present prepend a
12038  * DL_UNITDATA_REQ. Frees the mblk on failure.
12039  *
12040  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12041  * If there is a change to them, the nce will be deleted (condemned) and
12042  * a new nce_t will be created when packets are sent. Thus we need no locks
12043  * to access those fields.
12044  *
12045  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12046  * we place b_band in dl_priority.dl_max.
12047  */
12048 static mblk_t *
12049 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12050 {
12051 	uint_t	hlen;
12052 	mblk_t *mp1;
12053 	uint_t	priority;
12054 	uchar_t *rptr;
12055 
12056 	rptr = mp->b_rptr;
12057 
12058 	ASSERT(DB_TYPE(mp) == M_DATA);
12059 	priority = mp->b_band;
12060 
12061 	ASSERT(nce != NULL);
12062 	if ((mp1 = nce->nce_fp_mp) != NULL) {
12063 		hlen = MBLKL(mp1);
12064 		/*
12065 		 * Check if we have enough room to prepend fastpath
12066 		 * header
12067 		 */
12068 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12069 			rptr -= hlen;
12070 			bcopy(mp1->b_rptr, rptr, hlen);
12071 			/*
12072 			 * Set the b_rptr to the start of the link layer
12073 			 * header
12074 			 */
12075 			mp->b_rptr = rptr;
12076 			return (mp);
12077 		}
12078 		mp1 = copyb(mp1);
12079 		if (mp1 == NULL) {
12080 			ill_t *ill = nce->nce_ill;
12081 
12082 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12083 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12084 			freemsg(mp);
12085 			return (NULL);
12086 		}
12087 		mp1->b_band = priority;
12088 		mp1->b_cont = mp;
12089 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12090 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12091 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12092 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12093 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12094 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12095 		/*
12096 		 * XXX disable ICK_VALID and compute checksum
12097 		 * here; can happen if nce_fp_mp changes and
12098 		 * it can't be copied now due to insufficient
12099 		 * space. (unlikely, fp mp can change, but it
12100 		 * does not increase in length)
12101 		 */
12102 		return (mp1);
12103 	}
12104 	mp1 = copyb(nce->nce_dlur_mp);
12105 
12106 	if (mp1 == NULL) {
12107 		ill_t *ill = nce->nce_ill;
12108 
12109 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12110 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12111 		freemsg(mp);
12112 		return (NULL);
12113 	}
12114 	mp1->b_cont = mp;
12115 	if (priority != 0) {
12116 		mp1->b_band = priority;
12117 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12118 		    priority;
12119 	}
12120 	return (mp1);
12121 #undef rptr
12122 }
12123 
12124 /*
12125  * Finish the outbound IPsec processing. This function is called from
12126  * ipsec_out_process() if the IPsec packet was processed
12127  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12128  * asynchronously.
12129  *
12130  * This is common to IPv4 and IPv6.
12131  */
12132 int
12133 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12134 {
12135 	iaflags_t	ixaflags = ixa->ixa_flags;
12136 	uint_t		pktlen;
12137 
12138 
12139 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12140 	if (ixaflags & IXAF_IS_IPV4) {
12141 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12142 
12143 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12144 		pktlen = ntohs(ipha->ipha_length);
12145 	} else {
12146 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12147 
12148 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12149 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12150 	}
12151 
12152 	/*
12153 	 * We release any hard reference on the SAs here to make
12154 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12155 	 * on the SAs.
12156 	 * If in the future we want the hard latching of the SAs in the
12157 	 * ip_xmit_attr_t then we should remove this.
12158 	 */
12159 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12160 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12161 		ixa->ixa_ipsec_esp_sa = NULL;
12162 	}
12163 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12164 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12165 		ixa->ixa_ipsec_ah_sa = NULL;
12166 	}
12167 
12168 	/* Do we need to fragment? */
12169 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12170 	    pktlen > ixa->ixa_fragsize) {
12171 		if (ixaflags & IXAF_IS_IPV4) {
12172 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12173 			/*
12174 			 * We check for the DF case in ipsec_out_process
12175 			 * hence this only handles the non-DF case.
12176 			 */
12177 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12178 			    pktlen, ixa->ixa_fragsize,
12179 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12180 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12181 			    &ixa->ixa_cookie));
12182 		} else {
12183 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12184 			if (mp == NULL) {
12185 				/* MIB and ip_drop_output already done */
12186 				return (ENOMEM);
12187 			}
12188 			pktlen += sizeof (ip6_frag_t);
12189 			if (pktlen > ixa->ixa_fragsize) {
12190 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12191 				    ixa->ixa_flags, pktlen,
12192 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12193 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12194 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12195 			}
12196 		}
12197 	}
12198 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12199 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12200 	    ixa->ixa_no_loop_zoneid, NULL));
12201 }
12202 
12203 /*
12204  * Finish the inbound IPsec processing. This function is called from
12205  * ipsec_out_process() if the IPsec packet was processed
12206  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12207  * asynchronously.
12208  *
12209  * This is common to IPv4 and IPv6.
12210  */
12211 void
12212 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12213 {
12214 	iaflags_t	iraflags = ira->ira_flags;
12215 
12216 	/* Length might have changed */
12217 	if (iraflags & IRAF_IS_IPV4) {
12218 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12219 
12220 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12221 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12222 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12223 		ira->ira_protocol = ipha->ipha_protocol;
12224 
12225 		ip_fanout_v4(mp, ipha, ira);
12226 	} else {
12227 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12228 		uint8_t		*nexthdrp;
12229 
12230 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12231 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12232 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12233 		    &nexthdrp)) {
12234 			/* Malformed packet */
12235 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12236 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12237 			freemsg(mp);
12238 			return;
12239 		}
12240 		ira->ira_protocol = *nexthdrp;
12241 		ip_fanout_v6(mp, ip6h, ira);
12242 	}
12243 }
12244 
12245 /*
12246  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12247  *
12248  * If this function returns B_TRUE, the requested SA's have been filled
12249  * into the ixa_ipsec_*_sa pointers.
12250  *
12251  * If the function returns B_FALSE, the packet has been "consumed", most
12252  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12253  *
12254  * The SA references created by the protocol-specific "select"
12255  * function will be released in ip_output_post_ipsec.
12256  */
12257 static boolean_t
12258 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12259 {
12260 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12261 	ipsec_policy_t *pp;
12262 	ipsec_action_t *ap;
12263 
12264 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12265 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12266 	    (ixa->ixa_ipsec_action != NULL));
12267 
12268 	ap = ixa->ixa_ipsec_action;
12269 	if (ap == NULL) {
12270 		pp = ixa->ixa_ipsec_policy;
12271 		ASSERT(pp != NULL);
12272 		ap = pp->ipsp_act;
12273 		ASSERT(ap != NULL);
12274 	}
12275 
12276 	/*
12277 	 * We have an action.  now, let's select SA's.
12278 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12279 	 * be cached in the conn_t.
12280 	 */
12281 	if (ap->ipa_want_esp) {
12282 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12283 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12284 			    IPPROTO_ESP);
12285 		}
12286 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12287 	}
12288 
12289 	if (ap->ipa_want_ah) {
12290 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12291 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12292 			    IPPROTO_AH);
12293 		}
12294 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12295 		/*
12296 		 * The ESP and AH processing order needs to be preserved
12297 		 * when both protocols are required (ESP should be applied
12298 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12299 		 * when both ESP and AH are required, and an AH ACQUIRE
12300 		 * is needed.
12301 		 */
12302 		if (ap->ipa_want_esp && need_ah_acquire)
12303 			need_esp_acquire = B_TRUE;
12304 	}
12305 
12306 	/*
12307 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12308 	 * Release SAs that got referenced, but will not be used until we
12309 	 * acquire _all_ of the SAs we need.
12310 	 */
12311 	if (need_ah_acquire || need_esp_acquire) {
12312 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12313 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12314 			ixa->ixa_ipsec_ah_sa = NULL;
12315 		}
12316 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12317 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12318 			ixa->ixa_ipsec_esp_sa = NULL;
12319 		}
12320 
12321 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12322 		return (B_FALSE);
12323 	}
12324 
12325 	return (B_TRUE);
12326 }
12327 
12328 /*
12329  * Handle IPsec output processing.
12330  * This function is only entered once for a given packet.
12331  * We try to do things synchronously, but if we need to have user-level
12332  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12333  * will be completed
12334  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12335  *  - when asynchronous ESP is done it will do AH
12336  *
12337  * In all cases we come back in ip_output_post_ipsec() to fragment and
12338  * send out the packet.
12339  */
12340 int
12341 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12342 {
12343 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12344 	ip_stack_t	*ipst = ixa->ixa_ipst;
12345 	ipsec_stack_t	*ipss;
12346 	ipsec_policy_t	*pp;
12347 	ipsec_action_t	*ap;
12348 
12349 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12350 
12351 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12352 	    (ixa->ixa_ipsec_action != NULL));
12353 
12354 	ipss = ipst->ips_netstack->netstack_ipsec;
12355 	if (!ipsec_loaded(ipss)) {
12356 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12357 		ip_drop_packet(mp, B_TRUE, ill,
12358 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12359 		    &ipss->ipsec_dropper);
12360 		return (ENOTSUP);
12361 	}
12362 
12363 	ap = ixa->ixa_ipsec_action;
12364 	if (ap == NULL) {
12365 		pp = ixa->ixa_ipsec_policy;
12366 		ASSERT(pp != NULL);
12367 		ap = pp->ipsp_act;
12368 		ASSERT(ap != NULL);
12369 	}
12370 
12371 	/* Handle explicit drop action and bypass. */
12372 	switch (ap->ipa_act.ipa_type) {
12373 	case IPSEC_ACT_DISCARD:
12374 	case IPSEC_ACT_REJECT:
12375 		ip_drop_packet(mp, B_FALSE, ill,
12376 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12377 		return (EHOSTUNREACH);	/* IPsec policy failure */
12378 	case IPSEC_ACT_BYPASS:
12379 		return (ip_output_post_ipsec(mp, ixa));
12380 	}
12381 
12382 	/*
12383 	 * The order of processing is first insert a IP header if needed.
12384 	 * Then insert the ESP header and then the AH header.
12385 	 */
12386 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12387 		/*
12388 		 * First get the outer IP header before sending
12389 		 * it to ESP.
12390 		 */
12391 		ipha_t *oipha, *iipha;
12392 		mblk_t *outer_mp, *inner_mp;
12393 
12394 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12395 			(void) mi_strlog(ill->ill_rq, 0,
12396 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12397 			    "ipsec_out_process: "
12398 			    "Self-Encapsulation failed: Out of memory\n");
12399 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12400 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12401 			freemsg(mp);
12402 			return (ENOBUFS);
12403 		}
12404 		inner_mp = mp;
12405 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12406 		oipha = (ipha_t *)outer_mp->b_rptr;
12407 		iipha = (ipha_t *)inner_mp->b_rptr;
12408 		*oipha = *iipha;
12409 		outer_mp->b_wptr += sizeof (ipha_t);
12410 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12411 		    sizeof (ipha_t));
12412 		oipha->ipha_protocol = IPPROTO_ENCAP;
12413 		oipha->ipha_version_and_hdr_length =
12414 		    IP_SIMPLE_HDR_VERSION;
12415 		oipha->ipha_hdr_checksum = 0;
12416 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12417 		outer_mp->b_cont = inner_mp;
12418 		mp = outer_mp;
12419 
12420 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12421 	}
12422 
12423 	/* If we need to wait for a SA then we can't return any errno */
12424 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12425 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12426 	    !ipsec_out_select_sa(mp, ixa))
12427 		return (0);
12428 
12429 	/*
12430 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12431 	 * to do the heavy lifting.
12432 	 */
12433 	if (ap->ipa_want_esp) {
12434 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12435 
12436 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12437 		if (mp == NULL) {
12438 			/*
12439 			 * Either it failed or is pending. In the former case
12440 			 * ipIfStatsInDiscards was increased.
12441 			 */
12442 			return (0);
12443 		}
12444 	}
12445 
12446 	if (ap->ipa_want_ah) {
12447 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12448 
12449 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12450 		if (mp == NULL) {
12451 			/*
12452 			 * Either it failed or is pending. In the former case
12453 			 * ipIfStatsInDiscards was increased.
12454 			 */
12455 			return (0);
12456 		}
12457 	}
12458 	/*
12459 	 * We are done with IPsec processing. Send it over
12460 	 * the wire.
12461 	 */
12462 	return (ip_output_post_ipsec(mp, ixa));
12463 }
12464 
12465 /*
12466  * ioctls that go through a down/up sequence may need to wait for the down
12467  * to complete. This involves waiting for the ire and ipif refcnts to go down
12468  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12469  */
12470 /* ARGSUSED */
12471 void
12472 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12473 {
12474 	struct iocblk *iocp;
12475 	mblk_t *mp1;
12476 	ip_ioctl_cmd_t *ipip;
12477 	int err;
12478 	sin_t	*sin;
12479 	struct lifreq *lifr;
12480 	struct ifreq *ifr;
12481 
12482 	iocp = (struct iocblk *)mp->b_rptr;
12483 	ASSERT(ipsq != NULL);
12484 	/* Existence of mp1 verified in ip_wput_nondata */
12485 	mp1 = mp->b_cont->b_cont;
12486 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12487 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12488 		/*
12489 		 * Special case where ipx_current_ipif is not set:
12490 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12491 		 * We are here as were not able to complete the operation in
12492 		 * ipif_set_values because we could not become exclusive on
12493 		 * the new ipsq.
12494 		 */
12495 		ill_t *ill = q->q_ptr;
12496 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12497 	}
12498 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12499 
12500 	if (ipip->ipi_cmd_type == IF_CMD) {
12501 		/* This a old style SIOC[GS]IF* command */
12502 		ifr = (struct ifreq *)mp1->b_rptr;
12503 		sin = (sin_t *)&ifr->ifr_addr;
12504 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12505 		/* This a new style SIOC[GS]LIF* command */
12506 		lifr = (struct lifreq *)mp1->b_rptr;
12507 		sin = (sin_t *)&lifr->lifr_addr;
12508 	} else {
12509 		sin = NULL;
12510 	}
12511 
12512 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12513 	    q, mp, ipip, mp1->b_rptr);
12514 
12515 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12516 	    int, ipip->ipi_cmd,
12517 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12518 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12519 
12520 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12521 }
12522 
12523 /*
12524  * ioctl processing
12525  *
12526  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12527  * the ioctl command in the ioctl tables, determines the copyin data size
12528  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12529  *
12530  * ioctl processing then continues when the M_IOCDATA makes its way down to
12531  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12532  * associated 'conn' is refheld till the end of the ioctl and the general
12533  * ioctl processing function ip_process_ioctl() is called to extract the
12534  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12535  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12536  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12537  * is used to extract the ioctl's arguments.
12538  *
12539  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12540  * so goes thru the serialization primitive ipsq_try_enter. Then the
12541  * appropriate function to handle the ioctl is called based on the entry in
12542  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12543  * which also refreleases the 'conn' that was refheld at the start of the
12544  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12545  *
12546  * Many exclusive ioctls go thru an internal down up sequence as part of
12547  * the operation. For example an attempt to change the IP address of an
12548  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12549  * does all the cleanup such as deleting all ires that use this address.
12550  * Then we need to wait till all references to the interface go away.
12551  */
12552 void
12553 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12554 {
12555 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12556 	ip_ioctl_cmd_t *ipip = arg;
12557 	ip_extract_func_t *extract_funcp;
12558 	cmd_info_t ci;
12559 	int err;
12560 	boolean_t entered_ipsq = B_FALSE;
12561 
12562 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12563 
12564 	if (ipip == NULL)
12565 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12566 
12567 	/*
12568 	 * SIOCLIFADDIF needs to go thru a special path since the
12569 	 * ill may not exist yet. This happens in the case of lo0
12570 	 * which is created using this ioctl.
12571 	 */
12572 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12573 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12574 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12575 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12576 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12577 		return;
12578 	}
12579 
12580 	ci.ci_ipif = NULL;
12581 	switch (ipip->ipi_cmd_type) {
12582 	case MISC_CMD:
12583 	case MSFILT_CMD:
12584 		/*
12585 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12586 		 */
12587 		if (ipip->ipi_cmd == IF_UNITSEL) {
12588 			/* ioctl comes down the ill */
12589 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12590 			ipif_refhold(ci.ci_ipif);
12591 		}
12592 		err = 0;
12593 		ci.ci_sin = NULL;
12594 		ci.ci_sin6 = NULL;
12595 		ci.ci_lifr = NULL;
12596 		extract_funcp = NULL;
12597 		break;
12598 
12599 	case IF_CMD:
12600 	case LIF_CMD:
12601 		extract_funcp = ip_extract_lifreq;
12602 		break;
12603 
12604 	case ARP_CMD:
12605 	case XARP_CMD:
12606 		extract_funcp = ip_extract_arpreq;
12607 		break;
12608 
12609 	default:
12610 		ASSERT(0);
12611 	}
12612 
12613 	if (extract_funcp != NULL) {
12614 		err = (*extract_funcp)(q, mp, ipip, &ci);
12615 		if (err != 0) {
12616 			DTRACE_PROBE4(ipif__ioctl,
12617 			    char *, "ip_process_ioctl finish err",
12618 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12619 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12620 			return;
12621 		}
12622 
12623 		/*
12624 		 * All of the extraction functions return a refheld ipif.
12625 		 */
12626 		ASSERT(ci.ci_ipif != NULL);
12627 	}
12628 
12629 	if (!(ipip->ipi_flags & IPI_WR)) {
12630 		/*
12631 		 * A return value of EINPROGRESS means the ioctl is
12632 		 * either queued and waiting for some reason or has
12633 		 * already completed.
12634 		 */
12635 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12636 		    ci.ci_lifr);
12637 		if (ci.ci_ipif != NULL) {
12638 			DTRACE_PROBE4(ipif__ioctl,
12639 			    char *, "ip_process_ioctl finish RD",
12640 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12641 			    ipif_t *, ci.ci_ipif);
12642 			ipif_refrele(ci.ci_ipif);
12643 		} else {
12644 			DTRACE_PROBE4(ipif__ioctl,
12645 			    char *, "ip_process_ioctl finish RD",
12646 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12647 		}
12648 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12649 		return;
12650 	}
12651 
12652 	ASSERT(ci.ci_ipif != NULL);
12653 
12654 	/*
12655 	 * If ipsq is non-NULL, we are already being called exclusively
12656 	 */
12657 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12658 	if (ipsq == NULL) {
12659 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12660 		    NEW_OP, B_TRUE);
12661 		if (ipsq == NULL) {
12662 			ipif_refrele(ci.ci_ipif);
12663 			return;
12664 		}
12665 		entered_ipsq = B_TRUE;
12666 	}
12667 	/*
12668 	 * Release the ipif so that ipif_down and friends that wait for
12669 	 * references to go away are not misled about the current ipif_refcnt
12670 	 * values. We are writer so we can access the ipif even after releasing
12671 	 * the ipif.
12672 	 */
12673 	ipif_refrele(ci.ci_ipif);
12674 
12675 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12676 
12677 	/*
12678 	 * A return value of EINPROGRESS means the ioctl is
12679 	 * either queued and waiting for some reason or has
12680 	 * already completed.
12681 	 */
12682 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12683 
12684 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12685 	    int, ipip->ipi_cmd,
12686 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12687 	    ipif_t *, ci.ci_ipif);
12688 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12689 
12690 	if (entered_ipsq)
12691 		ipsq_exit(ipsq);
12692 }
12693 
12694 /*
12695  * Complete the ioctl. Typically ioctls use the mi package and need to
12696  * do mi_copyout/mi_copy_done.
12697  */
12698 void
12699 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12700 {
12701 	conn_t	*connp = NULL;
12702 
12703 	if (err == EINPROGRESS)
12704 		return;
12705 
12706 	if (CONN_Q(q)) {
12707 		connp = Q_TO_CONN(q);
12708 		ASSERT(connp->conn_ref >= 2);
12709 	}
12710 
12711 	switch (mode) {
12712 	case COPYOUT:
12713 		if (err == 0)
12714 			mi_copyout(q, mp);
12715 		else
12716 			mi_copy_done(q, mp, err);
12717 		break;
12718 
12719 	case NO_COPYOUT:
12720 		mi_copy_done(q, mp, err);
12721 		break;
12722 
12723 	default:
12724 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12725 		break;
12726 	}
12727 
12728 	/*
12729 	 * The conn refhold and ioctlref placed on the conn at the start of the
12730 	 * ioctl are released here.
12731 	 */
12732 	if (connp != NULL) {
12733 		CONN_DEC_IOCTLREF(connp);
12734 		CONN_OPER_PENDING_DONE(connp);
12735 	}
12736 
12737 	if (ipsq != NULL)
12738 		ipsq_current_finish(ipsq);
12739 }
12740 
12741 /* Handles all non data messages */
12742 void
12743 ip_wput_nondata(queue_t *q, mblk_t *mp)
12744 {
12745 	mblk_t		*mp1;
12746 	struct iocblk	*iocp;
12747 	ip_ioctl_cmd_t	*ipip;
12748 	conn_t		*connp;
12749 	cred_t		*cr;
12750 	char		*proto_str;
12751 
12752 	if (CONN_Q(q))
12753 		connp = Q_TO_CONN(q);
12754 	else
12755 		connp = NULL;
12756 
12757 	switch (DB_TYPE(mp)) {
12758 	case M_IOCTL:
12759 		/*
12760 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12761 		 * will arrange to copy in associated control structures.
12762 		 */
12763 		ip_sioctl_copyin_setup(q, mp);
12764 		return;
12765 	case M_IOCDATA:
12766 		/*
12767 		 * Ensure that this is associated with one of our trans-
12768 		 * parent ioctls.  If it's not ours, discard it if we're
12769 		 * running as a driver, or pass it on if we're a module.
12770 		 */
12771 		iocp = (struct iocblk *)mp->b_rptr;
12772 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12773 		if (ipip == NULL) {
12774 			if (q->q_next == NULL) {
12775 				goto nak;
12776 			} else {
12777 				putnext(q, mp);
12778 			}
12779 			return;
12780 		}
12781 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12782 			/*
12783 			 * The ioctl is one we recognise, but is not consumed
12784 			 * by IP as a module and we are a module, so we drop
12785 			 */
12786 			goto nak;
12787 		}
12788 
12789 		/* IOCTL continuation following copyin or copyout. */
12790 		if (mi_copy_state(q, mp, NULL) == -1) {
12791 			/*
12792 			 * The copy operation failed.  mi_copy_state already
12793 			 * cleaned up, so we're out of here.
12794 			 */
12795 			return;
12796 		}
12797 		/*
12798 		 * If we just completed a copy in, we become writer and
12799 		 * continue processing in ip_sioctl_copyin_done.  If it
12800 		 * was a copy out, we call mi_copyout again.  If there is
12801 		 * nothing more to copy out, it will complete the IOCTL.
12802 		 */
12803 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12804 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12805 				mi_copy_done(q, mp, EPROTO);
12806 				return;
12807 			}
12808 			/*
12809 			 * Check for cases that need more copying.  A return
12810 			 * value of 0 means a second copyin has been started,
12811 			 * so we return; a return value of 1 means no more
12812 			 * copying is needed, so we continue.
12813 			 */
12814 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12815 			    MI_COPY_COUNT(mp) == 1) {
12816 				if (ip_copyin_msfilter(q, mp) == 0)
12817 					return;
12818 			}
12819 			/*
12820 			 * Refhold the conn, till the ioctl completes. This is
12821 			 * needed in case the ioctl ends up in the pending mp
12822 			 * list. Every mp in the ipx_pending_mp list must have
12823 			 * a refhold on the conn to resume processing. The
12824 			 * refhold is released when the ioctl completes
12825 			 * (whether normally or abnormally). An ioctlref is also
12826 			 * placed on the conn to prevent TCP from removing the
12827 			 * queue needed to send the ioctl reply back.
12828 			 * In all cases ip_ioctl_finish is called to finish
12829 			 * the ioctl and release the refholds.
12830 			 */
12831 			if (connp != NULL) {
12832 				/* This is not a reentry */
12833 				CONN_INC_REF(connp);
12834 				CONN_INC_IOCTLREF(connp);
12835 			} else {
12836 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12837 					mi_copy_done(q, mp, EINVAL);
12838 					return;
12839 				}
12840 			}
12841 
12842 			ip_process_ioctl(NULL, q, mp, ipip);
12843 
12844 		} else {
12845 			mi_copyout(q, mp);
12846 		}
12847 		return;
12848 
12849 	case M_IOCNAK:
12850 		/*
12851 		 * The only way we could get here is if a resolver didn't like
12852 		 * an IOCTL we sent it.	 This shouldn't happen.
12853 		 */
12854 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12855 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12856 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12857 		freemsg(mp);
12858 		return;
12859 	case M_IOCACK:
12860 		/* /dev/ip shouldn't see this */
12861 		goto nak;
12862 	case M_FLUSH:
12863 		if (*mp->b_rptr & FLUSHW)
12864 			flushq(q, FLUSHALL);
12865 		if (q->q_next) {
12866 			putnext(q, mp);
12867 			return;
12868 		}
12869 		if (*mp->b_rptr & FLUSHR) {
12870 			*mp->b_rptr &= ~FLUSHW;
12871 			qreply(q, mp);
12872 			return;
12873 		}
12874 		freemsg(mp);
12875 		return;
12876 	case M_CTL:
12877 		break;
12878 	case M_PROTO:
12879 	case M_PCPROTO:
12880 		/*
12881 		 * The only PROTO messages we expect are SNMP-related.
12882 		 */
12883 		switch (((union T_primitives *)mp->b_rptr)->type) {
12884 		case T_SVR4_OPTMGMT_REQ:
12885 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12886 			    "flags %x\n",
12887 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12888 
12889 			if (connp == NULL) {
12890 				proto_str = "T_SVR4_OPTMGMT_REQ";
12891 				goto protonak;
12892 			}
12893 
12894 			/*
12895 			 * All Solaris components should pass a db_credp
12896 			 * for this TPI message, hence we ASSERT.
12897 			 * But in case there is some other M_PROTO that looks
12898 			 * like a TPI message sent by some other kernel
12899 			 * component, we check and return an error.
12900 			 */
12901 			cr = msg_getcred(mp, NULL);
12902 			ASSERT(cr != NULL);
12903 			if (cr == NULL) {
12904 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12905 				if (mp != NULL)
12906 					qreply(q, mp);
12907 				return;
12908 			}
12909 
12910 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12911 				proto_str = "Bad SNMPCOM request?";
12912 				goto protonak;
12913 			}
12914 			return;
12915 		default:
12916 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12917 			    (int)*(uint_t *)mp->b_rptr));
12918 			freemsg(mp);
12919 			return;
12920 		}
12921 	default:
12922 		break;
12923 	}
12924 	if (q->q_next) {
12925 		putnext(q, mp);
12926 	} else
12927 		freemsg(mp);
12928 	return;
12929 
12930 nak:
12931 	iocp->ioc_error = EINVAL;
12932 	mp->b_datap->db_type = M_IOCNAK;
12933 	iocp->ioc_count = 0;
12934 	qreply(q, mp);
12935 	return;
12936 
12937 protonak:
12938 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12939 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12940 		qreply(q, mp);
12941 }
12942 
12943 /*
12944  * Process IP options in an outbound packet.  Verify that the nexthop in a
12945  * strict source route is onlink.
12946  * Returns non-zero if something fails in which case an ICMP error has been
12947  * sent and mp freed.
12948  *
12949  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12950  */
12951 int
12952 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12953 {
12954 	ipoptp_t	opts;
12955 	uchar_t		*opt;
12956 	uint8_t		optval;
12957 	uint8_t		optlen;
12958 	ipaddr_t	dst;
12959 	intptr_t	code = 0;
12960 	ire_t		*ire;
12961 	ip_stack_t	*ipst = ixa->ixa_ipst;
12962 	ip_recv_attr_t	iras;
12963 
12964 	ip2dbg(("ip_output_options\n"));
12965 
12966 	dst = ipha->ipha_dst;
12967 	for (optval = ipoptp_first(&opts, ipha);
12968 	    optval != IPOPT_EOL;
12969 	    optval = ipoptp_next(&opts)) {
12970 		opt = opts.ipoptp_cur;
12971 		optlen = opts.ipoptp_len;
12972 		ip2dbg(("ip_output_options: opt %d, len %d\n",
12973 		    optval, optlen));
12974 		switch (optval) {
12975 			uint32_t off;
12976 		case IPOPT_SSRR:
12977 		case IPOPT_LSRR:
12978 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12979 				ip1dbg((
12980 				    "ip_output_options: bad option offset\n"));
12981 				code = (char *)&opt[IPOPT_OLEN] -
12982 				    (char *)ipha;
12983 				goto param_prob;
12984 			}
12985 			off = opt[IPOPT_OFFSET];
12986 			ip1dbg(("ip_output_options: next hop 0x%x\n",
12987 			    ntohl(dst)));
12988 			/*
12989 			 * For strict: verify that dst is directly
12990 			 * reachable.
12991 			 */
12992 			if (optval == IPOPT_SSRR) {
12993 				ire = ire_ftable_lookup_v4(dst, 0, 0,
12994 				    IRE_INTERFACE, NULL, ALL_ZONES,
12995 				    ixa->ixa_tsl,
12996 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
12997 				    NULL);
12998 				if (ire == NULL) {
12999 					ip1dbg(("ip_output_options: SSRR not"
13000 					    " directly reachable: 0x%x\n",
13001 					    ntohl(dst)));
13002 					goto bad_src_route;
13003 				}
13004 				ire_refrele(ire);
13005 			}
13006 			break;
13007 		case IPOPT_RR:
13008 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13009 				ip1dbg((
13010 				    "ip_output_options: bad option offset\n"));
13011 				code = (char *)&opt[IPOPT_OLEN] -
13012 				    (char *)ipha;
13013 				goto param_prob;
13014 			}
13015 			break;
13016 		case IPOPT_TS:
13017 			/*
13018 			 * Verify that length >=5 and that there is either
13019 			 * room for another timestamp or that the overflow
13020 			 * counter is not maxed out.
13021 			 */
13022 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
13023 			if (optlen < IPOPT_MINLEN_IT) {
13024 				goto param_prob;
13025 			}
13026 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13027 				ip1dbg((
13028 				    "ip_output_options: bad option offset\n"));
13029 				code = (char *)&opt[IPOPT_OFFSET] -
13030 				    (char *)ipha;
13031 				goto param_prob;
13032 			}
13033 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13034 			case IPOPT_TS_TSONLY:
13035 				off = IPOPT_TS_TIMELEN;
13036 				break;
13037 			case IPOPT_TS_TSANDADDR:
13038 			case IPOPT_TS_PRESPEC:
13039 			case IPOPT_TS_PRESPEC_RFC791:
13040 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13041 				break;
13042 			default:
13043 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
13044 				    (char *)ipha;
13045 				goto param_prob;
13046 			}
13047 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13048 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13049 				/*
13050 				 * No room and the overflow counter is 15
13051 				 * already.
13052 				 */
13053 				goto param_prob;
13054 			}
13055 			break;
13056 		}
13057 	}
13058 
13059 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13060 		return (0);
13061 
13062 	ip1dbg(("ip_output_options: error processing IP options."));
13063 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13064 
13065 param_prob:
13066 	bzero(&iras, sizeof (iras));
13067 	iras.ira_ill = iras.ira_rill = ill;
13068 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13069 	iras.ira_rifindex = iras.ira_ruifindex;
13070 	iras.ira_flags = IRAF_IS_IPV4;
13071 
13072 	ip_drop_output("ip_output_options", mp, ill);
13073 	icmp_param_problem(mp, (uint8_t)code, &iras);
13074 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13075 	return (-1);
13076 
13077 bad_src_route:
13078 	bzero(&iras, sizeof (iras));
13079 	iras.ira_ill = iras.ira_rill = ill;
13080 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13081 	iras.ira_rifindex = iras.ira_ruifindex;
13082 	iras.ira_flags = IRAF_IS_IPV4;
13083 
13084 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13085 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13086 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13087 	return (-1);
13088 }
13089 
13090 /*
13091  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13092  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13093  * thru /etc/system.
13094  */
13095 #define	CONN_MAXDRAINCNT	64
13096 
13097 static void
13098 conn_drain_init(ip_stack_t *ipst)
13099 {
13100 	int i, j;
13101 	idl_tx_list_t *itl_tx;
13102 
13103 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13104 
13105 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
13106 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13107 		/*
13108 		 * Default value of the number of drainers is the
13109 		 * number of cpus, subject to maximum of 8 drainers.
13110 		 */
13111 		if (boot_max_ncpus != -1)
13112 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13113 		else
13114 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13115 	}
13116 
13117 	ipst->ips_idl_tx_list =
13118 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13119 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13120 		itl_tx =  &ipst->ips_idl_tx_list[i];
13121 		itl_tx->txl_drain_list =
13122 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13123 		    sizeof (idl_t), KM_SLEEP);
13124 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13125 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13126 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13127 			    MUTEX_DEFAULT, NULL);
13128 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13129 		}
13130 	}
13131 }
13132 
13133 static void
13134 conn_drain_fini(ip_stack_t *ipst)
13135 {
13136 	int i;
13137 	idl_tx_list_t *itl_tx;
13138 
13139 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13140 		itl_tx =  &ipst->ips_idl_tx_list[i];
13141 		kmem_free(itl_tx->txl_drain_list,
13142 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13143 	}
13144 	kmem_free(ipst->ips_idl_tx_list,
13145 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13146 	ipst->ips_idl_tx_list = NULL;
13147 }
13148 
13149 /*
13150  * Flow control has blocked us from proceeding.  Insert the given conn in one
13151  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13152  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13153  * will call conn_walk_drain().  See the flow control notes at the top of this
13154  * file for more details.
13155  */
13156 void
13157 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13158 {
13159 	idl_t	*idl = tx_list->txl_drain_list;
13160 	uint_t	index;
13161 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13162 
13163 	mutex_enter(&connp->conn_lock);
13164 	if (connp->conn_state_flags & CONN_CLOSING) {
13165 		/*
13166 		 * The conn is closing as a result of which CONN_CLOSING
13167 		 * is set. Return.
13168 		 */
13169 		mutex_exit(&connp->conn_lock);
13170 		return;
13171 	} else if (connp->conn_idl == NULL) {
13172 		/*
13173 		 * Assign the next drain list round robin. We dont' use
13174 		 * a lock, and thus it may not be strictly round robin.
13175 		 * Atomicity of load/stores is enough to make sure that
13176 		 * conn_drain_list_index is always within bounds.
13177 		 */
13178 		index = tx_list->txl_drain_index;
13179 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13180 		connp->conn_idl = &tx_list->txl_drain_list[index];
13181 		index++;
13182 		if (index == ipst->ips_conn_drain_list_cnt)
13183 			index = 0;
13184 		tx_list->txl_drain_index = index;
13185 	} else {
13186 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13187 	}
13188 	mutex_exit(&connp->conn_lock);
13189 
13190 	idl = connp->conn_idl;
13191 	mutex_enter(&idl->idl_lock);
13192 	if ((connp->conn_drain_prev != NULL) ||
13193 	    (connp->conn_state_flags & CONN_CLOSING)) {
13194 		/*
13195 		 * The conn is either already in the drain list or closing.
13196 		 * (We needed to check for CONN_CLOSING again since close can
13197 		 * sneak in between dropping conn_lock and acquiring idl_lock.)
13198 		 */
13199 		mutex_exit(&idl->idl_lock);
13200 		return;
13201 	}
13202 
13203 	/*
13204 	 * The conn is not in the drain list. Insert it at the
13205 	 * tail of the drain list. The drain list is circular
13206 	 * and doubly linked. idl_conn points to the 1st element
13207 	 * in the list.
13208 	 */
13209 	if (idl->idl_conn == NULL) {
13210 		idl->idl_conn = connp;
13211 		connp->conn_drain_next = connp;
13212 		connp->conn_drain_prev = connp;
13213 	} else {
13214 		conn_t *head = idl->idl_conn;
13215 
13216 		connp->conn_drain_next = head;
13217 		connp->conn_drain_prev = head->conn_drain_prev;
13218 		head->conn_drain_prev->conn_drain_next = connp;
13219 		head->conn_drain_prev = connp;
13220 	}
13221 	/*
13222 	 * For non streams based sockets assert flow control.
13223 	 */
13224 	conn_setqfull(connp, NULL);
13225 	mutex_exit(&idl->idl_lock);
13226 }
13227 
13228 static void
13229 conn_drain_remove(conn_t *connp)
13230 {
13231 	idl_t *idl = connp->conn_idl;
13232 
13233 	if (idl != NULL) {
13234 		/*
13235 		 * Remove ourself from the drain list.
13236 		 */
13237 		if (connp->conn_drain_next == connp) {
13238 			/* Singleton in the list */
13239 			ASSERT(connp->conn_drain_prev == connp);
13240 			idl->idl_conn = NULL;
13241 		} else {
13242 			connp->conn_drain_prev->conn_drain_next =
13243 			    connp->conn_drain_next;
13244 			connp->conn_drain_next->conn_drain_prev =
13245 			    connp->conn_drain_prev;
13246 			if (idl->idl_conn == connp)
13247 				idl->idl_conn = connp->conn_drain_next;
13248 		}
13249 
13250 		/*
13251 		 * NOTE: because conn_idl is associated with a specific drain
13252 		 * list which in turn is tied to the index the TX ring
13253 		 * (txl_cookie) hashes to, and because the TX ring can change
13254 		 * over the lifetime of the conn_t, we must clear conn_idl so
13255 		 * a subsequent conn_drain_insert() will set conn_idl again
13256 		 * based on the latest txl_cookie.
13257 		 */
13258 		connp->conn_idl = NULL;
13259 	}
13260 	connp->conn_drain_next = NULL;
13261 	connp->conn_drain_prev = NULL;
13262 
13263 	conn_clrqfull(connp, NULL);
13264 	/*
13265 	 * For streams based sockets open up flow control.
13266 	 */
13267 	if (!IPCL_IS_NONSTR(connp))
13268 		enableok(connp->conn_wq);
13269 }
13270 
13271 /*
13272  * This conn is closing, and we are called from ip_close. OR
13273  * this conn is draining because flow-control on the ill has been relieved.
13274  *
13275  * We must also need to remove conn's on this idl from the list, and also
13276  * inform the sockfs upcalls about the change in flow-control.
13277  */
13278 static void
13279 conn_drain(conn_t *connp, boolean_t closing)
13280 {
13281 	idl_t *idl;
13282 	conn_t *next_connp;
13283 
13284 	/*
13285 	 * connp->conn_idl is stable at this point, and no lock is needed
13286 	 * to check it. If we are called from ip_close, close has already
13287 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13288 	 * called us only because conn_idl is non-null. If we are called thru
13289 	 * service, conn_idl could be null, but it cannot change because
13290 	 * service is single-threaded per queue, and there cannot be another
13291 	 * instance of service trying to call conn_drain_insert on this conn
13292 	 * now.
13293 	 */
13294 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13295 
13296 	/*
13297 	 * If the conn doesn't exist or is not on a drain list, bail.
13298 	 */
13299 	if (connp == NULL || connp->conn_idl == NULL ||
13300 	    connp->conn_drain_prev == NULL) {
13301 		return;
13302 	}
13303 
13304 	idl = connp->conn_idl;
13305 	ASSERT(MUTEX_HELD(&idl->idl_lock));
13306 
13307 	if (!closing) {
13308 		next_connp = connp->conn_drain_next;
13309 		while (next_connp != connp) {
13310 			conn_t *delconnp = next_connp;
13311 
13312 			next_connp = next_connp->conn_drain_next;
13313 			conn_drain_remove(delconnp);
13314 		}
13315 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13316 	}
13317 	conn_drain_remove(connp);
13318 }
13319 
13320 /*
13321  * Write service routine. Shared perimeter entry point.
13322  * The device queue's messages has fallen below the low water mark and STREAMS
13323  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13324  * each waiting conn.
13325  */
13326 void
13327 ip_wsrv(queue_t *q)
13328 {
13329 	ill_t	*ill;
13330 
13331 	ill = (ill_t *)q->q_ptr;
13332 	if (ill->ill_state_flags == 0) {
13333 		ip_stack_t *ipst = ill->ill_ipst;
13334 
13335 		/*
13336 		 * The device flow control has opened up.
13337 		 * Walk through conn drain lists and qenable the
13338 		 * first conn in each list. This makes sense only
13339 		 * if the stream is fully plumbed and setup.
13340 		 * Hence the ill_state_flags check above.
13341 		 */
13342 		ip1dbg(("ip_wsrv: walking\n"));
13343 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13344 		enableok(ill->ill_wq);
13345 	}
13346 }
13347 
13348 /*
13349  * Callback to disable flow control in IP.
13350  *
13351  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13352  * is enabled.
13353  *
13354  * When MAC_TX() is not able to send any more packets, dld sets its queue
13355  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13356  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13357  * function and wakes up corresponding mac worker threads, which in turn
13358  * calls this callback function, and disables flow control.
13359  */
13360 void
13361 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13362 {
13363 	ill_t *ill = (ill_t *)arg;
13364 	ip_stack_t *ipst = ill->ill_ipst;
13365 	idl_tx_list_t *idl_txl;
13366 
13367 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13368 	mutex_enter(&idl_txl->txl_lock);
13369 	/* add code to to set a flag to indicate idl_txl is enabled */
13370 	conn_walk_drain(ipst, idl_txl);
13371 	mutex_exit(&idl_txl->txl_lock);
13372 }
13373 
13374 /*
13375  * Flow control has been relieved and STREAMS has backenabled us; drain
13376  * all the conn lists on `tx_list'.
13377  */
13378 static void
13379 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13380 {
13381 	int i;
13382 	idl_t *idl;
13383 
13384 	IP_STAT(ipst, ip_conn_walk_drain);
13385 
13386 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13387 		idl = &tx_list->txl_drain_list[i];
13388 		mutex_enter(&idl->idl_lock);
13389 		conn_drain(idl->idl_conn, B_FALSE);
13390 		mutex_exit(&idl->idl_lock);
13391 	}
13392 }
13393 
13394 /*
13395  * Determine if the ill and multicast aspects of that packets
13396  * "matches" the conn.
13397  */
13398 boolean_t
13399 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13400 {
13401 	ill_t		*ill = ira->ira_rill;
13402 	zoneid_t	zoneid = ira->ira_zoneid;
13403 	uint_t		in_ifindex;
13404 	ipaddr_t	dst, src;
13405 
13406 	dst = ipha->ipha_dst;
13407 	src = ipha->ipha_src;
13408 
13409 	/*
13410 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13411 	 * unicast, broadcast and multicast reception to
13412 	 * conn_incoming_ifindex.
13413 	 * conn_wantpacket is called for unicast, broadcast and
13414 	 * multicast packets.
13415 	 */
13416 	in_ifindex = connp->conn_incoming_ifindex;
13417 
13418 	/* mpathd can bind to the under IPMP interface, which we allow */
13419 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13420 		if (!IS_UNDER_IPMP(ill))
13421 			return (B_FALSE);
13422 
13423 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13424 			return (B_FALSE);
13425 	}
13426 
13427 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13428 		return (B_FALSE);
13429 
13430 	if (!(ira->ira_flags & IRAF_MULTICAST))
13431 		return (B_TRUE);
13432 
13433 	if (connp->conn_multi_router) {
13434 		/* multicast packet and multicast router socket: send up */
13435 		return (B_TRUE);
13436 	}
13437 
13438 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13439 	    ipha->ipha_protocol == IPPROTO_RSVP)
13440 		return (B_TRUE);
13441 
13442 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13443 }
13444 
13445 void
13446 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13447 {
13448 	if (IPCL_IS_NONSTR(connp)) {
13449 		(*connp->conn_upcalls->su_txq_full)
13450 		    (connp->conn_upper_handle, B_TRUE);
13451 		if (flow_stopped != NULL)
13452 			*flow_stopped = B_TRUE;
13453 	} else {
13454 		queue_t *q = connp->conn_wq;
13455 
13456 		ASSERT(q != NULL);
13457 		if (!(q->q_flag & QFULL)) {
13458 			mutex_enter(QLOCK(q));
13459 			if (!(q->q_flag & QFULL)) {
13460 				/* still need to set QFULL */
13461 				q->q_flag |= QFULL;
13462 				/* set flow_stopped to true under QLOCK */
13463 				if (flow_stopped != NULL)
13464 					*flow_stopped = B_TRUE;
13465 				mutex_exit(QLOCK(q));
13466 			} else {
13467 				/* flow_stopped is left unchanged */
13468 				mutex_exit(QLOCK(q));
13469 			}
13470 		}
13471 	}
13472 }
13473 
13474 void
13475 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13476 {
13477 	if (IPCL_IS_NONSTR(connp)) {
13478 		(*connp->conn_upcalls->su_txq_full)
13479 		    (connp->conn_upper_handle, B_FALSE);
13480 		if (flow_stopped != NULL)
13481 			*flow_stopped = B_FALSE;
13482 	} else {
13483 		queue_t *q = connp->conn_wq;
13484 
13485 		ASSERT(q != NULL);
13486 		if (q->q_flag & QFULL) {
13487 			mutex_enter(QLOCK(q));
13488 			if (q->q_flag & QFULL) {
13489 				q->q_flag &= ~QFULL;
13490 				/* set flow_stopped to false under QLOCK */
13491 				if (flow_stopped != NULL)
13492 					*flow_stopped = B_FALSE;
13493 				mutex_exit(QLOCK(q));
13494 				if (q->q_flag & QWANTW)
13495 					qbackenable(q, 0);
13496 			} else {
13497 				/* flow_stopped is left unchanged */
13498 				mutex_exit(QLOCK(q));
13499 			}
13500 		}
13501 	}
13502 
13503 	mutex_enter(&connp->conn_lock);
13504 	connp->conn_blocked = B_FALSE;
13505 	mutex_exit(&connp->conn_lock);
13506 }
13507 
13508 /*
13509  * Return the length in bytes of the IPv4 headers (base header, label, and
13510  * other IP options) that will be needed based on the
13511  * ip_pkt_t structure passed by the caller.
13512  *
13513  * The returned length does not include the length of the upper level
13514  * protocol (ULP) header.
13515  * The caller needs to check that the length doesn't exceed the max for IPv4.
13516  */
13517 int
13518 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13519 {
13520 	int len;
13521 
13522 	len = IP_SIMPLE_HDR_LENGTH;
13523 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13524 		ASSERT(ipp->ipp_label_len_v4 != 0);
13525 		/* We need to round up here */
13526 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13527 	}
13528 
13529 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13530 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13531 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13532 		len += ipp->ipp_ipv4_options_len;
13533 	}
13534 	return (len);
13535 }
13536 
13537 /*
13538  * All-purpose routine to build an IPv4 header with options based
13539  * on the abstract ip_pkt_t.
13540  *
13541  * The caller has to set the source and destination address as well as
13542  * ipha_length. The caller has to massage any source route and compensate
13543  * for the ULP pseudo-header checksum due to the source route.
13544  */
13545 void
13546 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13547     uint8_t protocol)
13548 {
13549 	ipha_t	*ipha = (ipha_t *)buf;
13550 	uint8_t *cp;
13551 
13552 	/* Initialize IPv4 header */
13553 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13554 	ipha->ipha_length = 0;	/* Caller will set later */
13555 	ipha->ipha_ident = 0;
13556 	ipha->ipha_fragment_offset_and_flags = 0;
13557 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13558 	ipha->ipha_protocol = protocol;
13559 	ipha->ipha_hdr_checksum = 0;
13560 
13561 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13562 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13563 		ipha->ipha_src = ipp->ipp_addr_v4;
13564 
13565 	cp = (uint8_t *)&ipha[1];
13566 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13567 		ASSERT(ipp->ipp_label_len_v4 != 0);
13568 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13569 		cp += ipp->ipp_label_len_v4;
13570 		/* We need to round up here */
13571 		while ((uintptr_t)cp & 0x3) {
13572 			*cp++ = IPOPT_NOP;
13573 		}
13574 	}
13575 
13576 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13577 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13578 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13579 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13580 		cp += ipp->ipp_ipv4_options_len;
13581 	}
13582 	ipha->ipha_version_and_hdr_length =
13583 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13584 
13585 	ASSERT((int)(cp - buf) == buf_len);
13586 }
13587 
13588 /* Allocate the private structure */
13589 static int
13590 ip_priv_alloc(void **bufp)
13591 {
13592 	void	*buf;
13593 
13594 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13595 		return (ENOMEM);
13596 
13597 	*bufp = buf;
13598 	return (0);
13599 }
13600 
13601 /* Function to delete the private structure */
13602 void
13603 ip_priv_free(void *buf)
13604 {
13605 	ASSERT(buf != NULL);
13606 	kmem_free(buf, sizeof (ip_priv_t));
13607 }
13608 
13609 /*
13610  * The entry point for IPPF processing.
13611  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13612  * routine just returns.
13613  *
13614  * When called, ip_process generates an ipp_packet_t structure
13615  * which holds the state information for this packet and invokes the
13616  * the classifier (via ipp_packet_process). The classification, depending on
13617  * configured filters, results in a list of actions for this packet. Invoking
13618  * an action may cause the packet to be dropped, in which case we return NULL.
13619  * proc indicates the callout position for
13620  * this packet and ill is the interface this packet arrived on or will leave
13621  * on (inbound and outbound resp.).
13622  *
13623  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13624  * on the ill corrsponding to the destination IP address.
13625  */
13626 mblk_t *
13627 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13628 {
13629 	ip_priv_t	*priv;
13630 	ipp_action_id_t	aid;
13631 	int		rc = 0;
13632 	ipp_packet_t	*pp;
13633 
13634 	/* If the classifier is not loaded, return  */
13635 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13636 		return (mp);
13637 	}
13638 
13639 	ASSERT(mp != NULL);
13640 
13641 	/* Allocate the packet structure */
13642 	rc = ipp_packet_alloc(&pp, "ip", aid);
13643 	if (rc != 0)
13644 		goto drop;
13645 
13646 	/* Allocate the private structure */
13647 	rc = ip_priv_alloc((void **)&priv);
13648 	if (rc != 0) {
13649 		ipp_packet_free(pp);
13650 		goto drop;
13651 	}
13652 	priv->proc = proc;
13653 	priv->ill_index = ill_get_upper_ifindex(rill);
13654 
13655 	ipp_packet_set_private(pp, priv, ip_priv_free);
13656 	ipp_packet_set_data(pp, mp);
13657 
13658 	/* Invoke the classifier */
13659 	rc = ipp_packet_process(&pp);
13660 	if (pp != NULL) {
13661 		mp = ipp_packet_get_data(pp);
13662 		ipp_packet_free(pp);
13663 		if (rc != 0)
13664 			goto drop;
13665 		return (mp);
13666 	} else {
13667 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13668 		mp = NULL;
13669 	}
13670 drop:
13671 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13672 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13673 		ip_drop_input("ip_process", mp, ill);
13674 	} else {
13675 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13676 		ip_drop_output("ip_process", mp, ill);
13677 	}
13678 	freemsg(mp);
13679 	return (NULL);
13680 }
13681 
13682 /*
13683  * Propagate a multicast group membership operation (add/drop) on
13684  * all the interfaces crossed by the related multirt routes.
13685  * The call is considered successful if the operation succeeds
13686  * on at least one interface.
13687  *
13688  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13689  * multicast addresses with the ire argument being the first one.
13690  * We walk the bucket to find all the of those.
13691  *
13692  * Common to IPv4 and IPv6.
13693  */
13694 static int
13695 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13696     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13697     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13698     mcast_record_t fmode, const in6_addr_t *v6src)
13699 {
13700 	ire_t		*ire_gw;
13701 	irb_t		*irb;
13702 	int		ifindex;
13703 	int		error = 0;
13704 	int		result;
13705 	ip_stack_t	*ipst = ire->ire_ipst;
13706 	ipaddr_t	group;
13707 	boolean_t	isv6;
13708 	int		match_flags;
13709 
13710 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13711 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13712 		isv6 = B_FALSE;
13713 	} else {
13714 		isv6 = B_TRUE;
13715 	}
13716 
13717 	irb = ire->ire_bucket;
13718 	ASSERT(irb != NULL);
13719 
13720 	result = 0;
13721 	irb_refhold(irb);
13722 	for (; ire != NULL; ire = ire->ire_next) {
13723 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13724 			continue;
13725 
13726 		/* We handle -ifp routes by matching on the ill if set */
13727 		match_flags = MATCH_IRE_TYPE;
13728 		if (ire->ire_ill != NULL)
13729 			match_flags |= MATCH_IRE_ILL;
13730 
13731 		if (isv6) {
13732 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13733 				continue;
13734 
13735 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13736 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13737 			    match_flags, 0, ipst, NULL);
13738 		} else {
13739 			if (ire->ire_addr != group)
13740 				continue;
13741 
13742 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13743 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13744 			    match_flags, 0, ipst, NULL);
13745 		}
13746 		/* No interface route exists for the gateway; skip this ire. */
13747 		if (ire_gw == NULL)
13748 			continue;
13749 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13750 			ire_refrele(ire_gw);
13751 			continue;
13752 		}
13753 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13754 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13755 
13756 		/*
13757 		 * The operation is considered a success if
13758 		 * it succeeds at least once on any one interface.
13759 		 */
13760 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13761 		    fmode, v6src);
13762 		if (error == 0)
13763 			result = CGTP_MCAST_SUCCESS;
13764 
13765 		ire_refrele(ire_gw);
13766 	}
13767 	irb_refrele(irb);
13768 	/*
13769 	 * Consider the call as successful if we succeeded on at least
13770 	 * one interface. Otherwise, return the last encountered error.
13771 	 */
13772 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13773 }
13774 
13775 /*
13776  * Return the expected CGTP hooks version number.
13777  */
13778 int
13779 ip_cgtp_filter_supported(void)
13780 {
13781 	return (ip_cgtp_filter_rev);
13782 }
13783 
13784 /*
13785  * CGTP hooks can be registered by invoking this function.
13786  * Checks that the version number matches.
13787  */
13788 int
13789 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13790 {
13791 	netstack_t *ns;
13792 	ip_stack_t *ipst;
13793 
13794 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13795 		return (ENOTSUP);
13796 
13797 	ns = netstack_find_by_stackid(stackid);
13798 	if (ns == NULL)
13799 		return (EINVAL);
13800 	ipst = ns->netstack_ip;
13801 	ASSERT(ipst != NULL);
13802 
13803 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13804 		netstack_rele(ns);
13805 		return (EALREADY);
13806 	}
13807 
13808 	ipst->ips_ip_cgtp_filter_ops = ops;
13809 
13810 	ill_set_inputfn_all(ipst);
13811 
13812 	netstack_rele(ns);
13813 	return (0);
13814 }
13815 
13816 /*
13817  * CGTP hooks can be unregistered by invoking this function.
13818  * Returns ENXIO if there was no registration.
13819  * Returns EBUSY if the ndd variable has not been turned off.
13820  */
13821 int
13822 ip_cgtp_filter_unregister(netstackid_t stackid)
13823 {
13824 	netstack_t *ns;
13825 	ip_stack_t *ipst;
13826 
13827 	ns = netstack_find_by_stackid(stackid);
13828 	if (ns == NULL)
13829 		return (EINVAL);
13830 	ipst = ns->netstack_ip;
13831 	ASSERT(ipst != NULL);
13832 
13833 	if (ipst->ips_ip_cgtp_filter) {
13834 		netstack_rele(ns);
13835 		return (EBUSY);
13836 	}
13837 
13838 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13839 		netstack_rele(ns);
13840 		return (ENXIO);
13841 	}
13842 	ipst->ips_ip_cgtp_filter_ops = NULL;
13843 
13844 	ill_set_inputfn_all(ipst);
13845 
13846 	netstack_rele(ns);
13847 	return (0);
13848 }
13849 
13850 /*
13851  * Check whether there is a CGTP filter registration.
13852  * Returns non-zero if there is a registration, otherwise returns zero.
13853  * Note: returns zero if bad stackid.
13854  */
13855 int
13856 ip_cgtp_filter_is_registered(netstackid_t stackid)
13857 {
13858 	netstack_t *ns;
13859 	ip_stack_t *ipst;
13860 	int ret;
13861 
13862 	ns = netstack_find_by_stackid(stackid);
13863 	if (ns == NULL)
13864 		return (0);
13865 	ipst = ns->netstack_ip;
13866 	ASSERT(ipst != NULL);
13867 
13868 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13869 		ret = 1;
13870 	else
13871 		ret = 0;
13872 
13873 	netstack_rele(ns);
13874 	return (ret);
13875 }
13876 
13877 static int
13878 ip_squeue_switch(int val)
13879 {
13880 	int rval;
13881 
13882 	switch (val) {
13883 	case IP_SQUEUE_ENTER_NODRAIN:
13884 		rval = SQ_NODRAIN;
13885 		break;
13886 	case IP_SQUEUE_ENTER:
13887 		rval = SQ_PROCESS;
13888 		break;
13889 	case IP_SQUEUE_FILL:
13890 	default:
13891 		rval = SQ_FILL;
13892 		break;
13893 	}
13894 	return (rval);
13895 }
13896 
13897 static void *
13898 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13899 {
13900 	kstat_t *ksp;
13901 
13902 	ip_stat_t template = {
13903 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
13904 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
13905 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
13906 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13907 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13908 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13909 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13910 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13911 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13912 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13913 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13914 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13915 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13916 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13917 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13918 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13919 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13920 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13921 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13922 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13923 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13924 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13925 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13926 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13927 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13928 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13929 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13930 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13931 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13932 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13933 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
13934 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
13935 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
13936 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
13937 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
13938 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
13939 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
13940 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
13941 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
13942 	};
13943 
13944 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13945 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13946 	    KSTAT_FLAG_VIRTUAL, stackid);
13947 
13948 	if (ksp == NULL)
13949 		return (NULL);
13950 
13951 	bcopy(&template, ip_statisticsp, sizeof (template));
13952 	ksp->ks_data = (void *)ip_statisticsp;
13953 	ksp->ks_private = (void *)(uintptr_t)stackid;
13954 
13955 	kstat_install(ksp);
13956 	return (ksp);
13957 }
13958 
13959 static void
13960 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13961 {
13962 	if (ksp != NULL) {
13963 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13964 		kstat_delete_netstack(ksp, stackid);
13965 	}
13966 }
13967 
13968 static void *
13969 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13970 {
13971 	kstat_t	*ksp;
13972 
13973 	ip_named_kstat_t template = {
13974 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
13975 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
13976 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
13977 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
13978 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
13979 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
13980 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
13981 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
13982 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
13983 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
13984 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
13985 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
13986 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
13987 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
13988 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
13989 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
13990 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
13991 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
13992 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
13993 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
13994 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
13995 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
13996 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
13997 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
13998 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
13999 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
14000 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
14001 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
14002 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
14003 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
14004 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
14005 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
14006 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
14007 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
14008 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
14009 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
14010 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
14011 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
14012 	};
14013 
14014 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
14015 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
14016 	if (ksp == NULL || ksp->ks_data == NULL)
14017 		return (NULL);
14018 
14019 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
14020 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
14021 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
14022 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
14023 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14024 
14025 	template.netToMediaEntrySize.value.i32 =
14026 	    sizeof (mib2_ipNetToMediaEntry_t);
14027 
14028 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14029 
14030 	bcopy(&template, ksp->ks_data, sizeof (template));
14031 	ksp->ks_update = ip_kstat_update;
14032 	ksp->ks_private = (void *)(uintptr_t)stackid;
14033 
14034 	kstat_install(ksp);
14035 	return (ksp);
14036 }
14037 
14038 static void
14039 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14040 {
14041 	if (ksp != NULL) {
14042 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14043 		kstat_delete_netstack(ksp, stackid);
14044 	}
14045 }
14046 
14047 static int
14048 ip_kstat_update(kstat_t *kp, int rw)
14049 {
14050 	ip_named_kstat_t *ipkp;
14051 	mib2_ipIfStatsEntry_t ipmib;
14052 	ill_walk_context_t ctx;
14053 	ill_t *ill;
14054 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14055 	netstack_t	*ns;
14056 	ip_stack_t	*ipst;
14057 
14058 	if (kp == NULL || kp->ks_data == NULL)
14059 		return (EIO);
14060 
14061 	if (rw == KSTAT_WRITE)
14062 		return (EACCES);
14063 
14064 	ns = netstack_find_by_stackid(stackid);
14065 	if (ns == NULL)
14066 		return (-1);
14067 	ipst = ns->netstack_ip;
14068 	if (ipst == NULL) {
14069 		netstack_rele(ns);
14070 		return (-1);
14071 	}
14072 	ipkp = (ip_named_kstat_t *)kp->ks_data;
14073 
14074 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14075 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14076 	ill = ILL_START_WALK_V4(&ctx, ipst);
14077 	for (; ill != NULL; ill = ill_next(&ctx, ill))
14078 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14079 	rw_exit(&ipst->ips_ill_g_lock);
14080 
14081 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
14082 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
14083 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
14084 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
14085 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
14086 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14087 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
14088 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
14089 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
14090 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
14091 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
14092 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
14093 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
14094 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
14095 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
14096 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
14097 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
14098 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
14099 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
14100 
14101 	ipkp->routingDiscards.value.ui32 =	0;
14102 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
14103 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
14104 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
14105 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
14106 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
14107 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
14108 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
14109 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
14110 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
14111 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
14112 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
14113 
14114 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
14115 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
14116 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14117 
14118 	netstack_rele(ns);
14119 
14120 	return (0);
14121 }
14122 
14123 static void *
14124 icmp_kstat_init(netstackid_t stackid)
14125 {
14126 	kstat_t	*ksp;
14127 
14128 	icmp_named_kstat_t template = {
14129 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14130 		{ "inErrors",		KSTAT_DATA_UINT32 },
14131 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14132 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14133 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14134 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14135 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14136 		{ "inEchos",		KSTAT_DATA_UINT32 },
14137 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14138 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14139 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14140 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14141 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14142 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14143 		{ "outErrors",		KSTAT_DATA_UINT32 },
14144 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14145 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14146 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14147 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14148 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14149 		{ "outEchos",		KSTAT_DATA_UINT32 },
14150 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14151 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14152 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14153 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14154 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14155 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14156 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14157 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14158 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14159 		{ "outDrops",		KSTAT_DATA_UINT32 },
14160 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14161 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14162 	};
14163 
14164 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14165 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14166 	if (ksp == NULL || ksp->ks_data == NULL)
14167 		return (NULL);
14168 
14169 	bcopy(&template, ksp->ks_data, sizeof (template));
14170 
14171 	ksp->ks_update = icmp_kstat_update;
14172 	ksp->ks_private = (void *)(uintptr_t)stackid;
14173 
14174 	kstat_install(ksp);
14175 	return (ksp);
14176 }
14177 
14178 static void
14179 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14180 {
14181 	if (ksp != NULL) {
14182 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14183 		kstat_delete_netstack(ksp, stackid);
14184 	}
14185 }
14186 
14187 static int
14188 icmp_kstat_update(kstat_t *kp, int rw)
14189 {
14190 	icmp_named_kstat_t *icmpkp;
14191 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14192 	netstack_t	*ns;
14193 	ip_stack_t	*ipst;
14194 
14195 	if ((kp == NULL) || (kp->ks_data == NULL))
14196 		return (EIO);
14197 
14198 	if (rw == KSTAT_WRITE)
14199 		return (EACCES);
14200 
14201 	ns = netstack_find_by_stackid(stackid);
14202 	if (ns == NULL)
14203 		return (-1);
14204 	ipst = ns->netstack_ip;
14205 	if (ipst == NULL) {
14206 		netstack_rele(ns);
14207 		return (-1);
14208 	}
14209 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14210 
14211 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14212 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14213 	icmpkp->inDestUnreachs.value.ui32 =
14214 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14215 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14216 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14217 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14218 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14219 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14220 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14221 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14222 	icmpkp->inTimestampReps.value.ui32 =
14223 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14224 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14225 	icmpkp->inAddrMaskReps.value.ui32 =
14226 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14227 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14228 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14229 	icmpkp->outDestUnreachs.value.ui32 =
14230 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14231 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14232 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14233 	icmpkp->outSrcQuenchs.value.ui32 =
14234 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14235 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14236 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14237 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14238 	icmpkp->outTimestamps.value.ui32 =
14239 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14240 	icmpkp->outTimestampReps.value.ui32 =
14241 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14242 	icmpkp->outAddrMasks.value.ui32 =
14243 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14244 	icmpkp->outAddrMaskReps.value.ui32 =
14245 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14246 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14247 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14248 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14249 	icmpkp->outFragNeeded.value.ui32 =
14250 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14251 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14252 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14253 	icmpkp->inBadRedirects.value.ui32 =
14254 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14255 
14256 	netstack_rele(ns);
14257 	return (0);
14258 }
14259 
14260 /*
14261  * This is the fanout function for raw socket opened for SCTP.  Note
14262  * that it is called after SCTP checks that there is no socket which
14263  * wants a packet.  Then before SCTP handles this out of the blue packet,
14264  * this function is called to see if there is any raw socket for SCTP.
14265  * If there is and it is bound to the correct address, the packet will
14266  * be sent to that socket.  Note that only one raw socket can be bound to
14267  * a port.  This is assured in ipcl_sctp_hash_insert();
14268  */
14269 void
14270 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14271     ip_recv_attr_t *ira)
14272 {
14273 	conn_t		*connp;
14274 	queue_t		*rq;
14275 	boolean_t	secure;
14276 	ill_t		*ill = ira->ira_ill;
14277 	ip_stack_t	*ipst = ill->ill_ipst;
14278 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14279 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14280 	iaflags_t	iraflags = ira->ira_flags;
14281 	ill_t		*rill = ira->ira_rill;
14282 
14283 	secure = iraflags & IRAF_IPSEC_SECURE;
14284 
14285 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14286 	    ira, ipst);
14287 	if (connp == NULL) {
14288 		/*
14289 		 * Although raw sctp is not summed, OOB chunks must be.
14290 		 * Drop the packet here if the sctp checksum failed.
14291 		 */
14292 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14293 			SCTPS_BUMP_MIB(sctps, sctpChecksumError);
14294 			freemsg(mp);
14295 			return;
14296 		}
14297 		ira->ira_ill = ira->ira_rill = NULL;
14298 		sctp_ootb_input(mp, ira, ipst);
14299 		ira->ira_ill = ill;
14300 		ira->ira_rill = rill;
14301 		return;
14302 	}
14303 	rq = connp->conn_rq;
14304 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14305 		CONN_DEC_REF(connp);
14306 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14307 		freemsg(mp);
14308 		return;
14309 	}
14310 	if (((iraflags & IRAF_IS_IPV4) ?
14311 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14312 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14313 	    secure) {
14314 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14315 		    ip6h, ira);
14316 		if (mp == NULL) {
14317 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14318 			/* Note that mp is NULL */
14319 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14320 			CONN_DEC_REF(connp);
14321 			return;
14322 		}
14323 	}
14324 
14325 	if (iraflags & IRAF_ICMP_ERROR) {
14326 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14327 	} else {
14328 		ill_t *rill = ira->ira_rill;
14329 
14330 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14331 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14332 		ira->ira_ill = ira->ira_rill = NULL;
14333 		(connp->conn_recv)(connp, mp, NULL, ira);
14334 		ira->ira_ill = ill;
14335 		ira->ira_rill = rill;
14336 	}
14337 	CONN_DEC_REF(connp);
14338 }
14339 
14340 /*
14341  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14342  * header before the ip payload.
14343  */
14344 static void
14345 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14346 {
14347 	int len = (mp->b_wptr - mp->b_rptr);
14348 	mblk_t *ip_mp;
14349 
14350 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14351 	if (is_fp_mp || len != fp_mp_len) {
14352 		if (len > fp_mp_len) {
14353 			/*
14354 			 * fastpath header and ip header in the first mblk
14355 			 */
14356 			mp->b_rptr += fp_mp_len;
14357 		} else {
14358 			/*
14359 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14360 			 * attach the fastpath header before ip header.
14361 			 */
14362 			ip_mp = mp->b_cont;
14363 			freeb(mp);
14364 			mp = ip_mp;
14365 			mp->b_rptr += (fp_mp_len - len);
14366 		}
14367 	} else {
14368 		ip_mp = mp->b_cont;
14369 		freeb(mp);
14370 		mp = ip_mp;
14371 	}
14372 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14373 	freemsg(mp);
14374 }
14375 
14376 /*
14377  * Normal post fragmentation function.
14378  *
14379  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14380  * using the same state machine.
14381  *
14382  * We return an error on failure. In particular we return EWOULDBLOCK
14383  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14384  * (currently by canputnext failure resulting in backenabling from GLD.)
14385  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14386  * indication that they can flow control until ip_wsrv() tells then to restart.
14387  *
14388  * If the nce passed by caller is incomplete, this function
14389  * queues the packet and if necessary, sends ARP request and bails.
14390  * If the Neighbor Cache passed is fully resolved, we simply prepend
14391  * the link-layer header to the packet, do ipsec hw acceleration
14392  * work if necessary, and send the packet out on the wire.
14393  */
14394 /* ARGSUSED6 */
14395 int
14396 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14397     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14398 {
14399 	queue_t		*wq;
14400 	ill_t		*ill = nce->nce_ill;
14401 	ip_stack_t	*ipst = ill->ill_ipst;
14402 	uint64_t	delta;
14403 	boolean_t	isv6 = ill->ill_isv6;
14404 	boolean_t	fp_mp;
14405 	ncec_t		*ncec = nce->nce_common;
14406 	int64_t		now = LBOLT_FASTPATH64;
14407 	boolean_t	is_probe;
14408 
14409 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14410 
14411 	ASSERT(mp != NULL);
14412 	ASSERT(mp->b_datap->db_type == M_DATA);
14413 	ASSERT(pkt_len == msgdsize(mp));
14414 
14415 	/*
14416 	 * If we have already been here and are coming back after ARP/ND.
14417 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14418 	 * in that case since they have seen the packet when it came here
14419 	 * the first time.
14420 	 */
14421 	if (ixaflags & IXAF_NO_TRACE)
14422 		goto sendit;
14423 
14424 	if (ixaflags & IXAF_IS_IPV4) {
14425 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14426 
14427 		ASSERT(!isv6);
14428 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14429 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14430 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14431 			int	error;
14432 
14433 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14434 			    ipst->ips_ipv4firewall_physical_out,
14435 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14436 			DTRACE_PROBE1(ip4__physical__out__end,
14437 			    mblk_t *, mp);
14438 			if (mp == NULL)
14439 				return (error);
14440 
14441 			/* The length could have changed */
14442 			pkt_len = msgdsize(mp);
14443 		}
14444 		if (ipst->ips_ip4_observe.he_interested) {
14445 			/*
14446 			 * Note that for TX the zoneid is the sending
14447 			 * zone, whether or not MLP is in play.
14448 			 * Since the szone argument is the IP zoneid (i.e.,
14449 			 * zero for exclusive-IP zones) and ipobs wants
14450 			 * the system zoneid, we map it here.
14451 			 */
14452 			szone = IP_REAL_ZONEID(szone, ipst);
14453 
14454 			/*
14455 			 * On the outbound path the destination zone will be
14456 			 * unknown as we're sending this packet out on the
14457 			 * wire.
14458 			 */
14459 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14460 			    ill, ipst);
14461 		}
14462 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14463 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14464 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14465 	} else {
14466 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14467 
14468 		ASSERT(isv6);
14469 		ASSERT(pkt_len ==
14470 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14471 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14472 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14473 			int	error;
14474 
14475 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14476 			    ipst->ips_ipv6firewall_physical_out,
14477 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14478 			DTRACE_PROBE1(ip6__physical__out__end,
14479 			    mblk_t *, mp);
14480 			if (mp == NULL)
14481 				return (error);
14482 
14483 			/* The length could have changed */
14484 			pkt_len = msgdsize(mp);
14485 		}
14486 		if (ipst->ips_ip6_observe.he_interested) {
14487 			/* See above */
14488 			szone = IP_REAL_ZONEID(szone, ipst);
14489 
14490 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14491 			    ill, ipst);
14492 		}
14493 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14494 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14495 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14496 	}
14497 
14498 sendit:
14499 	/*
14500 	 * We check the state without a lock because the state can never
14501 	 * move "backwards" to initial or incomplete.
14502 	 */
14503 	switch (ncec->ncec_state) {
14504 	case ND_REACHABLE:
14505 	case ND_STALE:
14506 	case ND_DELAY:
14507 	case ND_PROBE:
14508 		mp = ip_xmit_attach_llhdr(mp, nce);
14509 		if (mp == NULL) {
14510 			/*
14511 			 * ip_xmit_attach_llhdr has increased
14512 			 * ipIfStatsOutDiscards and called ip_drop_output()
14513 			 */
14514 			return (ENOBUFS);
14515 		}
14516 		/*
14517 		 * check if nce_fastpath completed and we tagged on a
14518 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14519 		 */
14520 		fp_mp = (mp->b_datap->db_type == M_DATA);
14521 
14522 		if (fp_mp &&
14523 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14524 			ill_dld_direct_t *idd;
14525 
14526 			idd = &ill->ill_dld_capab->idc_direct;
14527 			/*
14528 			 * Send the packet directly to DLD, where it
14529 			 * may be queued depending on the availability
14530 			 * of transmit resources at the media layer.
14531 			 * Return value should be taken into
14532 			 * account and flow control the TCP.
14533 			 */
14534 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14535 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14536 			    pkt_len);
14537 
14538 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14539 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14540 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14541 			} else {
14542 				uintptr_t cookie;
14543 
14544 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14545 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14546 					if (ixacookie != NULL)
14547 						*ixacookie = cookie;
14548 					return (EWOULDBLOCK);
14549 				}
14550 			}
14551 		} else {
14552 			wq = ill->ill_wq;
14553 
14554 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14555 			    !canputnext(wq)) {
14556 				if (ixacookie != NULL)
14557 					*ixacookie = 0;
14558 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14559 				    nce->nce_fp_mp != NULL ?
14560 				    MBLKL(nce->nce_fp_mp) : 0);
14561 				return (EWOULDBLOCK);
14562 			}
14563 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14564 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14565 			    pkt_len);
14566 			putnext(wq, mp);
14567 		}
14568 
14569 		/*
14570 		 * The rest of this function implements Neighbor Unreachability
14571 		 * detection. Determine if the ncec is eligible for NUD.
14572 		 */
14573 		if (ncec->ncec_flags & NCE_F_NONUD)
14574 			return (0);
14575 
14576 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14577 
14578 		/*
14579 		 * Check for upper layer advice
14580 		 */
14581 		if (ixaflags & IXAF_REACH_CONF) {
14582 			timeout_id_t tid;
14583 
14584 			/*
14585 			 * It should be o.k. to check the state without
14586 			 * a lock here, at most we lose an advice.
14587 			 */
14588 			ncec->ncec_last = TICK_TO_MSEC(now);
14589 			if (ncec->ncec_state != ND_REACHABLE) {
14590 				mutex_enter(&ncec->ncec_lock);
14591 				ncec->ncec_state = ND_REACHABLE;
14592 				tid = ncec->ncec_timeout_id;
14593 				ncec->ncec_timeout_id = 0;
14594 				mutex_exit(&ncec->ncec_lock);
14595 				(void) untimeout(tid);
14596 				if (ip_debug > 2) {
14597 					/* ip1dbg */
14598 					pr_addr_dbg("ip_xmit: state"
14599 					    " for %s changed to"
14600 					    " REACHABLE\n", AF_INET6,
14601 					    &ncec->ncec_addr);
14602 				}
14603 			}
14604 			return (0);
14605 		}
14606 
14607 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14608 		ip1dbg(("ip_xmit: delta = %" PRId64
14609 		    " ill_reachable_time = %d \n", delta,
14610 		    ill->ill_reachable_time));
14611 		if (delta > (uint64_t)ill->ill_reachable_time) {
14612 			mutex_enter(&ncec->ncec_lock);
14613 			switch (ncec->ncec_state) {
14614 			case ND_REACHABLE:
14615 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14616 				/* FALLTHROUGH */
14617 			case ND_STALE:
14618 				/*
14619 				 * ND_REACHABLE is identical to
14620 				 * ND_STALE in this specific case. If
14621 				 * reachable time has expired for this
14622 				 * neighbor (delta is greater than
14623 				 * reachable time), conceptually, the
14624 				 * neighbor cache is no longer in
14625 				 * REACHABLE state, but already in
14626 				 * STALE state.  So the correct
14627 				 * transition here is to ND_DELAY.
14628 				 */
14629 				ncec->ncec_state = ND_DELAY;
14630 				mutex_exit(&ncec->ncec_lock);
14631 				nce_restart_timer(ncec,
14632 				    ipst->ips_delay_first_probe_time);
14633 				if (ip_debug > 3) {
14634 					/* ip2dbg */
14635 					pr_addr_dbg("ip_xmit: state"
14636 					    " for %s changed to"
14637 					    " DELAY\n", AF_INET6,
14638 					    &ncec->ncec_addr);
14639 				}
14640 				break;
14641 			case ND_DELAY:
14642 			case ND_PROBE:
14643 				mutex_exit(&ncec->ncec_lock);
14644 				/* Timers have already started */
14645 				break;
14646 			case ND_UNREACHABLE:
14647 				/*
14648 				 * nce_timer has detected that this ncec
14649 				 * is unreachable and initiated deleting
14650 				 * this ncec.
14651 				 * This is a harmless race where we found the
14652 				 * ncec before it was deleted and have
14653 				 * just sent out a packet using this
14654 				 * unreachable ncec.
14655 				 */
14656 				mutex_exit(&ncec->ncec_lock);
14657 				break;
14658 			default:
14659 				ASSERT(0);
14660 				mutex_exit(&ncec->ncec_lock);
14661 			}
14662 		}
14663 		return (0);
14664 
14665 	case ND_INCOMPLETE:
14666 		/*
14667 		 * the state could have changed since we didn't hold the lock.
14668 		 * Re-verify state under lock.
14669 		 */
14670 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14671 		mutex_enter(&ncec->ncec_lock);
14672 		if (NCE_ISREACHABLE(ncec)) {
14673 			mutex_exit(&ncec->ncec_lock);
14674 			goto sendit;
14675 		}
14676 		/* queue the packet */
14677 		nce_queue_mp(ncec, mp, is_probe);
14678 		mutex_exit(&ncec->ncec_lock);
14679 		DTRACE_PROBE2(ip__xmit__incomplete,
14680 		    (ncec_t *), ncec, (mblk_t *), mp);
14681 		return (0);
14682 
14683 	case ND_INITIAL:
14684 		/*
14685 		 * State could have changed since we didn't hold the lock, so
14686 		 * re-verify state.
14687 		 */
14688 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14689 		mutex_enter(&ncec->ncec_lock);
14690 		if (NCE_ISREACHABLE(ncec))  {
14691 			mutex_exit(&ncec->ncec_lock);
14692 			goto sendit;
14693 		}
14694 		nce_queue_mp(ncec, mp, is_probe);
14695 		if (ncec->ncec_state == ND_INITIAL) {
14696 			ncec->ncec_state = ND_INCOMPLETE;
14697 			mutex_exit(&ncec->ncec_lock);
14698 			/*
14699 			 * figure out the source we want to use
14700 			 * and resolve it.
14701 			 */
14702 			ip_ndp_resolve(ncec);
14703 		} else  {
14704 			mutex_exit(&ncec->ncec_lock);
14705 		}
14706 		return (0);
14707 
14708 	case ND_UNREACHABLE:
14709 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14710 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14711 		    mp, ill);
14712 		freemsg(mp);
14713 		return (0);
14714 
14715 	default:
14716 		ASSERT(0);
14717 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14718 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14719 		    mp, ill);
14720 		freemsg(mp);
14721 		return (ENETUNREACH);
14722 	}
14723 }
14724 
14725 /*
14726  * Return B_TRUE if the buffers differ in length or content.
14727  * This is used for comparing extension header buffers.
14728  * Note that an extension header would be declared different
14729  * even if all that changed was the next header value in that header i.e.
14730  * what really changed is the next extension header.
14731  */
14732 boolean_t
14733 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14734     uint_t blen)
14735 {
14736 	if (!b_valid)
14737 		blen = 0;
14738 
14739 	if (alen != blen)
14740 		return (B_TRUE);
14741 	if (alen == 0)
14742 		return (B_FALSE);	/* Both zero length */
14743 	return (bcmp(abuf, bbuf, alen));
14744 }
14745 
14746 /*
14747  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14748  * Return B_FALSE if memory allocation fails - don't change any state!
14749  */
14750 boolean_t
14751 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14752     const void *src, uint_t srclen)
14753 {
14754 	void *dst;
14755 
14756 	if (!src_valid)
14757 		srclen = 0;
14758 
14759 	ASSERT(*dstlenp == 0);
14760 	if (src != NULL && srclen != 0) {
14761 		dst = mi_alloc(srclen, BPRI_MED);
14762 		if (dst == NULL)
14763 			return (B_FALSE);
14764 	} else {
14765 		dst = NULL;
14766 	}
14767 	if (*dstp != NULL)
14768 		mi_free(*dstp);
14769 	*dstp = dst;
14770 	*dstlenp = dst == NULL ? 0 : srclen;
14771 	return (B_TRUE);
14772 }
14773 
14774 /*
14775  * Replace what is in *dst, *dstlen with the source.
14776  * Assumes ip_allocbuf has already been called.
14777  */
14778 void
14779 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14780     const void *src, uint_t srclen)
14781 {
14782 	if (!src_valid)
14783 		srclen = 0;
14784 
14785 	ASSERT(*dstlenp == srclen);
14786 	if (src != NULL && srclen != 0)
14787 		bcopy(src, *dstp, srclen);
14788 }
14789 
14790 /*
14791  * Free the storage pointed to by the members of an ip_pkt_t.
14792  */
14793 void
14794 ip_pkt_free(ip_pkt_t *ipp)
14795 {
14796 	uint_t	fields = ipp->ipp_fields;
14797 
14798 	if (fields & IPPF_HOPOPTS) {
14799 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14800 		ipp->ipp_hopopts = NULL;
14801 		ipp->ipp_hopoptslen = 0;
14802 	}
14803 	if (fields & IPPF_RTHDRDSTOPTS) {
14804 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14805 		ipp->ipp_rthdrdstopts = NULL;
14806 		ipp->ipp_rthdrdstoptslen = 0;
14807 	}
14808 	if (fields & IPPF_DSTOPTS) {
14809 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14810 		ipp->ipp_dstopts = NULL;
14811 		ipp->ipp_dstoptslen = 0;
14812 	}
14813 	if (fields & IPPF_RTHDR) {
14814 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14815 		ipp->ipp_rthdr = NULL;
14816 		ipp->ipp_rthdrlen = 0;
14817 	}
14818 	if (fields & IPPF_IPV4_OPTIONS) {
14819 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14820 		ipp->ipp_ipv4_options = NULL;
14821 		ipp->ipp_ipv4_options_len = 0;
14822 	}
14823 	if (fields & IPPF_LABEL_V4) {
14824 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14825 		ipp->ipp_label_v4 = NULL;
14826 		ipp->ipp_label_len_v4 = 0;
14827 	}
14828 	if (fields & IPPF_LABEL_V6) {
14829 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14830 		ipp->ipp_label_v6 = NULL;
14831 		ipp->ipp_label_len_v6 = 0;
14832 	}
14833 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14834 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14835 }
14836 
14837 /*
14838  * Copy from src to dst and allocate as needed.
14839  * Returns zero or ENOMEM.
14840  *
14841  * The caller must initialize dst to zero.
14842  */
14843 int
14844 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14845 {
14846 	uint_t	fields = src->ipp_fields;
14847 
14848 	/* Start with fields that don't require memory allocation */
14849 	dst->ipp_fields = fields &
14850 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14851 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14852 
14853 	dst->ipp_addr = src->ipp_addr;
14854 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14855 	dst->ipp_hoplimit = src->ipp_hoplimit;
14856 	dst->ipp_tclass = src->ipp_tclass;
14857 	dst->ipp_type_of_service = src->ipp_type_of_service;
14858 
14859 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14860 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14861 		return (0);
14862 
14863 	if (fields & IPPF_HOPOPTS) {
14864 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14865 		if (dst->ipp_hopopts == NULL) {
14866 			ip_pkt_free(dst);
14867 			return (ENOMEM);
14868 		}
14869 		dst->ipp_fields |= IPPF_HOPOPTS;
14870 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14871 		    src->ipp_hopoptslen);
14872 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14873 	}
14874 	if (fields & IPPF_RTHDRDSTOPTS) {
14875 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14876 		    kmflag);
14877 		if (dst->ipp_rthdrdstopts == NULL) {
14878 			ip_pkt_free(dst);
14879 			return (ENOMEM);
14880 		}
14881 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14882 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14883 		    src->ipp_rthdrdstoptslen);
14884 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14885 	}
14886 	if (fields & IPPF_DSTOPTS) {
14887 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14888 		if (dst->ipp_dstopts == NULL) {
14889 			ip_pkt_free(dst);
14890 			return (ENOMEM);
14891 		}
14892 		dst->ipp_fields |= IPPF_DSTOPTS;
14893 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14894 		    src->ipp_dstoptslen);
14895 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14896 	}
14897 	if (fields & IPPF_RTHDR) {
14898 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14899 		if (dst->ipp_rthdr == NULL) {
14900 			ip_pkt_free(dst);
14901 			return (ENOMEM);
14902 		}
14903 		dst->ipp_fields |= IPPF_RTHDR;
14904 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14905 		    src->ipp_rthdrlen);
14906 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14907 	}
14908 	if (fields & IPPF_IPV4_OPTIONS) {
14909 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14910 		    kmflag);
14911 		if (dst->ipp_ipv4_options == NULL) {
14912 			ip_pkt_free(dst);
14913 			return (ENOMEM);
14914 		}
14915 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14916 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14917 		    src->ipp_ipv4_options_len);
14918 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14919 	}
14920 	if (fields & IPPF_LABEL_V4) {
14921 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14922 		if (dst->ipp_label_v4 == NULL) {
14923 			ip_pkt_free(dst);
14924 			return (ENOMEM);
14925 		}
14926 		dst->ipp_fields |= IPPF_LABEL_V4;
14927 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14928 		    src->ipp_label_len_v4);
14929 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14930 	}
14931 	if (fields & IPPF_LABEL_V6) {
14932 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14933 		if (dst->ipp_label_v6 == NULL) {
14934 			ip_pkt_free(dst);
14935 			return (ENOMEM);
14936 		}
14937 		dst->ipp_fields |= IPPF_LABEL_V6;
14938 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14939 		    src->ipp_label_len_v6);
14940 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14941 	}
14942 	if (fields & IPPF_FRAGHDR) {
14943 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14944 		if (dst->ipp_fraghdr == NULL) {
14945 			ip_pkt_free(dst);
14946 			return (ENOMEM);
14947 		}
14948 		dst->ipp_fields |= IPPF_FRAGHDR;
14949 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14950 		    src->ipp_fraghdrlen);
14951 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14952 	}
14953 	return (0);
14954 }
14955 
14956 /*
14957  * Returns INADDR_ANY if no source route
14958  */
14959 ipaddr_t
14960 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14961 {
14962 	ipaddr_t	nexthop = INADDR_ANY;
14963 	ipoptp_t	opts;
14964 	uchar_t		*opt;
14965 	uint8_t		optval;
14966 	uint8_t		optlen;
14967 	uint32_t	totallen;
14968 
14969 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14970 		return (INADDR_ANY);
14971 
14972 	totallen = ipp->ipp_ipv4_options_len;
14973 	if (totallen & 0x3)
14974 		return (INADDR_ANY);
14975 
14976 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14977 	    optval != IPOPT_EOL;
14978 	    optval = ipoptp_next(&opts)) {
14979 		opt = opts.ipoptp_cur;
14980 		switch (optval) {
14981 			uint8_t off;
14982 		case IPOPT_SSRR:
14983 		case IPOPT_LSRR:
14984 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14985 				break;
14986 			}
14987 			optlen = opts.ipoptp_len;
14988 			off = opt[IPOPT_OFFSET];
14989 			off--;
14990 			if (optlen < IP_ADDR_LEN ||
14991 			    off > optlen - IP_ADDR_LEN) {
14992 				/* End of source route */
14993 				break;
14994 			}
14995 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
14996 			if (nexthop == htonl(INADDR_LOOPBACK)) {
14997 				/* Ignore */
14998 				nexthop = INADDR_ANY;
14999 				break;
15000 			}
15001 			break;
15002 		}
15003 	}
15004 	return (nexthop);
15005 }
15006 
15007 /*
15008  * Reverse a source route.
15009  */
15010 void
15011 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
15012 {
15013 	ipaddr_t	tmp;
15014 	ipoptp_t	opts;
15015 	uchar_t		*opt;
15016 	uint8_t		optval;
15017 	uint32_t	totallen;
15018 
15019 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15020 		return;
15021 
15022 	totallen = ipp->ipp_ipv4_options_len;
15023 	if (totallen & 0x3)
15024 		return;
15025 
15026 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15027 	    optval != IPOPT_EOL;
15028 	    optval = ipoptp_next(&opts)) {
15029 		uint8_t off1, off2;
15030 
15031 		opt = opts.ipoptp_cur;
15032 		switch (optval) {
15033 		case IPOPT_SSRR:
15034 		case IPOPT_LSRR:
15035 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15036 				break;
15037 			}
15038 			off1 = IPOPT_MINOFF_SR - 1;
15039 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15040 			while (off2 > off1) {
15041 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15042 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15043 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15044 				off2 -= IP_ADDR_LEN;
15045 				off1 += IP_ADDR_LEN;
15046 			}
15047 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15048 			break;
15049 		}
15050 	}
15051 }
15052 
15053 /*
15054  * Returns NULL if no routing header
15055  */
15056 in6_addr_t *
15057 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15058 {
15059 	in6_addr_t	*nexthop = NULL;
15060 	ip6_rthdr0_t	*rthdr;
15061 
15062 	if (!(ipp->ipp_fields & IPPF_RTHDR))
15063 		return (NULL);
15064 
15065 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15066 	if (rthdr->ip6r0_segleft == 0)
15067 		return (NULL);
15068 
15069 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15070 	return (nexthop);
15071 }
15072 
15073 zoneid_t
15074 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15075     zoneid_t lookup_zoneid)
15076 {
15077 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15078 	ire_t		*ire;
15079 	int		ire_flags = MATCH_IRE_TYPE;
15080 	zoneid_t	zoneid = ALL_ZONES;
15081 
15082 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15083 		return (ALL_ZONES);
15084 
15085 	if (lookup_zoneid != ALL_ZONES)
15086 		ire_flags |= MATCH_IRE_ZONEONLY;
15087 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15088 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15089 	if (ire != NULL) {
15090 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15091 		ire_refrele(ire);
15092 	}
15093 	return (zoneid);
15094 }
15095 
15096 zoneid_t
15097 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15098     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15099 {
15100 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15101 	ire_t		*ire;
15102 	int		ire_flags = MATCH_IRE_TYPE;
15103 	zoneid_t	zoneid = ALL_ZONES;
15104 
15105 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15106 		return (ALL_ZONES);
15107 
15108 	if (IN6_IS_ADDR_LINKLOCAL(addr))
15109 		ire_flags |= MATCH_IRE_ILL;
15110 
15111 	if (lookup_zoneid != ALL_ZONES)
15112 		ire_flags |= MATCH_IRE_ZONEONLY;
15113 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15114 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15115 	if (ire != NULL) {
15116 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15117 		ire_refrele(ire);
15118 	}
15119 	return (zoneid);
15120 }
15121 
15122 /*
15123  * IP obserability hook support functions.
15124  */
15125 static void
15126 ipobs_init(ip_stack_t *ipst)
15127 {
15128 	netid_t id;
15129 
15130 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15131 
15132 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15133 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15134 
15135 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15136 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15137 }
15138 
15139 static void
15140 ipobs_fini(ip_stack_t *ipst)
15141 {
15142 
15143 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15144 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15145 }
15146 
15147 /*
15148  * hook_pkt_observe_t is composed in network byte order so that the
15149  * entire mblk_t chain handed into hook_run can be used as-is.
15150  * The caveat is that use of the fields, such as the zone fields,
15151  * requires conversion into host byte order first.
15152  */
15153 void
15154 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15155     const ill_t *ill, ip_stack_t *ipst)
15156 {
15157 	hook_pkt_observe_t *hdr;
15158 	uint64_t grifindex;
15159 	mblk_t *imp;
15160 
15161 	imp = allocb(sizeof (*hdr), BPRI_HI);
15162 	if (imp == NULL)
15163 		return;
15164 
15165 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15166 	/*
15167 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15168 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15169 	 */
15170 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15171 	imp->b_cont = mp;
15172 
15173 	ASSERT(DB_TYPE(mp) == M_DATA);
15174 
15175 	if (IS_UNDER_IPMP(ill))
15176 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15177 	else
15178 		grifindex = 0;
15179 
15180 	hdr->hpo_version = 1;
15181 	hdr->hpo_htype = htons(htype);
15182 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15183 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15184 	hdr->hpo_grifindex = htonl(grifindex);
15185 	hdr->hpo_zsrc = htonl(zsrc);
15186 	hdr->hpo_zdst = htonl(zdst);
15187 	hdr->hpo_pkt = imp;
15188 	hdr->hpo_ctx = ipst->ips_netstack;
15189 
15190 	if (ill->ill_isv6) {
15191 		hdr->hpo_family = AF_INET6;
15192 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15193 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15194 	} else {
15195 		hdr->hpo_family = AF_INET;
15196 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15197 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15198 	}
15199 
15200 	imp->b_cont = NULL;
15201 	freemsg(imp);
15202 }
15203 
15204 /*
15205  * Utility routine that checks if `v4srcp' is a valid address on underlying
15206  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15207  * associated with `v4srcp' on success.  NOTE: if this is not called from
15208  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15209  * group during or after this lookup.
15210  */
15211 boolean_t
15212 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15213 {
15214 	ipif_t *ipif;
15215 
15216 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15217 	if (ipif != NULL) {
15218 		if (ipifp != NULL)
15219 			*ipifp = ipif;
15220 		else
15221 			ipif_refrele(ipif);
15222 		return (B_TRUE);
15223 	}
15224 
15225 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15226 	    *v4srcp));
15227 	return (B_FALSE);
15228 }
15229 
15230 /*
15231  * Transport protocol call back function for CPU state change.
15232  */
15233 /* ARGSUSED */
15234 static int
15235 ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
15236 {
15237 	processorid_t cpu_seqid;
15238 	netstack_handle_t nh;
15239 	netstack_t *ns;
15240 
15241 	ASSERT(MUTEX_HELD(&cpu_lock));
15242 
15243 	switch (what) {
15244 	case CPU_CONFIG:
15245 	case CPU_ON:
15246 	case CPU_INIT:
15247 	case CPU_CPUPART_IN:
15248 		cpu_seqid = cpu[id]->cpu_seqid;
15249 		netstack_next_init(&nh);
15250 		while ((ns = netstack_next(&nh)) != NULL) {
15251 			tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
15252 			sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
15253 			udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
15254 			netstack_rele(ns);
15255 		}
15256 		netstack_next_fini(&nh);
15257 		break;
15258 	case CPU_UNCONFIG:
15259 	case CPU_OFF:
15260 	case CPU_CPUPART_OUT:
15261 		/*
15262 		 * Nothing to do.  We don't remove the per CPU stats from
15263 		 * the IP stack even when the CPU goes offline.
15264 		 */
15265 		break;
15266 	default:
15267 		break;
15268 	}
15269 	return (0);
15270 }
15271