xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision a23420cf95f05ac67f2c299116a3225581e519d1)
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 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/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);
676 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
677 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
678 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
679 		    ip_stack_t *);
680 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
681 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
686 		    ip_stack_t *ipst);
687 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
688 		    ip_stack_t *ipst);
689 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst);
691 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
698 		    ip_stack_t *ipst);
699 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
700 		    ip_stack_t *ipst);
701 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
702 		    ip_stack_t *ipst);
703 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
704 		    ip_stack_t *ipst);
705 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
706 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
707 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
708 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
709 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
710 
711 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
712 		    mblk_t *);
713 
714 static void	conn_drain_init(ip_stack_t *);
715 static void	conn_drain_fini(ip_stack_t *);
716 static void	conn_drain(conn_t *connp, boolean_t closing);
717 
718 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
719 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
720 
721 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
722 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
723 static void	ip_stack_fini(netstackid_t stackid, void *arg);
724 
725 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
726     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
727     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
728     const in6_addr_t *);
729 
730 static int	ip_squeue_switch(int);
731 
732 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
733 static void	ip_kstat_fini(netstackid_t, kstat_t *);
734 static int	ip_kstat_update(kstat_t *kp, int rw);
735 static void	*icmp_kstat_init(netstackid_t);
736 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
737 static int	icmp_kstat_update(kstat_t *kp, int rw);
738 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
739 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
740 
741 static void	ipobs_init(ip_stack_t *);
742 static void	ipobs_fini(ip_stack_t *);
743 
744 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
745 
746 static long ip_rput_pullups;
747 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
748 
749 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
750 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
751 
752 int	ip_debug;
753 
754 /*
755  * Multirouting/CGTP stuff
756  */
757 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
758 
759 /*
760  * IP tunables related declarations. Definitions are in ip_tunables.c
761  */
762 extern mod_prop_info_t ip_propinfo_tbl[];
763 extern int ip_propinfo_count;
764 
765 /*
766  * Table of IP ioctls encoding the various properties of the ioctl and
767  * indexed based on the last byte of the ioctl command. Occasionally there
768  * is a clash, and there is more than 1 ioctl with the same last byte.
769  * In such a case 1 ioctl is encoded in the ndx table and the remaining
770  * ioctls are encoded in the misc table. An entry in the ndx table is
771  * retrieved by indexing on the last byte of the ioctl command and comparing
772  * the ioctl command with the value in the ndx table. In the event of a
773  * mismatch the misc table is then searched sequentially for the desired
774  * ioctl command.
775  *
776  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
777  */
778 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
779 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
780 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
781 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
782 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
783 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
784 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
785 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
786 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
787 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
788 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
789 
790 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
791 			MISC_CMD, ip_siocaddrt, NULL },
792 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
793 			MISC_CMD, ip_siocdelrt, NULL },
794 
795 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
796 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
797 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
798 			IF_CMD, ip_sioctl_get_addr, NULL },
799 
800 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
801 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
802 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
803 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
804 
805 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
806 			IPI_PRIV | IPI_WR,
807 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
808 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
809 			IPI_MODOK | IPI_GET_CMD,
810 			IF_CMD, ip_sioctl_get_flags, NULL },
811 
812 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
813 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
814 
815 	/* copyin size cannot be coded for SIOCGIFCONF */
816 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
817 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
818 
819 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
820 			IF_CMD, ip_sioctl_mtu, NULL },
821 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
822 			IF_CMD, ip_sioctl_get_mtu, NULL },
823 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
824 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
825 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
826 			IF_CMD, ip_sioctl_brdaddr, NULL },
827 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
828 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
829 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
830 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
831 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
832 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
833 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
834 			IF_CMD, ip_sioctl_metric, NULL },
835 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
836 
837 	/* See 166-168 below for extended SIOC*XARP ioctls */
838 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
839 			ARP_CMD, ip_sioctl_arp, NULL },
840 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
841 			ARP_CMD, ip_sioctl_arp, NULL },
842 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
843 			ARP_CMD, ip_sioctl_arp, NULL },
844 
845 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
846 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
847 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
848 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
849 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
850 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
851 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
852 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
853 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
854 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
855 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
856 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
857 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
858 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
859 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
860 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
861 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
862 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
863 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
864 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
865 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
866 
867 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
868 			MISC_CMD, if_unitsel, if_unitsel_restart },
869 
870 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
871 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
872 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
873 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
874 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
875 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
876 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
877 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
878 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
879 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
880 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
881 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
882 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
883 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
884 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
885 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
886 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
887 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
888 
889 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
890 			IPI_PRIV | IPI_WR | IPI_MODOK,
891 			IF_CMD, ip_sioctl_sifname, NULL },
892 
893 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
894 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
895 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
896 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
897 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
898 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
899 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
900 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
901 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
902 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
903 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
904 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
905 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
906 
907 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
908 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
909 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
910 			IF_CMD, ip_sioctl_get_muxid, NULL },
911 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
912 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
913 
914 	/* Both if and lif variants share same func */
915 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
916 			IF_CMD, ip_sioctl_get_lifindex, NULL },
917 	/* Both if and lif variants share same func */
918 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
919 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
920 
921 	/* copyin size cannot be coded for SIOCGIFCONF */
922 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
923 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
924 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
925 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
926 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
927 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
928 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
929 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
930 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
931 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
932 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
933 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
934 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
935 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
936 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
937 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
938 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
939 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
940 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
941 
942 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
943 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
944 			ip_sioctl_removeif_restart },
945 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
946 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
947 			LIF_CMD, ip_sioctl_addif, NULL },
948 #define	SIOCLIFADDR_NDX 112
949 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
950 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
951 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
952 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
953 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
954 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
955 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
956 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
957 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
958 			IPI_PRIV | IPI_WR,
959 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
960 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
961 			IPI_GET_CMD | IPI_MODOK,
962 			LIF_CMD, ip_sioctl_get_flags, NULL },
963 
964 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
965 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
966 
967 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
968 			ip_sioctl_get_lifconf, NULL },
969 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
970 			LIF_CMD, ip_sioctl_mtu, NULL },
971 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
972 			LIF_CMD, ip_sioctl_get_mtu, NULL },
973 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
974 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
975 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
976 			LIF_CMD, ip_sioctl_brdaddr, NULL },
977 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
978 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
979 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
980 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
981 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
982 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
983 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
984 			LIF_CMD, ip_sioctl_metric, NULL },
985 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
986 			IPI_PRIV | IPI_WR | IPI_MODOK,
987 			LIF_CMD, ip_sioctl_slifname,
988 			ip_sioctl_slifname_restart },
989 
990 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
991 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
992 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
993 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
994 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
995 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
996 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
997 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
998 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
999 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1000 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1001 			LIF_CMD, ip_sioctl_token, NULL },
1002 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1003 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1004 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1005 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1006 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1007 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1008 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1009 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1010 
1011 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1012 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1013 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1014 			LIF_CMD, ip_siocdelndp_v6, NULL },
1015 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1016 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1017 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1018 			LIF_CMD, ip_siocsetndp_v6, NULL },
1019 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1020 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1021 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1022 			MISC_CMD, ip_sioctl_tonlink, NULL },
1023 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1024 			MISC_CMD, ip_sioctl_tmysite, NULL },
1025 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1028 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1029 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1030 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1031 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1032 
1033 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 
1035 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1036 			LIF_CMD, ip_sioctl_get_binding, NULL },
1037 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1038 			IPI_PRIV | IPI_WR,
1039 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1040 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1041 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1042 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1043 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1044 
1045 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1046 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 
1050 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 
1052 	/* These are handled in ip_sioctl_copyin_setup itself */
1053 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1054 			MISC_CMD, NULL, NULL },
1055 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1056 			MISC_CMD, NULL, NULL },
1057 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1058 
1059 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1060 			ip_sioctl_get_lifconf, NULL },
1061 
1062 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1063 			XARP_CMD, ip_sioctl_arp, NULL },
1064 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1065 			XARP_CMD, ip_sioctl_arp, NULL },
1066 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1067 			XARP_CMD, ip_sioctl_arp, NULL },
1068 
1069 	/* SIOCPOPSOCKFS is not handled by IP */
1070 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1071 
1072 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1073 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1074 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1075 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1076 			ip_sioctl_slifzone_restart },
1077 	/* 172-174 are SCTP ioctls and not handled by IP */
1078 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1082 			IPI_GET_CMD, LIF_CMD,
1083 			ip_sioctl_get_lifusesrc, 0 },
1084 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1085 			IPI_PRIV | IPI_WR,
1086 			LIF_CMD, ip_sioctl_slifusesrc,
1087 			NULL },
1088 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1089 			ip_sioctl_get_lifsrcof, NULL },
1090 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1091 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1092 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1093 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1094 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1095 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1096 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1097 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1098 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* SIOCSENABLESDP is handled by SDP */
1100 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1101 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1102 	/* 185 */ { IPI_DONTCARE /* SIOCGIFHWADDR */, 0, 0, 0, NULL, NULL },
1103 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1104 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1105 			ip_sioctl_ilb_cmd, NULL },
1106 	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1107 	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1108 	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1109 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1110 	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1111 			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart }
1112 };
1113 
1114 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1115 
1116 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1117 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1118 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1119 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1120 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1121 	{ ND_GET,	0, 0, 0, NULL, NULL },
1122 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1123 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1124 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1125 		MISC_CMD, mrt_ioctl},
1126 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1127 		MISC_CMD, mrt_ioctl},
1128 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1129 		MISC_CMD, mrt_ioctl}
1130 };
1131 
1132 int ip_misc_ioctl_count =
1133     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1134 
1135 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1136 					/* Settable in /etc/system */
1137 /* Defined in ip_ire.c */
1138 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1139 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1140 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1141 
1142 static nv_t	ire_nv_arr[] = {
1143 	{ IRE_BROADCAST, "BROADCAST" },
1144 	{ IRE_LOCAL, "LOCAL" },
1145 	{ IRE_LOOPBACK, "LOOPBACK" },
1146 	{ IRE_DEFAULT, "DEFAULT" },
1147 	{ IRE_PREFIX, "PREFIX" },
1148 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1149 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1150 	{ IRE_IF_CLONE, "IF_CLONE" },
1151 	{ IRE_HOST, "HOST" },
1152 	{ IRE_MULTICAST, "MULTICAST" },
1153 	{ IRE_NOROUTE, "NOROUTE" },
1154 	{ 0 }
1155 };
1156 
1157 nv_t	*ire_nv_tbl = ire_nv_arr;
1158 
1159 /* Simple ICMP IP Header Template */
1160 static ipha_t icmp_ipha = {
1161 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1162 };
1163 
1164 struct module_info ip_mod_info = {
1165 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1166 	IP_MOD_LOWAT
1167 };
1168 
1169 /*
1170  * Duplicate static symbols within a module confuses mdb; so we avoid the
1171  * problem by making the symbols here distinct from those in udp.c.
1172  */
1173 
1174 /*
1175  * Entry points for IP as a device and as a module.
1176  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1177  */
1178 static struct qinit iprinitv4 = {
1179 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1180 	&ip_mod_info
1181 };
1182 
1183 struct qinit iprinitv6 = {
1184 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1185 	&ip_mod_info
1186 };
1187 
1188 static struct qinit ipwinit = {
1189 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1190 	&ip_mod_info
1191 };
1192 
1193 static struct qinit iplrinit = {
1194 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1195 	&ip_mod_info
1196 };
1197 
1198 static struct qinit iplwinit = {
1199 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1200 	&ip_mod_info
1201 };
1202 
1203 /* For AF_INET aka /dev/ip */
1204 struct streamtab ipinfov4 = {
1205 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1206 };
1207 
1208 /* For AF_INET6 aka /dev/ip6 */
1209 struct streamtab ipinfov6 = {
1210 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1211 };
1212 
1213 #ifdef	DEBUG
1214 boolean_t skip_sctp_cksum = B_FALSE;
1215 #endif
1216 
1217 /*
1218  * Generate an ICMP fragmentation needed message.
1219  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1220  * constructed by the caller.
1221  */
1222 void
1223 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1224 {
1225 	icmph_t	icmph;
1226 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1227 
1228 	mp = icmp_pkt_err_ok(mp, ira);
1229 	if (mp == NULL)
1230 		return;
1231 
1232 	bzero(&icmph, sizeof (icmph_t));
1233 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1234 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1235 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1236 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1237 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1238 
1239 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1240 }
1241 
1242 /*
1243  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1244  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1245  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1246  * Likewise, if the ICMP error is misformed (too short, etc), then it
1247  * returns NULL. The caller uses this to determine whether or not to send
1248  * to raw sockets.
1249  *
1250  * All error messages are passed to the matching transport stream.
1251  *
1252  * The following cases are handled by icmp_inbound:
1253  * 1) It needs to send a reply back and possibly delivering it
1254  *    to the "interested" upper clients.
1255  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1256  * 3) It needs to change some values in IP only.
1257  * 4) It needs to change some values in IP and upper layers e.g TCP
1258  *    by delivering an error to the upper layers.
1259  *
1260  * We handle the above three cases in the context of IPsec in the
1261  * following way :
1262  *
1263  * 1) Send the reply back in the same way as the request came in.
1264  *    If it came in encrypted, it goes out encrypted. If it came in
1265  *    clear, it goes out in clear. Thus, this will prevent chosen
1266  *    plain text attack.
1267  * 2) The client may or may not expect things to come in secure.
1268  *    If it comes in secure, the policy constraints are checked
1269  *    before delivering it to the upper layers. If it comes in
1270  *    clear, ipsec_inbound_accept_clear will decide whether to
1271  *    accept this in clear or not. In both the cases, if the returned
1272  *    message (IP header + 8 bytes) that caused the icmp message has
1273  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1274  *    sending up. If there are only 8 bytes of returned message, then
1275  *    upper client will not be notified.
1276  * 3) Check with global policy to see whether it matches the constaints.
1277  *    But this will be done only if icmp_accept_messages_in_clear is
1278  *    zero.
1279  * 4) If we need to change both in IP and ULP, then the decision taken
1280  *    while affecting the values in IP and while delivering up to TCP
1281  *    should be the same.
1282  *
1283  * 	There are two cases.
1284  *
1285  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1286  *	   failed), we will not deliver it to the ULP, even though they
1287  *	   are *willing* to accept in *clear*. This is fine as our global
1288  *	   disposition to icmp messages asks us reject the datagram.
1289  *
1290  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1291  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1292  *	   to deliver it to ULP (policy failed), it can lead to
1293  *	   consistency problems. The cases known at this time are
1294  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1295  *	   values :
1296  *
1297  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1298  *	     and Upper layer rejects. Then the communication will
1299  *	     come to a stop. This is solved by making similar decisions
1300  *	     at both levels. Currently, when we are unable to deliver
1301  *	     to the Upper Layer (due to policy failures) while IP has
1302  *	     adjusted dce_pmtu, the next outbound datagram would
1303  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1304  *	     will be with the right level of protection. Thus the right
1305  *	     value will be communicated even if we are not able to
1306  *	     communicate when we get from the wire initially. But this
1307  *	     assumes there would be at least one outbound datagram after
1308  *	     IP has adjusted its dce_pmtu value. To make things
1309  *	     simpler, we accept in clear after the validation of
1310  *	     AH/ESP headers.
1311  *
1312  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1313  *	     upper layer depending on the level of protection the upper
1314  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1315  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1316  *	     should be accepted in clear when the Upper layer expects secure.
1317  *	     Thus the communication may get aborted by some bad ICMP
1318  *	     packets.
1319  */
1320 mblk_t *
1321 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1322 {
1323 	icmph_t		*icmph;
1324 	ipha_t		*ipha;		/* Outer header */
1325 	int		ip_hdr_length;	/* Outer header length */
1326 	boolean_t	interested;
1327 	ipif_t		*ipif;
1328 	uint32_t	ts;
1329 	uint32_t	*tsp;
1330 	timestruc_t	now;
1331 	ill_t		*ill = ira->ira_ill;
1332 	ip_stack_t	*ipst = ill->ill_ipst;
1333 	zoneid_t	zoneid = ira->ira_zoneid;
1334 	int		len_needed;
1335 	mblk_t		*mp_ret = NULL;
1336 
1337 	ipha = (ipha_t *)mp->b_rptr;
1338 
1339 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1340 
1341 	ip_hdr_length = ira->ira_ip_hdr_length;
1342 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1343 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1344 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1345 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1346 			freemsg(mp);
1347 			return (NULL);
1348 		}
1349 		/* Last chance to get real. */
1350 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1351 		if (ipha == NULL) {
1352 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1353 			freemsg(mp);
1354 			return (NULL);
1355 		}
1356 	}
1357 
1358 	/* The IP header will always be a multiple of four bytes */
1359 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1360 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1361 	    icmph->icmph_code));
1362 
1363 	/*
1364 	 * We will set "interested" to "true" if we should pass a copy to
1365 	 * the transport or if we handle the packet locally.
1366 	 */
1367 	interested = B_FALSE;
1368 	switch (icmph->icmph_type) {
1369 	case ICMP_ECHO_REPLY:
1370 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1371 		break;
1372 	case ICMP_DEST_UNREACHABLE:
1373 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1374 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1375 		interested = B_TRUE;	/* Pass up to transport */
1376 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1377 		break;
1378 	case ICMP_SOURCE_QUENCH:
1379 		interested = B_TRUE;	/* Pass up to transport */
1380 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1381 		break;
1382 	case ICMP_REDIRECT:
1383 		if (!ipst->ips_ip_ignore_redirect)
1384 			interested = B_TRUE;
1385 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1386 		break;
1387 	case ICMP_ECHO_REQUEST:
1388 		/*
1389 		 * Whether to respond to echo requests that come in as IP
1390 		 * broadcasts or as IP multicast is subject to debate
1391 		 * (what isn't?).  We aim to please, you pick it.
1392 		 * Default is do it.
1393 		 */
1394 		if (ira->ira_flags & IRAF_MULTICAST) {
1395 			/* multicast: respond based on tunable */
1396 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1397 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1398 			/* broadcast: respond based on tunable */
1399 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1400 		} else {
1401 			/* unicast: always respond */
1402 			interested = B_TRUE;
1403 		}
1404 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1405 		if (!interested) {
1406 			/* We never pass these to RAW sockets */
1407 			freemsg(mp);
1408 			return (NULL);
1409 		}
1410 
1411 		/* Check db_ref to make sure we can modify the packet. */
1412 		if (mp->b_datap->db_ref > 1) {
1413 			mblk_t	*mp1;
1414 
1415 			mp1 = copymsg(mp);
1416 			freemsg(mp);
1417 			if (!mp1) {
1418 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1419 				return (NULL);
1420 			}
1421 			mp = mp1;
1422 			ipha = (ipha_t *)mp->b_rptr;
1423 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1424 		}
1425 		icmph->icmph_type = ICMP_ECHO_REPLY;
1426 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1427 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1428 		return (NULL);
1429 
1430 	case ICMP_ROUTER_ADVERTISEMENT:
1431 	case ICMP_ROUTER_SOLICITATION:
1432 		break;
1433 	case ICMP_TIME_EXCEEDED:
1434 		interested = B_TRUE;	/* Pass up to transport */
1435 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1436 		break;
1437 	case ICMP_PARAM_PROBLEM:
1438 		interested = B_TRUE;	/* Pass up to transport */
1439 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1440 		break;
1441 	case ICMP_TIME_STAMP_REQUEST:
1442 		/* Response to Time Stamp Requests is local policy. */
1443 		if (ipst->ips_ip_g_resp_to_timestamp) {
1444 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1445 				interested =
1446 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1447 			else
1448 				interested = B_TRUE;
1449 		}
1450 		if (!interested) {
1451 			/* We never pass these to RAW sockets */
1452 			freemsg(mp);
1453 			return (NULL);
1454 		}
1455 
1456 		/* Make sure we have enough of the packet */
1457 		len_needed = ip_hdr_length + ICMPH_SIZE +
1458 		    3 * sizeof (uint32_t);
1459 
1460 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1461 			ipha = ip_pullup(mp, len_needed, ira);
1462 			if (ipha == NULL) {
1463 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1464 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1465 				    mp, ill);
1466 				freemsg(mp);
1467 				return (NULL);
1468 			}
1469 			/* Refresh following the pullup. */
1470 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1471 		}
1472 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1473 		/* Check db_ref to make sure we can modify the packet. */
1474 		if (mp->b_datap->db_ref > 1) {
1475 			mblk_t	*mp1;
1476 
1477 			mp1 = copymsg(mp);
1478 			freemsg(mp);
1479 			if (!mp1) {
1480 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1481 				return (NULL);
1482 			}
1483 			mp = mp1;
1484 			ipha = (ipha_t *)mp->b_rptr;
1485 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1486 		}
1487 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1488 		tsp = (uint32_t *)&icmph[1];
1489 		tsp++;		/* Skip past 'originate time' */
1490 		/* Compute # of milliseconds since midnight */
1491 		gethrestime(&now);
1492 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1493 		    now.tv_nsec / (NANOSEC / MILLISEC);
1494 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1495 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1496 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1497 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1498 		return (NULL);
1499 
1500 	case ICMP_TIME_STAMP_REPLY:
1501 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1502 		break;
1503 	case ICMP_INFO_REQUEST:
1504 		/* Per RFC 1122 3.2.2.7, ignore this. */
1505 	case ICMP_INFO_REPLY:
1506 		break;
1507 	case ICMP_ADDRESS_MASK_REQUEST:
1508 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1509 			interested =
1510 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1511 		} else {
1512 			interested = B_TRUE;
1513 		}
1514 		if (!interested) {
1515 			/* We never pass these to RAW sockets */
1516 			freemsg(mp);
1517 			return (NULL);
1518 		}
1519 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1520 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1521 			ipha = ip_pullup(mp, len_needed, ira);
1522 			if (ipha == NULL) {
1523 				BUMP_MIB(ill->ill_ip_mib,
1524 				    ipIfStatsInTruncatedPkts);
1525 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1526 				    ill);
1527 				freemsg(mp);
1528 				return (NULL);
1529 			}
1530 			/* Refresh following the pullup. */
1531 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1532 		}
1533 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1534 		/* Check db_ref to make sure we can modify the packet. */
1535 		if (mp->b_datap->db_ref > 1) {
1536 			mblk_t	*mp1;
1537 
1538 			mp1 = copymsg(mp);
1539 			freemsg(mp);
1540 			if (!mp1) {
1541 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1542 				return (NULL);
1543 			}
1544 			mp = mp1;
1545 			ipha = (ipha_t *)mp->b_rptr;
1546 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1547 		}
1548 		/*
1549 		 * Need the ipif with the mask be the same as the source
1550 		 * address of the mask reply. For unicast we have a specific
1551 		 * ipif. For multicast/broadcast we only handle onlink
1552 		 * senders, and use the source address to pick an ipif.
1553 		 */
1554 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1555 		if (ipif == NULL) {
1556 			/* Broadcast or multicast */
1557 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1558 			if (ipif == NULL) {
1559 				freemsg(mp);
1560 				return (NULL);
1561 			}
1562 		}
1563 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1564 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1565 		ipif_refrele(ipif);
1566 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1567 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1568 		return (NULL);
1569 
1570 	case ICMP_ADDRESS_MASK_REPLY:
1571 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1572 		break;
1573 	default:
1574 		interested = B_TRUE;	/* Pass up to transport */
1575 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1576 		break;
1577 	}
1578 	/*
1579 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1580 	 * if there isn't one.
1581 	 */
1582 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1583 		/* If there is an ICMP client and we want one too, copy it. */
1584 
1585 		if (!interested) {
1586 			/* Caller will deliver to RAW sockets */
1587 			return (mp);
1588 		}
1589 		mp_ret = copymsg(mp);
1590 		if (mp_ret == NULL) {
1591 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1592 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1593 		}
1594 	} else if (!interested) {
1595 		/* Neither we nor raw sockets are interested. Drop packet now */
1596 		freemsg(mp);
1597 		return (NULL);
1598 	}
1599 
1600 	/*
1601 	 * ICMP error or redirect packet. Make sure we have enough of
1602 	 * the header and that db_ref == 1 since we might end up modifying
1603 	 * the packet.
1604 	 */
1605 	if (mp->b_cont != NULL) {
1606 		if (ip_pullup(mp, -1, ira) == NULL) {
1607 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1608 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1609 			    mp, ill);
1610 			freemsg(mp);
1611 			return (mp_ret);
1612 		}
1613 	}
1614 
1615 	if (mp->b_datap->db_ref > 1) {
1616 		mblk_t	*mp1;
1617 
1618 		mp1 = copymsg(mp);
1619 		if (mp1 == NULL) {
1620 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1621 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1622 			freemsg(mp);
1623 			return (mp_ret);
1624 		}
1625 		freemsg(mp);
1626 		mp = mp1;
1627 	}
1628 
1629 	/*
1630 	 * In case mp has changed, verify the message before any further
1631 	 * processes.
1632 	 */
1633 	ipha = (ipha_t *)mp->b_rptr;
1634 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1635 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1636 		freemsg(mp);
1637 		return (mp_ret);
1638 	}
1639 
1640 	switch (icmph->icmph_type) {
1641 	case ICMP_REDIRECT:
1642 		icmp_redirect_v4(mp, ipha, icmph, ira);
1643 		break;
1644 	case ICMP_DEST_UNREACHABLE:
1645 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1646 			/* Update DCE and adjust MTU is icmp header if needed */
1647 			icmp_inbound_too_big_v4(icmph, ira);
1648 		}
1649 		/* FALLTHRU */
1650 	default:
1651 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1652 		break;
1653 	}
1654 	return (mp_ret);
1655 }
1656 
1657 /*
1658  * Send an ICMP echo, timestamp or address mask reply.
1659  * The caller has already updated the payload part of the packet.
1660  * We handle the ICMP checksum, IP source address selection and feed
1661  * the packet into ip_output_simple.
1662  */
1663 static void
1664 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1665     ip_recv_attr_t *ira)
1666 {
1667 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1668 	ill_t		*ill = ira->ira_ill;
1669 	ip_stack_t	*ipst = ill->ill_ipst;
1670 	ip_xmit_attr_t	ixas;
1671 
1672 	/* Send out an ICMP packet */
1673 	icmph->icmph_checksum = 0;
1674 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1675 	/* Reset time to live. */
1676 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1677 	{
1678 		/* Swap source and destination addresses */
1679 		ipaddr_t tmp;
1680 
1681 		tmp = ipha->ipha_src;
1682 		ipha->ipha_src = ipha->ipha_dst;
1683 		ipha->ipha_dst = tmp;
1684 	}
1685 	ipha->ipha_ident = 0;
1686 	if (!IS_SIMPLE_IPH(ipha))
1687 		icmp_options_update(ipha);
1688 
1689 	bzero(&ixas, sizeof (ixas));
1690 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1691 	ixas.ixa_zoneid = ira->ira_zoneid;
1692 	ixas.ixa_cred = kcred;
1693 	ixas.ixa_cpid = NOPID;
1694 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1695 	ixas.ixa_ifindex = 0;
1696 	ixas.ixa_ipst = ipst;
1697 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1698 
1699 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1700 		/*
1701 		 * This packet should go out the same way as it
1702 		 * came in i.e in clear, independent of the IPsec policy
1703 		 * for transmitting packets.
1704 		 */
1705 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1706 	} else {
1707 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1708 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1709 			/* Note: mp already consumed and ip_drop_packet done */
1710 			return;
1711 		}
1712 	}
1713 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1714 		/*
1715 		 * Not one or our addresses (IRE_LOCALs), thus we let
1716 		 * ip_output_simple pick the source.
1717 		 */
1718 		ipha->ipha_src = INADDR_ANY;
1719 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1720 	}
1721 	/* Should we send with DF and use dce_pmtu? */
1722 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1723 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1724 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1725 	}
1726 
1727 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1728 
1729 	(void) ip_output_simple(mp, &ixas);
1730 	ixa_cleanup(&ixas);
1731 }
1732 
1733 /*
1734  * Verify the ICMP messages for either for ICMP error or redirect packet.
1735  * The caller should have fully pulled up the message. If it's a redirect
1736  * packet, only basic checks on IP header will be done; otherwise, verify
1737  * the packet by looking at the included ULP header.
1738  *
1739  * Called before icmp_inbound_error_fanout_v4 is called.
1740  */
1741 static boolean_t
1742 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1743 {
1744 	ill_t		*ill = ira->ira_ill;
1745 	int		hdr_length;
1746 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1747 	conn_t		*connp;
1748 	ipha_t		*ipha;	/* Inner IP header */
1749 
1750 	ipha = (ipha_t *)&icmph[1];
1751 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1752 		goto truncated;
1753 
1754 	hdr_length = IPH_HDR_LENGTH(ipha);
1755 
1756 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1757 		goto discard_pkt;
1758 
1759 	if (hdr_length < sizeof (ipha_t))
1760 		goto truncated;
1761 
1762 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1763 		goto truncated;
1764 
1765 	/*
1766 	 * Stop here for ICMP_REDIRECT.
1767 	 */
1768 	if (icmph->icmph_type == ICMP_REDIRECT)
1769 		return (B_TRUE);
1770 
1771 	/*
1772 	 * ICMP errors only.
1773 	 */
1774 	switch (ipha->ipha_protocol) {
1775 	case IPPROTO_UDP:
1776 		/*
1777 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1778 		 * transport header.
1779 		 */
1780 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1781 		    mp->b_wptr)
1782 			goto truncated;
1783 		break;
1784 	case IPPROTO_TCP: {
1785 		tcpha_t		*tcpha;
1786 
1787 		/*
1788 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1789 		 * transport header.
1790 		 */
1791 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1792 		    mp->b_wptr)
1793 			goto truncated;
1794 
1795 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1796 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1797 		    ipst);
1798 		if (connp == NULL)
1799 			goto discard_pkt;
1800 
1801 		if ((connp->conn_verifyicmp != NULL) &&
1802 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1803 			CONN_DEC_REF(connp);
1804 			goto discard_pkt;
1805 		}
1806 		CONN_DEC_REF(connp);
1807 		break;
1808 	}
1809 	case IPPROTO_SCTP:
1810 		/*
1811 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1812 		 * transport header.
1813 		 */
1814 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1815 		    mp->b_wptr)
1816 			goto truncated;
1817 		break;
1818 	case IPPROTO_ESP:
1819 	case IPPROTO_AH:
1820 		break;
1821 	case IPPROTO_ENCAP:
1822 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1823 		    mp->b_wptr)
1824 			goto truncated;
1825 		break;
1826 	default:
1827 		break;
1828 	}
1829 
1830 	return (B_TRUE);
1831 
1832 discard_pkt:
1833 	/* Bogus ICMP error. */
1834 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1835 	return (B_FALSE);
1836 
1837 truncated:
1838 	/* We pulled up everthing already. Must be truncated */
1839 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1840 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1841 	return (B_FALSE);
1842 }
1843 
1844 /* Table from RFC 1191 */
1845 static int icmp_frag_size_table[] =
1846 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1847 
1848 /*
1849  * Process received ICMP Packet too big.
1850  * Just handles the DCE create/update, including using the above table of
1851  * PMTU guesses. The caller is responsible for validating the packet before
1852  * passing it in and also to fanout the ICMP error to any matching transport
1853  * conns. Assumes the message has been fully pulled up and verified.
1854  *
1855  * Before getting here, the caller has called icmp_inbound_verify_v4()
1856  * that should have verified with ULP to prevent undoing the changes we're
1857  * going to make to DCE. For example, TCP might have verified that the packet
1858  * which generated error is in the send window.
1859  *
1860  * In some cases modified this MTU in the ICMP header packet; the caller
1861  * should pass to the matching ULP after this returns.
1862  */
1863 static void
1864 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1865 {
1866 	dce_t		*dce;
1867 	int		old_mtu;
1868 	int		mtu, orig_mtu;
1869 	ipaddr_t	dst;
1870 	boolean_t	disable_pmtud;
1871 	ill_t		*ill = ira->ira_ill;
1872 	ip_stack_t	*ipst = ill->ill_ipst;
1873 	uint_t		hdr_length;
1874 	ipha_t		*ipha;
1875 
1876 	/* Caller already pulled up everything. */
1877 	ipha = (ipha_t *)&icmph[1];
1878 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1879 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1880 	ASSERT(ill != NULL);
1881 
1882 	hdr_length = IPH_HDR_LENGTH(ipha);
1883 
1884 	/*
1885 	 * We handle path MTU for source routed packets since the DCE
1886 	 * is looked up using the final destination.
1887 	 */
1888 	dst = ip_get_dst(ipha);
1889 
1890 	dce = dce_lookup_and_add_v4(dst, ipst);
1891 	if (dce == NULL) {
1892 		/* Couldn't add a unique one - ENOMEM */
1893 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1894 		    ntohl(dst)));
1895 		return;
1896 	}
1897 
1898 	/* Check for MTU discovery advice as described in RFC 1191 */
1899 	mtu = ntohs(icmph->icmph_du_mtu);
1900 	orig_mtu = mtu;
1901 	disable_pmtud = B_FALSE;
1902 
1903 	mutex_enter(&dce->dce_lock);
1904 	if (dce->dce_flags & DCEF_PMTU)
1905 		old_mtu = dce->dce_pmtu;
1906 	else
1907 		old_mtu = ill->ill_mtu;
1908 
1909 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1910 		uint32_t length;
1911 		int	i;
1912 
1913 		/*
1914 		 * Use the table from RFC 1191 to figure out
1915 		 * the next "plateau" based on the length in
1916 		 * the original IP packet.
1917 		 */
1918 		length = ntohs(ipha->ipha_length);
1919 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1920 		    uint32_t, length);
1921 		if (old_mtu <= length &&
1922 		    old_mtu >= length - hdr_length) {
1923 			/*
1924 			 * Handle broken BSD 4.2 systems that
1925 			 * return the wrong ipha_length in ICMP
1926 			 * errors.
1927 			 */
1928 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1929 			    length, old_mtu));
1930 			length -= hdr_length;
1931 		}
1932 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1933 			if (length > icmp_frag_size_table[i])
1934 				break;
1935 		}
1936 		if (i == A_CNT(icmp_frag_size_table)) {
1937 			/* Smaller than IP_MIN_MTU! */
1938 			ip1dbg(("Too big for packet size %d\n",
1939 			    length));
1940 			disable_pmtud = B_TRUE;
1941 			mtu = ipst->ips_ip_pmtu_min;
1942 		} else {
1943 			mtu = icmp_frag_size_table[i];
1944 			ip1dbg(("Calculated mtu %d, packet size %d, "
1945 			    "before %d\n", mtu, length, old_mtu));
1946 			if (mtu < ipst->ips_ip_pmtu_min) {
1947 				mtu = ipst->ips_ip_pmtu_min;
1948 				disable_pmtud = B_TRUE;
1949 			}
1950 		}
1951 	}
1952 	if (disable_pmtud)
1953 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1954 	else
1955 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1956 
1957 	dce->dce_pmtu = MIN(old_mtu, mtu);
1958 	/* Prepare to send the new max frag size for the ULP. */
1959 	icmph->icmph_du_zero = 0;
1960 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1961 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1962 	    dce, int, orig_mtu, int, mtu);
1963 
1964 	/* We now have a PMTU for sure */
1965 	dce->dce_flags |= DCEF_PMTU;
1966 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1967 	mutex_exit(&dce->dce_lock);
1968 	/*
1969 	 * After dropping the lock the new value is visible to everyone.
1970 	 * Then we bump the generation number so any cached values reinspect
1971 	 * the dce_t.
1972 	 */
1973 	dce_increment_generation(dce);
1974 	dce_refrele(dce);
1975 }
1976 
1977 /*
1978  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1979  * calls this function.
1980  */
1981 static mblk_t *
1982 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1983 {
1984 	int length;
1985 
1986 	ASSERT(mp->b_datap->db_type == M_DATA);
1987 
1988 	/* icmp_inbound_v4 has already pulled up the whole error packet */
1989 	ASSERT(mp->b_cont == NULL);
1990 
1991 	/*
1992 	 * The length that we want to overlay is the inner header
1993 	 * and what follows it.
1994 	 */
1995 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
1996 
1997 	/*
1998 	 * Overlay the inner header and whatever follows it over the
1999 	 * outer header.
2000 	 */
2001 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2002 
2003 	/* Adjust for what we removed */
2004 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2005 	return (mp);
2006 }
2007 
2008 /*
2009  * Try to pass the ICMP message upstream in case the ULP cares.
2010  *
2011  * If the packet that caused the ICMP error is secure, we send
2012  * it to AH/ESP to make sure that the attached packet has a
2013  * valid association. ipha in the code below points to the
2014  * IP header of the packet that caused the error.
2015  *
2016  * For IPsec cases, we let the next-layer-up (which has access to
2017  * cached policy on the conn_t, or can query the SPD directly)
2018  * subtract out any IPsec overhead if they must.  We therefore make no
2019  * adjustments here for IPsec overhead.
2020  *
2021  * IFN could have been generated locally or by some router.
2022  *
2023  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2024  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2025  *	    This happens because IP adjusted its value of MTU on an
2026  *	    earlier IFN message and could not tell the upper layer,
2027  *	    the new adjusted value of MTU e.g. Packet was encrypted
2028  *	    or there was not enough information to fanout to upper
2029  *	    layers. Thus on the next outbound datagram, ire_send_wire
2030  *	    generates the IFN, where IPsec processing has *not* been
2031  *	    done.
2032  *
2033  *	    Note that we retain ixa_fragsize across IPsec thus once
2034  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2035  *	    no change the fragsize even if the path MTU changes before
2036  *	    we reach ip_output_post_ipsec.
2037  *
2038  *	    In the local case, IRAF_LOOPBACK will be set indicating
2039  *	    that IFN was generated locally.
2040  *
2041  * ROUTER : IFN could be secure or non-secure.
2042  *
2043  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2044  *	      packet in error has AH/ESP headers to validate the AH/ESP
2045  *	      headers. AH/ESP will verify whether there is a valid SA or
2046  *	      not and send it back. We will fanout again if we have more
2047  *	      data in the packet.
2048  *
2049  *	      If the packet in error does not have AH/ESP, we handle it
2050  *	      like any other case.
2051  *
2052  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2053  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2054  *	      valid SA or not and send it back. We will fanout again if
2055  *	      we have more data in the packet.
2056  *
2057  *	      If the packet in error does not have AH/ESP, we handle it
2058  *	      like any other case.
2059  *
2060  * The caller must have called icmp_inbound_verify_v4.
2061  */
2062 static void
2063 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2064 {
2065 	uint16_t	*up;	/* Pointer to ports in ULP header */
2066 	uint32_t	ports;	/* reversed ports for fanout */
2067 	ipha_t		ripha;	/* With reversed addresses */
2068 	ipha_t		*ipha;  /* Inner IP header */
2069 	uint_t		hdr_length; /* Inner IP header length */
2070 	tcpha_t		*tcpha;
2071 	conn_t		*connp;
2072 	ill_t		*ill = ira->ira_ill;
2073 	ip_stack_t	*ipst = ill->ill_ipst;
2074 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2075 	ill_t		*rill = ira->ira_rill;
2076 
2077 	/* Caller already pulled up everything. */
2078 	ipha = (ipha_t *)&icmph[1];
2079 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2080 	ASSERT(mp->b_cont == NULL);
2081 
2082 	hdr_length = IPH_HDR_LENGTH(ipha);
2083 	ira->ira_protocol = ipha->ipha_protocol;
2084 
2085 	/*
2086 	 * We need a separate IP header with the source and destination
2087 	 * addresses reversed to do fanout/classification because the ipha in
2088 	 * the ICMP error is in the form we sent it out.
2089 	 */
2090 	ripha.ipha_src = ipha->ipha_dst;
2091 	ripha.ipha_dst = ipha->ipha_src;
2092 	ripha.ipha_protocol = ipha->ipha_protocol;
2093 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2094 
2095 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2096 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2097 	    ntohl(ipha->ipha_dst),
2098 	    icmph->icmph_type, icmph->icmph_code));
2099 
2100 	switch (ipha->ipha_protocol) {
2101 	case IPPROTO_UDP:
2102 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2103 
2104 		/* Attempt to find a client stream based on port. */
2105 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2106 		    ntohs(up[0]), ntohs(up[1])));
2107 
2108 		/* Note that we send error to all matches. */
2109 		ira->ira_flags |= IRAF_ICMP_ERROR;
2110 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2111 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2112 		return;
2113 
2114 	case IPPROTO_TCP:
2115 		/*
2116 		 * Find a TCP client stream for this packet.
2117 		 * Note that we do a reverse lookup since the header is
2118 		 * in the form we sent it out.
2119 		 */
2120 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2121 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2122 		    ipst);
2123 		if (connp == NULL)
2124 			goto discard_pkt;
2125 
2126 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2127 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2128 			mp = ipsec_check_inbound_policy(mp, connp,
2129 			    ipha, NULL, ira);
2130 			if (mp == NULL) {
2131 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2132 				/* Note that mp is NULL */
2133 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2134 				CONN_DEC_REF(connp);
2135 				return;
2136 			}
2137 		}
2138 
2139 		ira->ira_flags |= IRAF_ICMP_ERROR;
2140 		ira->ira_ill = ira->ira_rill = NULL;
2141 		if (IPCL_IS_TCP(connp)) {
2142 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2143 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2144 			    SQTAG_TCP_INPUT_ICMP_ERR);
2145 		} else {
2146 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2147 			(connp->conn_recv)(connp, mp, NULL, ira);
2148 			CONN_DEC_REF(connp);
2149 		}
2150 		ira->ira_ill = ill;
2151 		ira->ira_rill = rill;
2152 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2153 		return;
2154 
2155 	case IPPROTO_SCTP:
2156 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2157 		/* Find a SCTP client stream for this packet. */
2158 		((uint16_t *)&ports)[0] = up[1];
2159 		((uint16_t *)&ports)[1] = up[0];
2160 
2161 		ira->ira_flags |= IRAF_ICMP_ERROR;
2162 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2163 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2164 		return;
2165 
2166 	case IPPROTO_ESP:
2167 	case IPPROTO_AH:
2168 		if (!ipsec_loaded(ipss)) {
2169 			ip_proto_not_sup(mp, ira);
2170 			return;
2171 		}
2172 
2173 		if (ipha->ipha_protocol == IPPROTO_ESP)
2174 			mp = ipsecesp_icmp_error(mp, ira);
2175 		else
2176 			mp = ipsecah_icmp_error(mp, ira);
2177 		if (mp == NULL)
2178 			return;
2179 
2180 		/* Just in case ipsec didn't preserve the NULL b_cont */
2181 		if (mp->b_cont != NULL) {
2182 			if (!pullupmsg(mp, -1))
2183 				goto discard_pkt;
2184 		}
2185 
2186 		/*
2187 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2188 		 * correct, but we don't use them any more here.
2189 		 *
2190 		 * If succesful, the mp has been modified to not include
2191 		 * the ESP/AH header so we can fanout to the ULP's icmp
2192 		 * error handler.
2193 		 */
2194 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2195 			goto truncated;
2196 
2197 		/* Verify the modified message before any further processes. */
2198 		ipha = (ipha_t *)mp->b_rptr;
2199 		hdr_length = IPH_HDR_LENGTH(ipha);
2200 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2201 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2202 			freemsg(mp);
2203 			return;
2204 		}
2205 
2206 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2207 		return;
2208 
2209 	case IPPROTO_ENCAP: {
2210 		/* Look for self-encapsulated packets that caused an error */
2211 		ipha_t *in_ipha;
2212 
2213 		/*
2214 		 * Caller has verified that length has to be
2215 		 * at least the size of IP header.
2216 		 */
2217 		ASSERT(hdr_length >= sizeof (ipha_t));
2218 		/*
2219 		 * Check the sanity of the inner IP header like
2220 		 * we did for the outer header.
2221 		 */
2222 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2223 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2224 			goto discard_pkt;
2225 		}
2226 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2227 			goto discard_pkt;
2228 		}
2229 		/* Check for Self-encapsulated tunnels */
2230 		if (in_ipha->ipha_src == ipha->ipha_src &&
2231 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2232 
2233 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2234 			    in_ipha);
2235 			if (mp == NULL)
2236 				goto discard_pkt;
2237 
2238 			/*
2239 			 * Just in case self_encap didn't preserve the NULL
2240 			 * b_cont
2241 			 */
2242 			if (mp->b_cont != NULL) {
2243 				if (!pullupmsg(mp, -1))
2244 					goto discard_pkt;
2245 			}
2246 			/*
2247 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2248 			 * longer correct, but we don't use them any more here.
2249 			 */
2250 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2251 				goto truncated;
2252 
2253 			/*
2254 			 * Verify the modified message before any further
2255 			 * processes.
2256 			 */
2257 			ipha = (ipha_t *)mp->b_rptr;
2258 			hdr_length = IPH_HDR_LENGTH(ipha);
2259 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2260 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2261 				freemsg(mp);
2262 				return;
2263 			}
2264 
2265 			/*
2266 			 * The packet in error is self-encapsualted.
2267 			 * And we are finding it further encapsulated
2268 			 * which we could not have possibly generated.
2269 			 */
2270 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2271 				goto discard_pkt;
2272 			}
2273 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2274 			return;
2275 		}
2276 		/* No self-encapsulated */
2277 		/* FALLTHRU */
2278 	}
2279 	case IPPROTO_IPV6:
2280 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2281 		    &ripha.ipha_dst, ipst)) != NULL) {
2282 			ira->ira_flags |= IRAF_ICMP_ERROR;
2283 			connp->conn_recvicmp(connp, mp, NULL, ira);
2284 			CONN_DEC_REF(connp);
2285 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2286 			return;
2287 		}
2288 		/*
2289 		 * No IP tunnel is interested, fallthrough and see
2290 		 * if a raw socket will want it.
2291 		 */
2292 		/* FALLTHRU */
2293 	default:
2294 		ira->ira_flags |= IRAF_ICMP_ERROR;
2295 		ip_fanout_proto_v4(mp, &ripha, ira);
2296 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2297 		return;
2298 	}
2299 	/* NOTREACHED */
2300 discard_pkt:
2301 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2302 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2303 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2304 	freemsg(mp);
2305 	return;
2306 
2307 truncated:
2308 	/* We pulled up everthing already. Must be truncated */
2309 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2310 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2311 	freemsg(mp);
2312 }
2313 
2314 /*
2315  * Common IP options parser.
2316  *
2317  * Setup routine: fill in *optp with options-parsing state, then
2318  * tail-call ipoptp_next to return the first option.
2319  */
2320 uint8_t
2321 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2322 {
2323 	uint32_t totallen; /* total length of all options */
2324 
2325 	totallen = ipha->ipha_version_and_hdr_length -
2326 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2327 	totallen <<= 2;
2328 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2329 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2330 	optp->ipoptp_flags = 0;
2331 	return (ipoptp_next(optp));
2332 }
2333 
2334 /* Like above but without an ipha_t */
2335 uint8_t
2336 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2337 {
2338 	optp->ipoptp_next = opt;
2339 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2340 	optp->ipoptp_flags = 0;
2341 	return (ipoptp_next(optp));
2342 }
2343 
2344 /*
2345  * Common IP options parser: extract next option.
2346  */
2347 uint8_t
2348 ipoptp_next(ipoptp_t *optp)
2349 {
2350 	uint8_t *end = optp->ipoptp_end;
2351 	uint8_t *cur = optp->ipoptp_next;
2352 	uint8_t opt, len, pointer;
2353 
2354 	/*
2355 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2356 	 * has been corrupted.
2357 	 */
2358 	ASSERT(cur <= end);
2359 
2360 	if (cur == end)
2361 		return (IPOPT_EOL);
2362 
2363 	opt = cur[IPOPT_OPTVAL];
2364 
2365 	/*
2366 	 * Skip any NOP options.
2367 	 */
2368 	while (opt == IPOPT_NOP) {
2369 		cur++;
2370 		if (cur == end)
2371 			return (IPOPT_EOL);
2372 		opt = cur[IPOPT_OPTVAL];
2373 	}
2374 
2375 	if (opt == IPOPT_EOL)
2376 		return (IPOPT_EOL);
2377 
2378 	/*
2379 	 * Option requiring a length.
2380 	 */
2381 	if ((cur + 1) >= end) {
2382 		optp->ipoptp_flags |= IPOPTP_ERROR;
2383 		return (IPOPT_EOL);
2384 	}
2385 	len = cur[IPOPT_OLEN];
2386 	if (len < 2) {
2387 		optp->ipoptp_flags |= IPOPTP_ERROR;
2388 		return (IPOPT_EOL);
2389 	}
2390 	optp->ipoptp_cur = cur;
2391 	optp->ipoptp_len = len;
2392 	optp->ipoptp_next = cur + len;
2393 	if (cur + len > end) {
2394 		optp->ipoptp_flags |= IPOPTP_ERROR;
2395 		return (IPOPT_EOL);
2396 	}
2397 
2398 	/*
2399 	 * For the options which require a pointer field, make sure
2400 	 * its there, and make sure it points to either something
2401 	 * inside this option, or the end of the option.
2402 	 */
2403 	switch (opt) {
2404 	case IPOPT_RR:
2405 	case IPOPT_TS:
2406 	case IPOPT_LSRR:
2407 	case IPOPT_SSRR:
2408 		if (len <= IPOPT_OFFSET) {
2409 			optp->ipoptp_flags |= IPOPTP_ERROR;
2410 			return (opt);
2411 		}
2412 		pointer = cur[IPOPT_OFFSET];
2413 		if (pointer - 1 > len) {
2414 			optp->ipoptp_flags |= IPOPTP_ERROR;
2415 			return (opt);
2416 		}
2417 		break;
2418 	}
2419 
2420 	/*
2421 	 * Sanity check the pointer field based on the type of the
2422 	 * option.
2423 	 */
2424 	switch (opt) {
2425 	case IPOPT_RR:
2426 	case IPOPT_SSRR:
2427 	case IPOPT_LSRR:
2428 		if (pointer < IPOPT_MINOFF_SR)
2429 			optp->ipoptp_flags |= IPOPTP_ERROR;
2430 		break;
2431 	case IPOPT_TS:
2432 		if (pointer < IPOPT_MINOFF_IT)
2433 			optp->ipoptp_flags |= IPOPTP_ERROR;
2434 		/*
2435 		 * Note that the Internet Timestamp option also
2436 		 * contains two four bit fields (the Overflow field,
2437 		 * and the Flag field), which follow the pointer
2438 		 * field.  We don't need to check that these fields
2439 		 * fall within the length of the option because this
2440 		 * was implicitely done above.  We've checked that the
2441 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2442 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2443 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2444 		 */
2445 		ASSERT(len > IPOPT_POS_OV_FLG);
2446 		break;
2447 	}
2448 
2449 	return (opt);
2450 }
2451 
2452 /*
2453  * Use the outgoing IP header to create an IP_OPTIONS option the way
2454  * it was passed down from the application.
2455  *
2456  * This is compatible with BSD in that it returns
2457  * the reverse source route with the final destination
2458  * as the last entry. The first 4 bytes of the option
2459  * will contain the final destination.
2460  */
2461 int
2462 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2463 {
2464 	ipoptp_t	opts;
2465 	uchar_t		*opt;
2466 	uint8_t		optval;
2467 	uint8_t		optlen;
2468 	uint32_t	len = 0;
2469 	uchar_t		*buf1 = buf;
2470 	uint32_t	totallen;
2471 	ipaddr_t	dst;
2472 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2473 
2474 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2475 		return (0);
2476 
2477 	totallen = ipp->ipp_ipv4_options_len;
2478 	if (totallen & 0x3)
2479 		return (0);
2480 
2481 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2482 	len += IP_ADDR_LEN;
2483 	bzero(buf1, IP_ADDR_LEN);
2484 
2485 	dst = connp->conn_faddr_v4;
2486 
2487 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2488 	    optval != IPOPT_EOL;
2489 	    optval = ipoptp_next(&opts)) {
2490 		int	off;
2491 
2492 		opt = opts.ipoptp_cur;
2493 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2494 			break;
2495 		}
2496 		optlen = opts.ipoptp_len;
2497 
2498 		switch (optval) {
2499 		case IPOPT_SSRR:
2500 		case IPOPT_LSRR:
2501 
2502 			/*
2503 			 * Insert destination as the first entry in the source
2504 			 * route and move down the entries on step.
2505 			 * The last entry gets placed at buf1.
2506 			 */
2507 			buf[IPOPT_OPTVAL] = optval;
2508 			buf[IPOPT_OLEN] = optlen;
2509 			buf[IPOPT_OFFSET] = optlen;
2510 
2511 			off = optlen - IP_ADDR_LEN;
2512 			if (off < 0) {
2513 				/* No entries in source route */
2514 				break;
2515 			}
2516 			/* Last entry in source route if not already set */
2517 			if (dst == INADDR_ANY)
2518 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2519 			off -= IP_ADDR_LEN;
2520 
2521 			while (off > 0) {
2522 				bcopy(opt + off,
2523 				    buf + off + IP_ADDR_LEN,
2524 				    IP_ADDR_LEN);
2525 				off -= IP_ADDR_LEN;
2526 			}
2527 			/* ipha_dst into first slot */
2528 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2529 			    IP_ADDR_LEN);
2530 			buf += optlen;
2531 			len += optlen;
2532 			break;
2533 
2534 		default:
2535 			bcopy(opt, buf, optlen);
2536 			buf += optlen;
2537 			len += optlen;
2538 			break;
2539 		}
2540 	}
2541 done:
2542 	/* Pad the resulting options */
2543 	while (len & 0x3) {
2544 		*buf++ = IPOPT_EOL;
2545 		len++;
2546 	}
2547 	return (len);
2548 }
2549 
2550 /*
2551  * Update any record route or timestamp options to include this host.
2552  * Reverse any source route option.
2553  * This routine assumes that the options are well formed i.e. that they
2554  * have already been checked.
2555  */
2556 static void
2557 icmp_options_update(ipha_t *ipha)
2558 {
2559 	ipoptp_t	opts;
2560 	uchar_t		*opt;
2561 	uint8_t		optval;
2562 	ipaddr_t	src;		/* Our local address */
2563 	ipaddr_t	dst;
2564 
2565 	ip2dbg(("icmp_options_update\n"));
2566 	src = ipha->ipha_src;
2567 	dst = ipha->ipha_dst;
2568 
2569 	for (optval = ipoptp_first(&opts, ipha);
2570 	    optval != IPOPT_EOL;
2571 	    optval = ipoptp_next(&opts)) {
2572 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2573 		opt = opts.ipoptp_cur;
2574 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2575 		    optval, opts.ipoptp_len));
2576 		switch (optval) {
2577 			int off1, off2;
2578 		case IPOPT_SSRR:
2579 		case IPOPT_LSRR:
2580 			/*
2581 			 * Reverse the source route.  The first entry
2582 			 * should be the next to last one in the current
2583 			 * source route (the last entry is our address).
2584 			 * The last entry should be the final destination.
2585 			 */
2586 			off1 = IPOPT_MINOFF_SR - 1;
2587 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2588 			if (off2 < 0) {
2589 				/* No entries in source route */
2590 				ip1dbg((
2591 				    "icmp_options_update: bad src route\n"));
2592 				break;
2593 			}
2594 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2595 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2596 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2597 			off2 -= IP_ADDR_LEN;
2598 
2599 			while (off1 < off2) {
2600 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2601 				bcopy((char *)opt + off2, (char *)opt + off1,
2602 				    IP_ADDR_LEN);
2603 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2604 				off1 += IP_ADDR_LEN;
2605 				off2 -= IP_ADDR_LEN;
2606 			}
2607 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2608 			break;
2609 		}
2610 	}
2611 }
2612 
2613 /*
2614  * Process received ICMP Redirect messages.
2615  * Assumes the caller has verified that the headers are in the pulled up mblk.
2616  * Consumes mp.
2617  */
2618 static void
2619 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2620 {
2621 	ire_t		*ire, *nire;
2622 	ire_t		*prev_ire;
2623 	ipaddr_t  	src, dst, gateway;
2624 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2625 	ipha_t		*inner_ipha;	/* Inner IP header */
2626 
2627 	/* Caller already pulled up everything. */
2628 	inner_ipha = (ipha_t *)&icmph[1];
2629 	src = ipha->ipha_src;
2630 	dst = inner_ipha->ipha_dst;
2631 	gateway = icmph->icmph_rd_gateway;
2632 	/* Make sure the new gateway is reachable somehow. */
2633 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2634 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2635 	/*
2636 	 * Make sure we had a route for the dest in question and that
2637 	 * that route was pointing to the old gateway (the source of the
2638 	 * redirect packet.)
2639 	 * We do longest match and then compare ire_gateway_addr below.
2640 	 */
2641 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2642 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2643 	/*
2644 	 * Check that
2645 	 *	the redirect was not from ourselves
2646 	 *	the new gateway and the old gateway are directly reachable
2647 	 */
2648 	if (prev_ire == NULL || ire == NULL ||
2649 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2650 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2651 	    !(ire->ire_type & IRE_IF_ALL) ||
2652 	    prev_ire->ire_gateway_addr != src) {
2653 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2654 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2655 		freemsg(mp);
2656 		if (ire != NULL)
2657 			ire_refrele(ire);
2658 		if (prev_ire != NULL)
2659 			ire_refrele(prev_ire);
2660 		return;
2661 	}
2662 
2663 	ire_refrele(prev_ire);
2664 	ire_refrele(ire);
2665 
2666 	/*
2667 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2668 	 * require TOS routing
2669 	 */
2670 	switch (icmph->icmph_code) {
2671 	case 0:
2672 	case 1:
2673 		/* TODO: TOS specificity for cases 2 and 3 */
2674 	case 2:
2675 	case 3:
2676 		break;
2677 	default:
2678 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2679 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2680 		freemsg(mp);
2681 		return;
2682 	}
2683 	/*
2684 	 * Create a Route Association.  This will allow us to remember that
2685 	 * someone we believe told us to use the particular gateway.
2686 	 */
2687 	ire = ire_create(
2688 	    (uchar_t *)&dst,			/* dest addr */
2689 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2690 	    (uchar_t *)&gateway,		/* gateway addr */
2691 	    IRE_HOST,
2692 	    NULL,				/* ill */
2693 	    ALL_ZONES,
2694 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2695 	    NULL,				/* tsol_gc_t */
2696 	    ipst);
2697 
2698 	if (ire == NULL) {
2699 		freemsg(mp);
2700 		return;
2701 	}
2702 	nire = ire_add(ire);
2703 	/* Check if it was a duplicate entry */
2704 	if (nire != NULL && nire != ire) {
2705 		ASSERT(nire->ire_identical_ref > 1);
2706 		ire_delete(nire);
2707 		ire_refrele(nire);
2708 		nire = NULL;
2709 	}
2710 	ire = nire;
2711 	if (ire != NULL) {
2712 		ire_refrele(ire);		/* Held in ire_add */
2713 
2714 		/* tell routing sockets that we received a redirect */
2715 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2716 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2717 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2718 	}
2719 
2720 	/*
2721 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2722 	 * This together with the added IRE has the effect of
2723 	 * modifying an existing redirect.
2724 	 */
2725 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2726 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2727 	if (prev_ire != NULL) {
2728 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2729 			ire_delete(prev_ire);
2730 		ire_refrele(prev_ire);
2731 	}
2732 
2733 	freemsg(mp);
2734 }
2735 
2736 /*
2737  * Generate an ICMP parameter problem message.
2738  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2739  * constructed by the caller.
2740  */
2741 static void
2742 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2743 {
2744 	icmph_t	icmph;
2745 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2746 
2747 	mp = icmp_pkt_err_ok(mp, ira);
2748 	if (mp == NULL)
2749 		return;
2750 
2751 	bzero(&icmph, sizeof (icmph_t));
2752 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2753 	icmph.icmph_pp_ptr = ptr;
2754 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2755 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2756 }
2757 
2758 /*
2759  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2760  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2761  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2762  * an icmp error packet can be sent.
2763  * Assigns an appropriate source address to the packet. If ipha_dst is
2764  * one of our addresses use it for source. Otherwise let ip_output_simple
2765  * pick the source address.
2766  */
2767 static void
2768 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2769 {
2770 	ipaddr_t dst;
2771 	icmph_t	*icmph;
2772 	ipha_t	*ipha;
2773 	uint_t	len_needed;
2774 	size_t	msg_len;
2775 	mblk_t	*mp1;
2776 	ipaddr_t src;
2777 	ire_t	*ire;
2778 	ip_xmit_attr_t ixas;
2779 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2780 
2781 	ipha = (ipha_t *)mp->b_rptr;
2782 
2783 	bzero(&ixas, sizeof (ixas));
2784 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2785 	ixas.ixa_zoneid = ira->ira_zoneid;
2786 	ixas.ixa_ifindex = 0;
2787 	ixas.ixa_ipst = ipst;
2788 	ixas.ixa_cred = kcred;
2789 	ixas.ixa_cpid = NOPID;
2790 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2791 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2792 
2793 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2794 		/*
2795 		 * Apply IPsec based on how IPsec was applied to
2796 		 * the packet that had the error.
2797 		 *
2798 		 * If it was an outbound packet that caused the ICMP
2799 		 * error, then the caller will have setup the IRA
2800 		 * appropriately.
2801 		 */
2802 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2803 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2804 			/* Note: mp already consumed and ip_drop_packet done */
2805 			return;
2806 		}
2807 	} else {
2808 		/*
2809 		 * This is in clear. The icmp message we are building
2810 		 * here should go out in clear, independent of our policy.
2811 		 */
2812 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2813 	}
2814 
2815 	/* Remember our eventual destination */
2816 	dst = ipha->ipha_src;
2817 
2818 	/*
2819 	 * If the packet was for one of our unicast addresses, make
2820 	 * sure we respond with that as the source. Otherwise
2821 	 * have ip_output_simple pick the source address.
2822 	 */
2823 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2824 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2825 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2826 	if (ire != NULL) {
2827 		ire_refrele(ire);
2828 		src = ipha->ipha_dst;
2829 	} else {
2830 		src = INADDR_ANY;
2831 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2832 	}
2833 
2834 	/*
2835 	 * Check if we can send back more then 8 bytes in addition to
2836 	 * the IP header.  We try to send 64 bytes of data and the internal
2837 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2838 	 */
2839 	len_needed = IPH_HDR_LENGTH(ipha);
2840 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2841 	    ipha->ipha_protocol == IPPROTO_IPV6) {
2842 		if (!pullupmsg(mp, -1)) {
2843 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2844 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2845 			freemsg(mp);
2846 			return;
2847 		}
2848 		ipha = (ipha_t *)mp->b_rptr;
2849 
2850 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2851 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2852 			    len_needed));
2853 		} else {
2854 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2855 
2856 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2857 			len_needed += ip_hdr_length_v6(mp, ip6h);
2858 		}
2859 	}
2860 	len_needed += ipst->ips_ip_icmp_return;
2861 	msg_len = msgdsize(mp);
2862 	if (msg_len > len_needed) {
2863 		(void) adjmsg(mp, len_needed - msg_len);
2864 		msg_len = len_needed;
2865 	}
2866 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2867 	if (mp1 == NULL) {
2868 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2869 		freemsg(mp);
2870 		return;
2871 	}
2872 	mp1->b_cont = mp;
2873 	mp = mp1;
2874 
2875 	/*
2876 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2877 	 * node generates be accepted in peace by all on-host destinations.
2878 	 * If we do NOT assume that all on-host destinations trust
2879 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2880 	 * (Look for IXAF_TRUSTED_ICMP).
2881 	 */
2882 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2883 
2884 	ipha = (ipha_t *)mp->b_rptr;
2885 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2886 	*ipha = icmp_ipha;
2887 	ipha->ipha_src = src;
2888 	ipha->ipha_dst = dst;
2889 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2890 	msg_len += sizeof (icmp_ipha) + len;
2891 	if (msg_len > IP_MAXPACKET) {
2892 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
2893 		msg_len = IP_MAXPACKET;
2894 	}
2895 	ipha->ipha_length = htons((uint16_t)msg_len);
2896 	icmph = (icmph_t *)&ipha[1];
2897 	bcopy(stuff, icmph, len);
2898 	icmph->icmph_checksum = 0;
2899 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2900 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2901 
2902 	(void) ip_output_simple(mp, &ixas);
2903 	ixa_cleanup(&ixas);
2904 }
2905 
2906 /*
2907  * Determine if an ICMP error packet can be sent given the rate limit.
2908  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2909  * in milliseconds) and a burst size. Burst size number of packets can
2910  * be sent arbitrarely closely spaced.
2911  * The state is tracked using two variables to implement an approximate
2912  * token bucket filter:
2913  *	icmp_pkt_err_last - lbolt value when the last burst started
2914  *	icmp_pkt_err_sent - number of packets sent in current burst
2915  */
2916 boolean_t
2917 icmp_err_rate_limit(ip_stack_t *ipst)
2918 {
2919 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2920 	uint_t refilled; /* Number of packets refilled in tbf since last */
2921 	/* Guard against changes by loading into local variable */
2922 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2923 
2924 	if (err_interval == 0)
2925 		return (B_FALSE);
2926 
2927 	if (ipst->ips_icmp_pkt_err_last > now) {
2928 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2929 		ipst->ips_icmp_pkt_err_last = 0;
2930 		ipst->ips_icmp_pkt_err_sent = 0;
2931 	}
2932 	/*
2933 	 * If we are in a burst update the token bucket filter.
2934 	 * Update the "last" time to be close to "now" but make sure
2935 	 * we don't loose precision.
2936 	 */
2937 	if (ipst->ips_icmp_pkt_err_sent != 0) {
2938 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2939 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
2940 			ipst->ips_icmp_pkt_err_sent = 0;
2941 		} else {
2942 			ipst->ips_icmp_pkt_err_sent -= refilled;
2943 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2944 		}
2945 	}
2946 	if (ipst->ips_icmp_pkt_err_sent == 0) {
2947 		/* Start of new burst */
2948 		ipst->ips_icmp_pkt_err_last = now;
2949 	}
2950 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2951 		ipst->ips_icmp_pkt_err_sent++;
2952 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2953 		    ipst->ips_icmp_pkt_err_sent));
2954 		return (B_FALSE);
2955 	}
2956 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
2957 	return (B_TRUE);
2958 }
2959 
2960 /*
2961  * Check if it is ok to send an IPv4 ICMP error packet in
2962  * response to the IPv4 packet in mp.
2963  * Free the message and return null if no
2964  * ICMP error packet should be sent.
2965  */
2966 static mblk_t *
2967 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2968 {
2969 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2970 	icmph_t	*icmph;
2971 	ipha_t	*ipha;
2972 	uint_t	len_needed;
2973 
2974 	if (!mp)
2975 		return (NULL);
2976 	ipha = (ipha_t *)mp->b_rptr;
2977 	if (ip_csum_hdr(ipha)) {
2978 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2979 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2980 		freemsg(mp);
2981 		return (NULL);
2982 	}
2983 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2984 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2985 	    CLASSD(ipha->ipha_dst) ||
2986 	    CLASSD(ipha->ipha_src) ||
2987 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2988 		/* Note: only errors to the fragment with offset 0 */
2989 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2990 		freemsg(mp);
2991 		return (NULL);
2992 	}
2993 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
2994 		/*
2995 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
2996 		 * errors in response to any ICMP errors.
2997 		 */
2998 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
2999 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3000 			if (!pullupmsg(mp, len_needed)) {
3001 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3002 				freemsg(mp);
3003 				return (NULL);
3004 			}
3005 			ipha = (ipha_t *)mp->b_rptr;
3006 		}
3007 		icmph = (icmph_t *)
3008 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3009 		switch (icmph->icmph_type) {
3010 		case ICMP_DEST_UNREACHABLE:
3011 		case ICMP_SOURCE_QUENCH:
3012 		case ICMP_TIME_EXCEEDED:
3013 		case ICMP_PARAM_PROBLEM:
3014 		case ICMP_REDIRECT:
3015 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3016 			freemsg(mp);
3017 			return (NULL);
3018 		default:
3019 			break;
3020 		}
3021 	}
3022 	/*
3023 	 * If this is a labeled system, then check to see if we're allowed to
3024 	 * send a response to this particular sender.  If not, then just drop.
3025 	 */
3026 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3027 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3028 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3029 		freemsg(mp);
3030 		return (NULL);
3031 	}
3032 	if (icmp_err_rate_limit(ipst)) {
3033 		/*
3034 		 * Only send ICMP error packets every so often.
3035 		 * This should be done on a per port/source basis,
3036 		 * but for now this will suffice.
3037 		 */
3038 		freemsg(mp);
3039 		return (NULL);
3040 	}
3041 	return (mp);
3042 }
3043 
3044 /*
3045  * Called when a packet was sent out the same link that it arrived on.
3046  * Check if it is ok to send a redirect and then send it.
3047  */
3048 void
3049 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3050     ip_recv_attr_t *ira)
3051 {
3052 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3053 	ipaddr_t	src, nhop;
3054 	mblk_t		*mp1;
3055 	ire_t		*nhop_ire;
3056 
3057 	/*
3058 	 * Check the source address to see if it originated
3059 	 * on the same logical subnet it is going back out on.
3060 	 * If so, we should be able to send it a redirect.
3061 	 * Avoid sending a redirect if the destination
3062 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3063 	 * or if the packet was source routed out this interface.
3064 	 *
3065 	 * We avoid sending a redirect if the
3066 	 * destination is directly connected
3067 	 * because it is possible that multiple
3068 	 * IP subnets may have been configured on
3069 	 * the link, and the source may not
3070 	 * be on the same subnet as ip destination,
3071 	 * even though they are on the same
3072 	 * physical link.
3073 	 */
3074 	if ((ire->ire_type & IRE_ONLINK) ||
3075 	    ip_source_routed(ipha, ipst))
3076 		return;
3077 
3078 	nhop_ire = ire_nexthop(ire);
3079 	if (nhop_ire == NULL)
3080 		return;
3081 
3082 	nhop = nhop_ire->ire_addr;
3083 
3084 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3085 		ire_t	*ire2;
3086 
3087 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3088 		mutex_enter(&nhop_ire->ire_lock);
3089 		ire2 = nhop_ire->ire_dep_parent;
3090 		if (ire2 != NULL)
3091 			ire_refhold(ire2);
3092 		mutex_exit(&nhop_ire->ire_lock);
3093 		ire_refrele(nhop_ire);
3094 		nhop_ire = ire2;
3095 	}
3096 	if (nhop_ire == NULL)
3097 		return;
3098 
3099 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3100 
3101 	src = ipha->ipha_src;
3102 
3103 	/*
3104 	 * We look at the interface ire for the nexthop,
3105 	 * to see if ipha_src is in the same subnet
3106 	 * as the nexthop.
3107 	 */
3108 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3109 		/*
3110 		 * The source is directly connected.
3111 		 */
3112 		mp1 = copymsg(mp);
3113 		if (mp1 != NULL) {
3114 			icmp_send_redirect(mp1, nhop, ira);
3115 		}
3116 	}
3117 	ire_refrele(nhop_ire);
3118 }
3119 
3120 /*
3121  * Generate an ICMP redirect message.
3122  */
3123 static void
3124 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3125 {
3126 	icmph_t	icmph;
3127 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3128 
3129 	mp = icmp_pkt_err_ok(mp, ira);
3130 	if (mp == NULL)
3131 		return;
3132 
3133 	bzero(&icmph, sizeof (icmph_t));
3134 	icmph.icmph_type = ICMP_REDIRECT;
3135 	icmph.icmph_code = 1;
3136 	icmph.icmph_rd_gateway = gateway;
3137 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3138 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3139 }
3140 
3141 /*
3142  * Generate an ICMP time exceeded message.
3143  */
3144 void
3145 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3146 {
3147 	icmph_t	icmph;
3148 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3149 
3150 	mp = icmp_pkt_err_ok(mp, ira);
3151 	if (mp == NULL)
3152 		return;
3153 
3154 	bzero(&icmph, sizeof (icmph_t));
3155 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3156 	icmph.icmph_code = code;
3157 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3158 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3159 }
3160 
3161 /*
3162  * Generate an ICMP unreachable message.
3163  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3164  * constructed by the caller.
3165  */
3166 void
3167 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3168 {
3169 	icmph_t	icmph;
3170 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3171 
3172 	mp = icmp_pkt_err_ok(mp, ira);
3173 	if (mp == NULL)
3174 		return;
3175 
3176 	bzero(&icmph, sizeof (icmph_t));
3177 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3178 	icmph.icmph_code = code;
3179 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3180 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3181 }
3182 
3183 /*
3184  * Latch in the IPsec state for a stream based the policy in the listener
3185  * and the actions in the ip_recv_attr_t.
3186  * Called directly from TCP and SCTP.
3187  */
3188 boolean_t
3189 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3190 {
3191 	ASSERT(lconnp->conn_policy != NULL);
3192 	ASSERT(connp->conn_policy == NULL);
3193 
3194 	IPPH_REFHOLD(lconnp->conn_policy);
3195 	connp->conn_policy = lconnp->conn_policy;
3196 
3197 	if (ira->ira_ipsec_action != NULL) {
3198 		if (connp->conn_latch == NULL) {
3199 			connp->conn_latch = iplatch_create();
3200 			if (connp->conn_latch == NULL)
3201 				return (B_FALSE);
3202 		}
3203 		ipsec_latch_inbound(connp, ira);
3204 	}
3205 	return (B_TRUE);
3206 }
3207 
3208 /*
3209  * Verify whether or not the IP address is a valid local address.
3210  * Could be a unicast, including one for a down interface.
3211  * If allow_mcbc then a multicast or broadcast address is also
3212  * acceptable.
3213  *
3214  * In the case of a broadcast/multicast address, however, the
3215  * upper protocol is expected to reset the src address
3216  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3217  * no packets are emitted with broadcast/multicast address as
3218  * source address (that violates hosts requirements RFC 1122)
3219  * The addresses valid for bind are:
3220  *	(1) - INADDR_ANY (0)
3221  *	(2) - IP address of an UP interface
3222  *	(3) - IP address of a DOWN interface
3223  *	(4) - valid local IP broadcast addresses. In this case
3224  *	the conn will only receive packets destined to
3225  *	the specified broadcast address.
3226  *	(5) - a multicast address. In this case
3227  *	the conn will only receive packets destined to
3228  *	the specified multicast address. Note: the
3229  *	application still has to issue an
3230  *	IP_ADD_MEMBERSHIP socket option.
3231  *
3232  * In all the above cases, the bound address must be valid in the current zone.
3233  * When the address is loopback, multicast or broadcast, there might be many
3234  * matching IREs so bind has to look up based on the zone.
3235  */
3236 ip_laddr_t
3237 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3238     ip_stack_t *ipst, boolean_t allow_mcbc)
3239 {
3240 	ire_t *src_ire;
3241 
3242 	ASSERT(src_addr != INADDR_ANY);
3243 
3244 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3245 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3246 
3247 	/*
3248 	 * If an address other than in6addr_any is requested,
3249 	 * we verify that it is a valid address for bind
3250 	 * Note: Following code is in if-else-if form for
3251 	 * readability compared to a condition check.
3252 	 */
3253 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3254 		/*
3255 		 * (2) Bind to address of local UP interface
3256 		 */
3257 		ire_refrele(src_ire);
3258 		return (IPVL_UNICAST_UP);
3259 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3260 		/*
3261 		 * (4) Bind to broadcast address
3262 		 */
3263 		ire_refrele(src_ire);
3264 		if (allow_mcbc)
3265 			return (IPVL_BCAST);
3266 		else
3267 			return (IPVL_BAD);
3268 	} else if (CLASSD(src_addr)) {
3269 		/* (5) bind to multicast address. */
3270 		if (src_ire != NULL)
3271 			ire_refrele(src_ire);
3272 
3273 		if (allow_mcbc)
3274 			return (IPVL_MCAST);
3275 		else
3276 			return (IPVL_BAD);
3277 	} else {
3278 		ipif_t *ipif;
3279 
3280 		/*
3281 		 * (3) Bind to address of local DOWN interface?
3282 		 * (ipif_lookup_addr() looks up all interfaces
3283 		 * but we do not get here for UP interfaces
3284 		 * - case (2) above)
3285 		 */
3286 		if (src_ire != NULL)
3287 			ire_refrele(src_ire);
3288 
3289 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3290 		if (ipif == NULL)
3291 			return (IPVL_BAD);
3292 
3293 		/* Not a useful source? */
3294 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3295 			ipif_refrele(ipif);
3296 			return (IPVL_BAD);
3297 		}
3298 		ipif_refrele(ipif);
3299 		return (IPVL_UNICAST_DOWN);
3300 	}
3301 }
3302 
3303 /*
3304  * Insert in the bind fanout for IPv4 and IPv6.
3305  * The caller should already have used ip_laddr_verify_v*() before calling
3306  * this.
3307  */
3308 int
3309 ip_laddr_fanout_insert(conn_t *connp)
3310 {
3311 	int		error;
3312 
3313 	/*
3314 	 * Allow setting new policies. For example, disconnects result
3315 	 * in us being called. As we would have set conn_policy_cached
3316 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3317 	 * can change after the disconnect.
3318 	 */
3319 	connp->conn_policy_cached = B_FALSE;
3320 
3321 	error = ipcl_bind_insert(connp);
3322 	if (error != 0) {
3323 		if (connp->conn_anon_port) {
3324 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3325 			    connp->conn_mlp_type, connp->conn_proto,
3326 			    ntohs(connp->conn_lport), B_FALSE);
3327 		}
3328 		connp->conn_mlp_type = mlptSingle;
3329 	}
3330 	return (error);
3331 }
3332 
3333 /*
3334  * Verify that both the source and destination addresses are valid. If
3335  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3336  * i.e. have no route to it.  Protocols like TCP want to verify destination
3337  * reachability, while tunnels do not.
3338  *
3339  * Determine the route, the interface, and (optionally) the source address
3340  * to use to reach a given destination.
3341  * Note that we allow connect to broadcast and multicast addresses when
3342  * IPDF_ALLOW_MCBC is set.
3343  * first_hop and dst_addr are normally the same, but if source routing
3344  * they will differ; in that case the first_hop is what we'll use for the
3345  * routing lookup but the dce and label checks will be done on dst_addr,
3346  *
3347  * If uinfo is set, then we fill in the best available information
3348  * we have for the destination. This is based on (in priority order) any
3349  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3350  * ill_mtu.
3351  *
3352  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3353  * always do the label check on dst_addr.
3354  */
3355 int
3356 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3357     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3358 {
3359 	ire_t		*ire = NULL;
3360 	int		error = 0;
3361 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3362 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3363 	ip_stack_t	*ipst = ixa->ixa_ipst;
3364 	dce_t		*dce;
3365 	uint_t		pmtu;
3366 	uint_t		generation;
3367 	nce_t		*nce;
3368 	ill_t		*ill = NULL;
3369 	boolean_t	multirt = B_FALSE;
3370 
3371 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3372 
3373 	/*
3374 	 * We never send to zero; the ULPs map it to the loopback address.
3375 	 * We can't allow it since we use zero to mean unitialized in some
3376 	 * places.
3377 	 */
3378 	ASSERT(dst_addr != INADDR_ANY);
3379 
3380 	if (is_system_labeled()) {
3381 		ts_label_t *tsl = NULL;
3382 
3383 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3384 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3385 		if (error != 0)
3386 			return (error);
3387 		if (tsl != NULL) {
3388 			/* Update the label */
3389 			ip_xmit_attr_replace_tsl(ixa, tsl);
3390 		}
3391 	}
3392 
3393 	setsrc = INADDR_ANY;
3394 	/*
3395 	 * Select a route; For IPMP interfaces, we would only select
3396 	 * a "hidden" route (i.e., going through a specific under_ill)
3397 	 * if ixa_ifindex has been specified.
3398 	 */
3399 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3400 	    &generation, &setsrc, &error, &multirt);
3401 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3402 	if (error != 0)
3403 		goto bad_addr;
3404 
3405 	/*
3406 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3407 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3408 	 * Otherwise the destination needn't be reachable.
3409 	 *
3410 	 * If we match on a reject or black hole, then we've got a
3411 	 * local failure.  May as well fail out the connect() attempt,
3412 	 * since it's never going to succeed.
3413 	 */
3414 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3415 		/*
3416 		 * If we're verifying destination reachability, we always want
3417 		 * to complain here.
3418 		 *
3419 		 * If we're not verifying destination reachability but the
3420 		 * destination has a route, we still want to fail on the
3421 		 * temporary address and broadcast address tests.
3422 		 *
3423 		 * In both cases do we let the code continue so some reasonable
3424 		 * information is returned to the caller. That enables the
3425 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3426 		 * use the generation mismatch path to check for the unreachable
3427 		 * case thereby avoiding any specific check in the main path.
3428 		 */
3429 		ASSERT(generation == IRE_GENERATION_VERIFY);
3430 		if (flags & IPDF_VERIFY_DST) {
3431 			/*
3432 			 * Set errno but continue to set up ixa_ire to be
3433 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3434 			 * That allows callers to use ip_output to get an
3435 			 * ICMP error back.
3436 			 */
3437 			if (!(ire->ire_type & IRE_HOST))
3438 				error = ENETUNREACH;
3439 			else
3440 				error = EHOSTUNREACH;
3441 		}
3442 	}
3443 
3444 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3445 	    !(flags & IPDF_ALLOW_MCBC)) {
3446 		ire_refrele(ire);
3447 		ire = ire_reject(ipst, B_FALSE);
3448 		generation = IRE_GENERATION_VERIFY;
3449 		error = ENETUNREACH;
3450 	}
3451 
3452 	/* Cache things */
3453 	if (ixa->ixa_ire != NULL)
3454 		ire_refrele_notr(ixa->ixa_ire);
3455 #ifdef DEBUG
3456 	ire_refhold_notr(ire);
3457 	ire_refrele(ire);
3458 #endif
3459 	ixa->ixa_ire = ire;
3460 	ixa->ixa_ire_generation = generation;
3461 
3462 	/*
3463 	 * For multicast with multirt we have a flag passed back from
3464 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3465 	 * possible multicast address.
3466 	 * We also need a flag for multicast since we can't check
3467 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3468 	 */
3469 	if (multirt) {
3470 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3471 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3472 	} else {
3473 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3474 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3475 	}
3476 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3477 		/* Get an nce to cache. */
3478 		nce = ire_to_nce(ire, firsthop, NULL);
3479 		if (nce == NULL) {
3480 			/* Allocation failure? */
3481 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3482 		} else {
3483 			if (ixa->ixa_nce != NULL)
3484 				nce_refrele(ixa->ixa_nce);
3485 			ixa->ixa_nce = nce;
3486 		}
3487 	}
3488 
3489 	/*
3490 	 * If the source address is a loopback address, the
3491 	 * destination had best be local or multicast.
3492 	 * If we are sending to an IRE_LOCAL using a loopback source then
3493 	 * it had better be the same zoneid.
3494 	 */
3495 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3496 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3497 			ire = NULL;	/* Stored in ixa_ire */
3498 			error = EADDRNOTAVAIL;
3499 			goto bad_addr;
3500 		}
3501 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3502 			ire = NULL;	/* Stored in ixa_ire */
3503 			error = EADDRNOTAVAIL;
3504 			goto bad_addr;
3505 		}
3506 	}
3507 	if (ire->ire_type & IRE_BROADCAST) {
3508 		/*
3509 		 * If the ULP didn't have a specified source, then we
3510 		 * make sure we reselect the source when sending
3511 		 * broadcasts out different interfaces.
3512 		 */
3513 		if (flags & IPDF_SELECT_SRC)
3514 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3515 		else
3516 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3517 	}
3518 
3519 	/*
3520 	 * Does the caller want us to pick a source address?
3521 	 */
3522 	if (flags & IPDF_SELECT_SRC) {
3523 		ipaddr_t	src_addr;
3524 
3525 		/*
3526 		 * We use use ire_nexthop_ill to avoid the under ipmp
3527 		 * interface for source address selection. Note that for ipmp
3528 		 * probe packets, ixa_ifindex would have been specified, and
3529 		 * the ip_select_route() invocation would have picked an ire
3530 		 * will ire_ill pointing at an under interface.
3531 		 */
3532 		ill = ire_nexthop_ill(ire);
3533 
3534 		/* If unreachable we have no ill but need some source */
3535 		if (ill == NULL) {
3536 			src_addr = htonl(INADDR_LOOPBACK);
3537 			/* Make sure we look for a better source address */
3538 			generation = SRC_GENERATION_VERIFY;
3539 		} else {
3540 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3541 			    ixa->ixa_multicast_ifaddr, zoneid,
3542 			    ipst, &src_addr, &generation, NULL);
3543 			if (error != 0) {
3544 				ire = NULL;	/* Stored in ixa_ire */
3545 				goto bad_addr;
3546 			}
3547 		}
3548 
3549 		/*
3550 		 * We allow the source address to to down.
3551 		 * However, we check that we don't use the loopback address
3552 		 * as a source when sending out on the wire.
3553 		 */
3554 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3555 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3556 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3557 			ire = NULL;	/* Stored in ixa_ire */
3558 			error = EADDRNOTAVAIL;
3559 			goto bad_addr;
3560 		}
3561 
3562 		*src_addrp = src_addr;
3563 		ixa->ixa_src_generation = generation;
3564 	}
3565 
3566 	if (flags & IPDF_UNIQUE_DCE) {
3567 		/* Fallback to the default dce if allocation fails */
3568 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3569 		if (dce != NULL)
3570 			generation = dce->dce_generation;
3571 		else
3572 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3573 	} else {
3574 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3575 	}
3576 	ASSERT(dce != NULL);
3577 	if (ixa->ixa_dce != NULL)
3578 		dce_refrele_notr(ixa->ixa_dce);
3579 #ifdef DEBUG
3580 	dce_refhold_notr(dce);
3581 	dce_refrele(dce);
3582 #endif
3583 	ixa->ixa_dce = dce;
3584 	ixa->ixa_dce_generation = generation;
3585 
3586 	/*
3587 	 * Make sure we don't leave an unreachable ixa_nce in place
3588 	 * since ip_select_route is used when we unplumb i.e., remove
3589 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3590 	 */
3591 	nce = ixa->ixa_nce;
3592 	if (nce != NULL && nce->nce_is_condemned) {
3593 		nce_refrele(nce);
3594 		ixa->ixa_nce = NULL;
3595 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3596 	}
3597 
3598 	/*
3599 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3600 	 * However, we can't do it for IPv4 multicast or broadcast.
3601 	 */
3602 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3603 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3604 
3605 	/*
3606 	 * Set initial value for fragmentation limit. Either conn_ip_output
3607 	 * or ULP might updates it when there are routing changes.
3608 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3609 	 */
3610 	pmtu = ip_get_pmtu(ixa);
3611 	ixa->ixa_fragsize = pmtu;
3612 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3613 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3614 		ixa->ixa_pmtu = pmtu;
3615 
3616 	/*
3617 	 * Extract information useful for some transports.
3618 	 * First we look for DCE metrics. Then we take what we have in
3619 	 * the metrics in the route, where the offlink is used if we have
3620 	 * one.
3621 	 */
3622 	if (uinfo != NULL) {
3623 		bzero(uinfo, sizeof (*uinfo));
3624 
3625 		if (dce->dce_flags & DCEF_UINFO)
3626 			*uinfo = dce->dce_uinfo;
3627 
3628 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3629 
3630 		/* Allow ire_metrics to decrease the path MTU from above */
3631 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3632 			uinfo->iulp_mtu = pmtu;
3633 
3634 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3635 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3636 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3637 	}
3638 
3639 	if (ill != NULL)
3640 		ill_refrele(ill);
3641 
3642 	return (error);
3643 
3644 bad_addr:
3645 	if (ire != NULL)
3646 		ire_refrele(ire);
3647 
3648 	if (ill != NULL)
3649 		ill_refrele(ill);
3650 
3651 	/*
3652 	 * Make sure we don't leave an unreachable ixa_nce in place
3653 	 * since ip_select_route is used when we unplumb i.e., remove
3654 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3655 	 */
3656 	nce = ixa->ixa_nce;
3657 	if (nce != NULL && nce->nce_is_condemned) {
3658 		nce_refrele(nce);
3659 		ixa->ixa_nce = NULL;
3660 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3661 	}
3662 
3663 	return (error);
3664 }
3665 
3666 
3667 /*
3668  * Get the base MTU for the case when path MTU discovery is not used.
3669  * Takes the MTU of the IRE into account.
3670  */
3671 uint_t
3672 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3673 {
3674 	uint_t mtu = ill->ill_mtu;
3675 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3676 
3677 	if (iremtu != 0 && iremtu < mtu)
3678 		mtu = iremtu;
3679 
3680 	return (mtu);
3681 }
3682 
3683 /*
3684  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3685  * Assumes that ixa_ire, dce, and nce have already been set up.
3686  *
3687  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3688  * We avoid path MTU discovery if it is disabled with ndd.
3689  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3690  *
3691  * NOTE: We also used to turn it off for source routed packets. That
3692  * is no longer required since the dce is per final destination.
3693  */
3694 uint_t
3695 ip_get_pmtu(ip_xmit_attr_t *ixa)
3696 {
3697 	ip_stack_t	*ipst = ixa->ixa_ipst;
3698 	dce_t		*dce;
3699 	nce_t		*nce;
3700 	ire_t		*ire;
3701 	uint_t		pmtu;
3702 
3703 	ire = ixa->ixa_ire;
3704 	dce = ixa->ixa_dce;
3705 	nce = ixa->ixa_nce;
3706 
3707 	/*
3708 	 * If path MTU discovery has been turned off by ndd, then we ignore
3709 	 * any dce_pmtu and for IPv4 we will not set DF.
3710 	 */
3711 	if (!ipst->ips_ip_path_mtu_discovery)
3712 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3713 
3714 	pmtu = IP_MAXPACKET;
3715 	/*
3716 	 * Decide whether whether IPv4 sets DF
3717 	 * For IPv6 "no DF" means to use the 1280 mtu
3718 	 */
3719 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3720 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3721 	} else {
3722 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3723 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3724 			pmtu = IPV6_MIN_MTU;
3725 	}
3726 
3727 	/* Check if the PMTU is to old before we use it */
3728 	if ((dce->dce_flags & DCEF_PMTU) &&
3729 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3730 	    ipst->ips_ip_pathmtu_interval) {
3731 		/*
3732 		 * Older than 20 minutes. Drop the path MTU information.
3733 		 */
3734 		mutex_enter(&dce->dce_lock);
3735 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3736 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3737 		mutex_exit(&dce->dce_lock);
3738 		dce_increment_generation(dce);
3739 	}
3740 
3741 	/* The metrics on the route can lower the path MTU */
3742 	if (ire->ire_metrics.iulp_mtu != 0 &&
3743 	    ire->ire_metrics.iulp_mtu < pmtu)
3744 		pmtu = ire->ire_metrics.iulp_mtu;
3745 
3746 	/*
3747 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3748 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3749 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3750 	 */
3751 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3752 		if (dce->dce_flags & DCEF_PMTU) {
3753 			if (dce->dce_pmtu < pmtu)
3754 				pmtu = dce->dce_pmtu;
3755 
3756 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3757 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3758 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3759 			} else {
3760 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3761 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3762 			}
3763 		} else {
3764 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3765 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3766 		}
3767 	}
3768 
3769 	/*
3770 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3771 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3772 	 * mtu as IRE_LOOPBACK.
3773 	 */
3774 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3775 		uint_t loopback_mtu;
3776 
3777 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3778 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3779 
3780 		if (loopback_mtu < pmtu)
3781 			pmtu = loopback_mtu;
3782 	} else if (nce != NULL) {
3783 		/*
3784 		 * Make sure we don't exceed the interface MTU.
3785 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3786 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3787 		 * to tell the transport something larger than zero.
3788 		 */
3789 		if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3790 			pmtu = nce->nce_common->ncec_ill->ill_mtu;
3791 		if (nce->nce_common->ncec_ill != nce->nce_ill &&
3792 		    nce->nce_ill->ill_mtu < pmtu) {
3793 			/*
3794 			 * for interfaces in an IPMP group, the mtu of
3795 			 * the nce_ill (under_ill) could be different
3796 			 * from the mtu of the ncec_ill, so we take the
3797 			 * min of the two.
3798 			 */
3799 			pmtu = nce->nce_ill->ill_mtu;
3800 		}
3801 	}
3802 
3803 	/*
3804 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3805 	 * Only applies to IPv6.
3806 	 */
3807 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3808 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3809 			switch (ixa->ixa_use_min_mtu) {
3810 			case IPV6_USE_MIN_MTU_MULTICAST:
3811 				if (ire->ire_type & IRE_MULTICAST)
3812 					pmtu = IPV6_MIN_MTU;
3813 				break;
3814 			case IPV6_USE_MIN_MTU_ALWAYS:
3815 				pmtu = IPV6_MIN_MTU;
3816 				break;
3817 			case IPV6_USE_MIN_MTU_NEVER:
3818 				break;
3819 			}
3820 		} else {
3821 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3822 			if (ire->ire_type & IRE_MULTICAST)
3823 				pmtu = IPV6_MIN_MTU;
3824 		}
3825 	}
3826 
3827 	/*
3828 	 * After receiving an ICMPv6 "packet too big" message with a
3829 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3830 	 * will insert a 8-byte fragment header in every packet. We compensate
3831 	 * for those cases by returning a smaller path MTU to the ULP.
3832 	 *
3833 	 * In the case of CGTP then ip_output will add a fragment header.
3834 	 * Make sure there is room for it by telling a smaller number
3835 	 * to the transport.
3836 	 *
3837 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3838 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3839 	 * which is the size of the packets it can send.
3840 	 */
3841 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3842 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
3843 		    (ire->ire_flags & RTF_MULTIRT) ||
3844 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3845 			pmtu -= sizeof (ip6_frag_t);
3846 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3847 		}
3848 	}
3849 
3850 	return (pmtu);
3851 }
3852 
3853 /*
3854  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3855  * the final piece where we don't.  Return a pointer to the first mblk in the
3856  * result, and update the pointer to the next mblk to chew on.  If anything
3857  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3858  * NULL pointer.
3859  */
3860 mblk_t *
3861 ip_carve_mp(mblk_t **mpp, ssize_t len)
3862 {
3863 	mblk_t	*mp0;
3864 	mblk_t	*mp1;
3865 	mblk_t	*mp2;
3866 
3867 	if (!len || !mpp || !(mp0 = *mpp))
3868 		return (NULL);
3869 	/* If we aren't going to consume the first mblk, we need a dup. */
3870 	if (mp0->b_wptr - mp0->b_rptr > len) {
3871 		mp1 = dupb(mp0);
3872 		if (mp1) {
3873 			/* Partition the data between the two mblks. */
3874 			mp1->b_wptr = mp1->b_rptr + len;
3875 			mp0->b_rptr = mp1->b_wptr;
3876 			/*
3877 			 * after adjustments if mblk not consumed is now
3878 			 * unaligned, try to align it. If this fails free
3879 			 * all messages and let upper layer recover.
3880 			 */
3881 			if (!OK_32PTR(mp0->b_rptr)) {
3882 				if (!pullupmsg(mp0, -1)) {
3883 					freemsg(mp0);
3884 					freemsg(mp1);
3885 					*mpp = NULL;
3886 					return (NULL);
3887 				}
3888 			}
3889 		}
3890 		return (mp1);
3891 	}
3892 	/* Eat through as many mblks as we need to get len bytes. */
3893 	len -= mp0->b_wptr - mp0->b_rptr;
3894 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3895 		if (mp2->b_wptr - mp2->b_rptr > len) {
3896 			/*
3897 			 * We won't consume the entire last mblk.  Like
3898 			 * above, dup and partition it.
3899 			 */
3900 			mp1->b_cont = dupb(mp2);
3901 			mp1 = mp1->b_cont;
3902 			if (!mp1) {
3903 				/*
3904 				 * Trouble.  Rather than go to a lot of
3905 				 * trouble to clean up, we free the messages.
3906 				 * This won't be any worse than losing it on
3907 				 * the wire.
3908 				 */
3909 				freemsg(mp0);
3910 				freemsg(mp2);
3911 				*mpp = NULL;
3912 				return (NULL);
3913 			}
3914 			mp1->b_wptr = mp1->b_rptr + len;
3915 			mp2->b_rptr = mp1->b_wptr;
3916 			/*
3917 			 * after adjustments if mblk not consumed is now
3918 			 * unaligned, try to align it. If this fails free
3919 			 * all messages and let upper layer recover.
3920 			 */
3921 			if (!OK_32PTR(mp2->b_rptr)) {
3922 				if (!pullupmsg(mp2, -1)) {
3923 					freemsg(mp0);
3924 					freemsg(mp2);
3925 					*mpp = NULL;
3926 					return (NULL);
3927 				}
3928 			}
3929 			*mpp = mp2;
3930 			return (mp0);
3931 		}
3932 		/* Decrement len by the amount we just got. */
3933 		len -= mp2->b_wptr - mp2->b_rptr;
3934 	}
3935 	/*
3936 	 * len should be reduced to zero now.  If not our caller has
3937 	 * screwed up.
3938 	 */
3939 	if (len) {
3940 		/* Shouldn't happen! */
3941 		freemsg(mp0);
3942 		*mpp = NULL;
3943 		return (NULL);
3944 	}
3945 	/*
3946 	 * We consumed up to exactly the end of an mblk.  Detach the part
3947 	 * we are returning from the rest of the chain.
3948 	 */
3949 	mp1->b_cont = NULL;
3950 	*mpp = mp2;
3951 	return (mp0);
3952 }
3953 
3954 /* The ill stream is being unplumbed. Called from ip_close */
3955 int
3956 ip_modclose(ill_t *ill)
3957 {
3958 	boolean_t success;
3959 	ipsq_t	*ipsq;
3960 	ipif_t	*ipif;
3961 	queue_t	*q = ill->ill_rq;
3962 	ip_stack_t	*ipst = ill->ill_ipst;
3963 	int	i;
3964 	arl_ill_common_t *ai = ill->ill_common;
3965 
3966 	/*
3967 	 * The punlink prior to this may have initiated a capability
3968 	 * negotiation. But ipsq_enter will block until that finishes or
3969 	 * times out.
3970 	 */
3971 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
3972 
3973 	/*
3974 	 * Open/close/push/pop is guaranteed to be single threaded
3975 	 * per stream by STREAMS. FS guarantees that all references
3976 	 * from top are gone before close is called. So there can't
3977 	 * be another close thread that has set CONDEMNED on this ill.
3978 	 * and cause ipsq_enter to return failure.
3979 	 */
3980 	ASSERT(success);
3981 	ipsq = ill->ill_phyint->phyint_ipsq;
3982 
3983 	/*
3984 	 * Mark it condemned. No new reference will be made to this ill.
3985 	 * Lookup functions will return an error. Threads that try to
3986 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
3987 	 * that the refcnt will drop down to zero.
3988 	 */
3989 	mutex_enter(&ill->ill_lock);
3990 	ill->ill_state_flags |= ILL_CONDEMNED;
3991 	for (ipif = ill->ill_ipif; ipif != NULL;
3992 	    ipif = ipif->ipif_next) {
3993 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
3994 	}
3995 	/*
3996 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
3997 	 * returns  error if ILL_CONDEMNED is set
3998 	 */
3999 	cv_broadcast(&ill->ill_cv);
4000 	mutex_exit(&ill->ill_lock);
4001 
4002 	/*
4003 	 * Send all the deferred DLPI messages downstream which came in
4004 	 * during the small window right before ipsq_enter(). We do this
4005 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4006 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4007 	 */
4008 	ill_dlpi_send_deferred(ill);
4009 
4010 	/*
4011 	 * Shut down fragmentation reassembly.
4012 	 * ill_frag_timer won't start a timer again.
4013 	 * Now cancel any existing timer
4014 	 */
4015 	(void) untimeout(ill->ill_frag_timer_id);
4016 	(void) ill_frag_timeout(ill, 0);
4017 
4018 	/*
4019 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4020 	 * this ill. Then wait for the refcnts to drop to zero.
4021 	 * ill_is_freeable checks whether the ill is really quiescent.
4022 	 * Then make sure that threads that are waiting to enter the
4023 	 * ipsq have seen the error returned by ipsq_enter and have
4024 	 * gone away. Then we call ill_delete_tail which does the
4025 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4026 	 */
4027 	ill_delete(ill);
4028 	mutex_enter(&ill->ill_lock);
4029 	while (!ill_is_freeable(ill))
4030 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4031 
4032 	while (ill->ill_waiters)
4033 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4034 
4035 	mutex_exit(&ill->ill_lock);
4036 
4037 	/*
4038 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4039 	 * it held until the end of the function since the cleanup
4040 	 * below needs to be able to use the ip_stack_t.
4041 	 */
4042 	netstack_hold(ipst->ips_netstack);
4043 
4044 	/* qprocsoff is done via ill_delete_tail */
4045 	ill_delete_tail(ill);
4046 	/*
4047 	 * synchronously wait for arp stream to unbind. After this, we
4048 	 * cannot get any data packets up from the driver.
4049 	 */
4050 	arp_unbind_complete(ill);
4051 	ASSERT(ill->ill_ipst == NULL);
4052 
4053 	/*
4054 	 * Walk through all conns and qenable those that have queued data.
4055 	 * Close synchronization needs this to
4056 	 * be done to ensure that all upper layers blocked
4057 	 * due to flow control to the closing device
4058 	 * get unblocked.
4059 	 */
4060 	ip1dbg(("ip_wsrv: walking\n"));
4061 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4062 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4063 	}
4064 
4065 	/*
4066 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4067 	 * stream is being torn down before ARP was plumbed (e.g.,
4068 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4069 	 * an error
4070 	 */
4071 	if (ai != NULL) {
4072 		ASSERT(!ill->ill_isv6);
4073 		mutex_enter(&ai->ai_lock);
4074 		ai->ai_ill = NULL;
4075 		if (ai->ai_arl == NULL) {
4076 			mutex_destroy(&ai->ai_lock);
4077 			kmem_free(ai, sizeof (*ai));
4078 		} else {
4079 			cv_signal(&ai->ai_ill_unplumb_done);
4080 			mutex_exit(&ai->ai_lock);
4081 		}
4082 	}
4083 
4084 	mutex_enter(&ipst->ips_ip_mi_lock);
4085 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4086 	mutex_exit(&ipst->ips_ip_mi_lock);
4087 
4088 	/*
4089 	 * credp could be null if the open didn't succeed and ip_modopen
4090 	 * itself calls ip_close.
4091 	 */
4092 	if (ill->ill_credp != NULL)
4093 		crfree(ill->ill_credp);
4094 
4095 	mutex_destroy(&ill->ill_saved_ire_lock);
4096 	mutex_destroy(&ill->ill_lock);
4097 	rw_destroy(&ill->ill_mcast_lock);
4098 	mutex_destroy(&ill->ill_mcast_serializer);
4099 	list_destroy(&ill->ill_nce);
4100 
4101 	/*
4102 	 * Now we are done with the module close pieces that
4103 	 * need the netstack_t.
4104 	 */
4105 	netstack_rele(ipst->ips_netstack);
4106 
4107 	mi_close_free((IDP)ill);
4108 	q->q_ptr = WR(q)->q_ptr = NULL;
4109 
4110 	ipsq_exit(ipsq);
4111 
4112 	return (0);
4113 }
4114 
4115 /*
4116  * This is called as part of close() for IP, UDP, ICMP, and RTS
4117  * in order to quiesce the conn.
4118  */
4119 void
4120 ip_quiesce_conn(conn_t *connp)
4121 {
4122 	boolean_t	drain_cleanup_reqd = B_FALSE;
4123 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4124 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4125 	ip_stack_t	*ipst;
4126 
4127 	ASSERT(!IPCL_IS_TCP(connp));
4128 	ipst = connp->conn_netstack->netstack_ip;
4129 
4130 	/*
4131 	 * Mark the conn as closing, and this conn must not be
4132 	 * inserted in future into any list. Eg. conn_drain_insert(),
4133 	 * won't insert this conn into the conn_drain_list.
4134 	 *
4135 	 * conn_idl, and conn_ilg cannot get set henceforth.
4136 	 */
4137 	mutex_enter(&connp->conn_lock);
4138 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4139 	connp->conn_state_flags |= CONN_CLOSING;
4140 	if (connp->conn_idl != NULL)
4141 		drain_cleanup_reqd = B_TRUE;
4142 	if (connp->conn_oper_pending_ill != NULL)
4143 		conn_ioctl_cleanup_reqd = B_TRUE;
4144 	if (connp->conn_dhcpinit_ill != NULL) {
4145 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4146 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4147 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4148 		connp->conn_dhcpinit_ill = NULL;
4149 	}
4150 	if (connp->conn_ilg != NULL)
4151 		ilg_cleanup_reqd = B_TRUE;
4152 	mutex_exit(&connp->conn_lock);
4153 
4154 	if (conn_ioctl_cleanup_reqd)
4155 		conn_ioctl_cleanup(connp);
4156 
4157 	if (is_system_labeled() && connp->conn_anon_port) {
4158 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4159 		    connp->conn_mlp_type, connp->conn_proto,
4160 		    ntohs(connp->conn_lport), B_FALSE);
4161 		connp->conn_anon_port = 0;
4162 	}
4163 	connp->conn_mlp_type = mlptSingle;
4164 
4165 	/*
4166 	 * Remove this conn from any fanout list it is on.
4167 	 * and then wait for any threads currently operating
4168 	 * on this endpoint to finish
4169 	 */
4170 	ipcl_hash_remove(connp);
4171 
4172 	/*
4173 	 * Remove this conn from the drain list, and do
4174 	 * any other cleanup that may be required.
4175 	 * (Only non-tcp conns may have a non-null conn_idl.
4176 	 * TCP conns are never flow controlled, and
4177 	 * conn_idl will be null)
4178 	 */
4179 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4180 		mutex_enter(&connp->conn_idl->idl_lock);
4181 		conn_drain(connp, B_TRUE);
4182 		mutex_exit(&connp->conn_idl->idl_lock);
4183 	}
4184 
4185 	if (connp == ipst->ips_ip_g_mrouter)
4186 		(void) ip_mrouter_done(ipst);
4187 
4188 	if (ilg_cleanup_reqd)
4189 		ilg_delete_all(connp);
4190 
4191 	/*
4192 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4193 	 * callers from write side can't be there now because close
4194 	 * is in progress. The only other caller is ipcl_walk
4195 	 * which checks for the condemned flag.
4196 	 */
4197 	mutex_enter(&connp->conn_lock);
4198 	connp->conn_state_flags |= CONN_CONDEMNED;
4199 	while (connp->conn_ref != 1)
4200 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4201 	connp->conn_state_flags |= CONN_QUIESCED;
4202 	mutex_exit(&connp->conn_lock);
4203 }
4204 
4205 /* ARGSUSED */
4206 int
4207 ip_close(queue_t *q, int flags)
4208 {
4209 	conn_t		*connp;
4210 
4211 	/*
4212 	 * Call the appropriate delete routine depending on whether this is
4213 	 * a module or device.
4214 	 */
4215 	if (WR(q)->q_next != NULL) {
4216 		/* This is a module close */
4217 		return (ip_modclose((ill_t *)q->q_ptr));
4218 	}
4219 
4220 	connp = q->q_ptr;
4221 	ip_quiesce_conn(connp);
4222 
4223 	qprocsoff(q);
4224 
4225 	/*
4226 	 * Now we are truly single threaded on this stream, and can
4227 	 * delete the things hanging off the connp, and finally the connp.
4228 	 * We removed this connp from the fanout list, it cannot be
4229 	 * accessed thru the fanouts, and we already waited for the
4230 	 * conn_ref to drop to 0. We are already in close, so
4231 	 * there cannot be any other thread from the top. qprocsoff
4232 	 * has completed, and service has completed or won't run in
4233 	 * future.
4234 	 */
4235 	ASSERT(connp->conn_ref == 1);
4236 
4237 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4238 
4239 	connp->conn_ref--;
4240 	ipcl_conn_destroy(connp);
4241 
4242 	q->q_ptr = WR(q)->q_ptr = NULL;
4243 	return (0);
4244 }
4245 
4246 /*
4247  * Wapper around putnext() so that ip_rts_request can merely use
4248  * conn_recv.
4249  */
4250 /*ARGSUSED2*/
4251 static void
4252 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4253 {
4254 	conn_t *connp = (conn_t *)arg1;
4255 
4256 	putnext(connp->conn_rq, mp);
4257 }
4258 
4259 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4260 /* ARGSUSED */
4261 static void
4262 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4263 {
4264 	freemsg(mp);
4265 }
4266 
4267 /*
4268  * Called when the module is about to be unloaded
4269  */
4270 void
4271 ip_ddi_destroy(void)
4272 {
4273 	tnet_fini();
4274 
4275 	icmp_ddi_g_destroy();
4276 	rts_ddi_g_destroy();
4277 	udp_ddi_g_destroy();
4278 	sctp_ddi_g_destroy();
4279 	tcp_ddi_g_destroy();
4280 	ilb_ddi_g_destroy();
4281 	dce_g_destroy();
4282 	ipsec_policy_g_destroy();
4283 	ipcl_g_destroy();
4284 	ip_net_g_destroy();
4285 	ip_ire_g_fini();
4286 	inet_minor_destroy(ip_minor_arena_sa);
4287 #if defined(_LP64)
4288 	inet_minor_destroy(ip_minor_arena_la);
4289 #endif
4290 
4291 #ifdef DEBUG
4292 	list_destroy(&ip_thread_list);
4293 	rw_destroy(&ip_thread_rwlock);
4294 	tsd_destroy(&ip_thread_data);
4295 #endif
4296 
4297 	netstack_unregister(NS_IP);
4298 }
4299 
4300 /*
4301  * First step in cleanup.
4302  */
4303 /* ARGSUSED */
4304 static void
4305 ip_stack_shutdown(netstackid_t stackid, void *arg)
4306 {
4307 	ip_stack_t *ipst = (ip_stack_t *)arg;
4308 
4309 #ifdef NS_DEBUG
4310 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4311 #endif
4312 
4313 	/*
4314 	 * Perform cleanup for special interfaces (loopback and IPMP).
4315 	 */
4316 	ip_interface_cleanup(ipst);
4317 
4318 	/*
4319 	 * The *_hook_shutdown()s start the process of notifying any
4320 	 * consumers that things are going away.... nothing is destroyed.
4321 	 */
4322 	ipv4_hook_shutdown(ipst);
4323 	ipv6_hook_shutdown(ipst);
4324 	arp_hook_shutdown(ipst);
4325 
4326 	mutex_enter(&ipst->ips_capab_taskq_lock);
4327 	ipst->ips_capab_taskq_quit = B_TRUE;
4328 	cv_signal(&ipst->ips_capab_taskq_cv);
4329 	mutex_exit(&ipst->ips_capab_taskq_lock);
4330 }
4331 
4332 /*
4333  * Free the IP stack instance.
4334  */
4335 static void
4336 ip_stack_fini(netstackid_t stackid, void *arg)
4337 {
4338 	ip_stack_t *ipst = (ip_stack_t *)arg;
4339 	int ret;
4340 
4341 #ifdef NS_DEBUG
4342 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4343 #endif
4344 	/*
4345 	 * At this point, all of the notifications that the events and
4346 	 * protocols are going away have been run, meaning that we can
4347 	 * now set about starting to clean things up.
4348 	 */
4349 	ipobs_fini(ipst);
4350 	ipv4_hook_destroy(ipst);
4351 	ipv6_hook_destroy(ipst);
4352 	arp_hook_destroy(ipst);
4353 	ip_net_destroy(ipst);
4354 
4355 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4356 	cv_destroy(&ipst->ips_capab_taskq_cv);
4357 
4358 	ipmp_destroy(ipst);
4359 	rw_destroy(&ipst->ips_srcid_lock);
4360 
4361 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4362 	ipst->ips_ip_mibkp = NULL;
4363 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4364 	ipst->ips_icmp_mibkp = NULL;
4365 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4366 	ipst->ips_ip_kstat = NULL;
4367 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4368 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4369 	ipst->ips_ip6_kstat = NULL;
4370 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4371 
4372 	kmem_free(ipst->ips_propinfo_tbl,
4373 	    ip_propinfo_count * sizeof (mod_prop_info_t));
4374 	ipst->ips_propinfo_tbl = NULL;
4375 
4376 	dce_stack_destroy(ipst);
4377 	ip_mrouter_stack_destroy(ipst);
4378 
4379 	mutex_destroy(&ipst->ips_ip_mi_lock);
4380 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4381 
4382 	ret = untimeout(ipst->ips_igmp_timeout_id);
4383 	if (ret == -1) {
4384 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4385 	} else {
4386 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4387 		ipst->ips_igmp_timeout_id = 0;
4388 	}
4389 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4390 	if (ret == -1) {
4391 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4392 	} else {
4393 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4394 		ipst->ips_igmp_slowtimeout_id = 0;
4395 	}
4396 	ret = untimeout(ipst->ips_mld_timeout_id);
4397 	if (ret == -1) {
4398 		ASSERT(ipst->ips_mld_timeout_id == 0);
4399 	} else {
4400 		ASSERT(ipst->ips_mld_timeout_id != 0);
4401 		ipst->ips_mld_timeout_id = 0;
4402 	}
4403 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4404 	if (ret == -1) {
4405 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4406 	} else {
4407 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4408 		ipst->ips_mld_slowtimeout_id = 0;
4409 	}
4410 
4411 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4412 	mutex_destroy(&ipst->ips_mld_timer_lock);
4413 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4414 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4415 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4416 	rw_destroy(&ipst->ips_ill_g_lock);
4417 
4418 	ip_ire_fini(ipst);
4419 	ip6_asp_free(ipst);
4420 	conn_drain_fini(ipst);
4421 	ipcl_destroy(ipst);
4422 
4423 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4424 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4425 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4426 	ipst->ips_ndp4 = NULL;
4427 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4428 	ipst->ips_ndp6 = NULL;
4429 
4430 	if (ipst->ips_loopback_ksp != NULL) {
4431 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4432 		ipst->ips_loopback_ksp = NULL;
4433 	}
4434 
4435 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4436 	ipst->ips_phyint_g_list = NULL;
4437 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4438 	ipst->ips_ill_g_heads = NULL;
4439 
4440 	ldi_ident_release(ipst->ips_ldi_ident);
4441 	kmem_free(ipst, sizeof (*ipst));
4442 }
4443 
4444 /*
4445  * This function is called from the TSD destructor, and is used to debug
4446  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4447  * details.
4448  */
4449 static void
4450 ip_thread_exit(void *phash)
4451 {
4452 	th_hash_t *thh = phash;
4453 
4454 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4455 	list_remove(&ip_thread_list, thh);
4456 	rw_exit(&ip_thread_rwlock);
4457 	mod_hash_destroy_hash(thh->thh_hash);
4458 	kmem_free(thh, sizeof (*thh));
4459 }
4460 
4461 /*
4462  * Called when the IP kernel module is loaded into the kernel
4463  */
4464 void
4465 ip_ddi_init(void)
4466 {
4467 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4468 
4469 	/*
4470 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4471 	 * initial devices: ip, ip6, tcp, tcp6.
4472 	 */
4473 	/*
4474 	 * If this is a 64-bit kernel, then create two separate arenas -
4475 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4476 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4477 	 */
4478 	ip_minor_arena_la = NULL;
4479 	ip_minor_arena_sa = NULL;
4480 #if defined(_LP64)
4481 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4482 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4483 		cmn_err(CE_PANIC,
4484 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4485 	}
4486 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4487 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4488 		cmn_err(CE_PANIC,
4489 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4490 	}
4491 #else
4492 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4493 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4494 		cmn_err(CE_PANIC,
4495 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4496 	}
4497 #endif
4498 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4499 
4500 	ipcl_g_init();
4501 	ip_ire_g_init();
4502 	ip_net_g_init();
4503 
4504 #ifdef DEBUG
4505 	tsd_create(&ip_thread_data, ip_thread_exit);
4506 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4507 	list_create(&ip_thread_list, sizeof (th_hash_t),
4508 	    offsetof(th_hash_t, thh_link));
4509 #endif
4510 	ipsec_policy_g_init();
4511 	tcp_ddi_g_init();
4512 	sctp_ddi_g_init();
4513 	dce_g_init();
4514 
4515 	/*
4516 	 * We want to be informed each time a stack is created or
4517 	 * destroyed in the kernel, so we can maintain the
4518 	 * set of udp_stack_t's.
4519 	 */
4520 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4521 	    ip_stack_fini);
4522 
4523 	tnet_init();
4524 
4525 	udp_ddi_g_init();
4526 	rts_ddi_g_init();
4527 	icmp_ddi_g_init();
4528 	ilb_ddi_g_init();
4529 }
4530 
4531 /*
4532  * Initialize the IP stack instance.
4533  */
4534 static void *
4535 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4536 {
4537 	ip_stack_t	*ipst;
4538 	size_t		arrsz;
4539 	major_t		major;
4540 
4541 #ifdef NS_DEBUG
4542 	printf("ip_stack_init(stack %d)\n", stackid);
4543 #endif
4544 
4545 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4546 	ipst->ips_netstack = ns;
4547 
4548 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4549 	    KM_SLEEP);
4550 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4551 	    KM_SLEEP);
4552 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4553 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4554 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4555 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4556 
4557 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4558 	ipst->ips_igmp_deferred_next = INFINITY;
4559 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4560 	ipst->ips_mld_deferred_next = INFINITY;
4561 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4562 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4563 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4564 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4565 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4566 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4567 
4568 	ipcl_init(ipst);
4569 	ip_ire_init(ipst);
4570 	ip6_asp_init(ipst);
4571 	ipif_init(ipst);
4572 	conn_drain_init(ipst);
4573 	ip_mrouter_stack_init(ipst);
4574 	dce_stack_init(ipst);
4575 
4576 	ipst->ips_ip_multirt_log_interval = 1000;
4577 
4578 	ipst->ips_ill_index = 1;
4579 
4580 	ipst->ips_saved_ip_forwarding = -1;
4581 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4582 
4583 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4584 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4585 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4586 
4587 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4588 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4589 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4590 	ipst->ips_ip6_kstat =
4591 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4592 
4593 	ipst->ips_ip_src_id = 1;
4594 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4595 
4596 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4597 
4598 	ip_net_init(ipst, ns);
4599 	ipv4_hook_init(ipst);
4600 	ipv6_hook_init(ipst);
4601 	arp_hook_init(ipst);
4602 	ipmp_init(ipst);
4603 	ipobs_init(ipst);
4604 
4605 	/*
4606 	 * Create the taskq dispatcher thread and initialize related stuff.
4607 	 */
4608 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4609 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4610 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4611 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4612 
4613 	major = mod_name_to_major(INET_NAME);
4614 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4615 	return (ipst);
4616 }
4617 
4618 /*
4619  * Allocate and initialize a DLPI template of the specified length.  (May be
4620  * called as writer.)
4621  */
4622 mblk_t *
4623 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4624 {
4625 	mblk_t	*mp;
4626 
4627 	mp = allocb(len, BPRI_MED);
4628 	if (!mp)
4629 		return (NULL);
4630 
4631 	/*
4632 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4633 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4634 	 * that other DLPI are M_PROTO.
4635 	 */
4636 	if (prim == DL_INFO_REQ) {
4637 		mp->b_datap->db_type = M_PCPROTO;
4638 	} else {
4639 		mp->b_datap->db_type = M_PROTO;
4640 	}
4641 
4642 	mp->b_wptr = mp->b_rptr + len;
4643 	bzero(mp->b_rptr, len);
4644 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4645 	return (mp);
4646 }
4647 
4648 /*
4649  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4650  */
4651 mblk_t *
4652 ip_dlnotify_alloc(uint_t notification, uint_t data)
4653 {
4654 	dl_notify_ind_t	*notifyp;
4655 	mblk_t		*mp;
4656 
4657 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4658 		return (NULL);
4659 
4660 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4661 	notifyp->dl_notification = notification;
4662 	notifyp->dl_data = data;
4663 	return (mp);
4664 }
4665 
4666 /*
4667  * Debug formatting routine.  Returns a character string representation of the
4668  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4669  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4670  *
4671  * Once the ndd table-printing interfaces are removed, this can be changed to
4672  * standard dotted-decimal form.
4673  */
4674 char *
4675 ip_dot_addr(ipaddr_t addr, char *buf)
4676 {
4677 	uint8_t *ap = (uint8_t *)&addr;
4678 
4679 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4680 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4681 	return (buf);
4682 }
4683 
4684 /*
4685  * Write the given MAC address as a printable string in the usual colon-
4686  * separated format.
4687  */
4688 const char *
4689 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4690 {
4691 	char *bp;
4692 
4693 	if (alen == 0 || buflen < 4)
4694 		return ("?");
4695 	bp = buf;
4696 	for (;;) {
4697 		/*
4698 		 * If there are more MAC address bytes available, but we won't
4699 		 * have any room to print them, then add "..." to the string
4700 		 * instead.  See below for the 'magic number' explanation.
4701 		 */
4702 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4703 			(void) strcpy(bp, "...");
4704 			break;
4705 		}
4706 		(void) sprintf(bp, "%02x", *addr++);
4707 		bp += 2;
4708 		if (--alen == 0)
4709 			break;
4710 		*bp++ = ':';
4711 		buflen -= 3;
4712 		/*
4713 		 * At this point, based on the first 'if' statement above,
4714 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4715 		 * buflen >= 4.  The first case leaves room for the final "xx"
4716 		 * number and trailing NUL byte.  The second leaves room for at
4717 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4718 		 * that statement.
4719 		 */
4720 	}
4721 	return (buf);
4722 }
4723 
4724 /*
4725  * Called when it is conceptually a ULP that would sent the packet
4726  * e.g., port unreachable and protocol unreachable. Check that the packet
4727  * would have passed the IPsec global policy before sending the error.
4728  *
4729  * Send an ICMP error after patching up the packet appropriately.
4730  * Uses ip_drop_input and bumps the appropriate MIB.
4731  */
4732 void
4733 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4734     ip_recv_attr_t *ira)
4735 {
4736 	ipha_t		*ipha;
4737 	boolean_t	secure;
4738 	ill_t		*ill = ira->ira_ill;
4739 	ip_stack_t	*ipst = ill->ill_ipst;
4740 	netstack_t	*ns = ipst->ips_netstack;
4741 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4742 
4743 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4744 
4745 	/*
4746 	 * We are generating an icmp error for some inbound packet.
4747 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4748 	 * Before we generate an error, check with global policy
4749 	 * to see whether this is allowed to enter the system. As
4750 	 * there is no "conn", we are checking with global policy.
4751 	 */
4752 	ipha = (ipha_t *)mp->b_rptr;
4753 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4754 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4755 		if (mp == NULL)
4756 			return;
4757 	}
4758 
4759 	/* We never send errors for protocols that we do implement */
4760 	if (ira->ira_protocol == IPPROTO_ICMP ||
4761 	    ira->ira_protocol == IPPROTO_IGMP) {
4762 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4763 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4764 		freemsg(mp);
4765 		return;
4766 	}
4767 	/*
4768 	 * Have to correct checksum since
4769 	 * the packet might have been
4770 	 * fragmented and the reassembly code in ip_rput
4771 	 * does not restore the IP checksum.
4772 	 */
4773 	ipha->ipha_hdr_checksum = 0;
4774 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4775 
4776 	switch (icmp_type) {
4777 	case ICMP_DEST_UNREACHABLE:
4778 		switch (icmp_code) {
4779 		case ICMP_PROTOCOL_UNREACHABLE:
4780 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4781 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4782 			break;
4783 		case ICMP_PORT_UNREACHABLE:
4784 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4785 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4786 			break;
4787 		}
4788 
4789 		icmp_unreachable(mp, icmp_code, ira);
4790 		break;
4791 	default:
4792 #ifdef DEBUG
4793 		panic("ip_fanout_send_icmp_v4: wrong type");
4794 		/*NOTREACHED*/
4795 #else
4796 		freemsg(mp);
4797 		break;
4798 #endif
4799 	}
4800 }
4801 
4802 /*
4803  * Used to send an ICMP error message when a packet is received for
4804  * a protocol that is not supported. The mblk passed as argument
4805  * is consumed by this function.
4806  */
4807 void
4808 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4809 {
4810 	ipha_t		*ipha;
4811 
4812 	ipha = (ipha_t *)mp->b_rptr;
4813 	if (ira->ira_flags & IRAF_IS_IPV4) {
4814 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4815 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4816 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4817 	} else {
4818 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4819 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4820 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4821 	}
4822 }
4823 
4824 /*
4825  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4826  * Handles IPv4 and IPv6.
4827  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4828  * Caller is responsible for dropping references to the conn.
4829  */
4830 void
4831 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4832     ip_recv_attr_t *ira)
4833 {
4834 	ill_t		*ill = ira->ira_ill;
4835 	ip_stack_t	*ipst = ill->ill_ipst;
4836 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4837 	boolean_t	secure;
4838 	uint_t		protocol = ira->ira_protocol;
4839 	iaflags_t	iraflags = ira->ira_flags;
4840 	queue_t		*rq;
4841 
4842 	secure = iraflags & IRAF_IPSEC_SECURE;
4843 
4844 	rq = connp->conn_rq;
4845 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4846 		switch (protocol) {
4847 		case IPPROTO_ICMPV6:
4848 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4849 			break;
4850 		case IPPROTO_ICMP:
4851 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4852 			break;
4853 		default:
4854 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4855 			break;
4856 		}
4857 		freemsg(mp);
4858 		return;
4859 	}
4860 
4861 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4862 
4863 	if (((iraflags & IRAF_IS_IPV4) ?
4864 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4865 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4866 	    secure) {
4867 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4868 		    ip6h, ira);
4869 		if (mp == NULL) {
4870 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4871 			/* Note that mp is NULL */
4872 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4873 			return;
4874 		}
4875 	}
4876 
4877 	if (iraflags & IRAF_ICMP_ERROR) {
4878 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4879 	} else {
4880 		ill_t *rill = ira->ira_rill;
4881 
4882 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4883 		ira->ira_ill = ira->ira_rill = NULL;
4884 		/* Send it upstream */
4885 		(connp->conn_recv)(connp, mp, NULL, ira);
4886 		ira->ira_ill = ill;
4887 		ira->ira_rill = rill;
4888 	}
4889 }
4890 
4891 /*
4892  * Handle protocols with which IP is less intimate.  There
4893  * can be more than one stream bound to a particular
4894  * protocol.  When this is the case, normally each one gets a copy
4895  * of any incoming packets.
4896  *
4897  * IPsec NOTE :
4898  *
4899  * Don't allow a secure packet going up a non-secure connection.
4900  * We don't allow this because
4901  *
4902  * 1) Reply might go out in clear which will be dropped at
4903  *    the sending side.
4904  * 2) If the reply goes out in clear it will give the
4905  *    adversary enough information for getting the key in
4906  *    most of the cases.
4907  *
4908  * Moreover getting a secure packet when we expect clear
4909  * implies that SA's were added without checking for
4910  * policy on both ends. This should not happen once ISAKMP
4911  * is used to negotiate SAs as SAs will be added only after
4912  * verifying the policy.
4913  *
4914  * Zones notes:
4915  * Earlier in ip_input on a system with multiple shared-IP zones we
4916  * duplicate the multicast and broadcast packets and send them up
4917  * with each explicit zoneid that exists on that ill.
4918  * This means that here we can match the zoneid with SO_ALLZONES being special.
4919  */
4920 void
4921 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
4922 {
4923 	mblk_t		*mp1;
4924 	ipaddr_t	laddr;
4925 	conn_t		*connp, *first_connp, *next_connp;
4926 	connf_t		*connfp;
4927 	ill_t		*ill = ira->ira_ill;
4928 	ip_stack_t	*ipst = ill->ill_ipst;
4929 
4930 	laddr = ipha->ipha_dst;
4931 
4932 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
4933 	mutex_enter(&connfp->connf_lock);
4934 	connp = connfp->connf_head;
4935 	for (connp = connfp->connf_head; connp != NULL;
4936 	    connp = connp->conn_next) {
4937 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4938 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4939 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4940 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
4941 			break;
4942 		}
4943 	}
4944 
4945 	if (connp == NULL) {
4946 		/*
4947 		 * No one bound to these addresses.  Is
4948 		 * there a client that wants all
4949 		 * unclaimed datagrams?
4950 		 */
4951 		mutex_exit(&connfp->connf_lock);
4952 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4953 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4954 		return;
4955 	}
4956 
4957 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
4958 
4959 	CONN_INC_REF(connp);
4960 	first_connp = connp;
4961 	connp = connp->conn_next;
4962 
4963 	for (;;) {
4964 		while (connp != NULL) {
4965 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4966 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4967 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4968 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
4969 			    ira, connp)))
4970 				break;
4971 			connp = connp->conn_next;
4972 		}
4973 
4974 		if (connp == NULL) {
4975 			/* No more interested clients */
4976 			connp = first_connp;
4977 			break;
4978 		}
4979 		if (((mp1 = dupmsg(mp)) == NULL) &&
4980 		    ((mp1 = copymsg(mp)) == NULL)) {
4981 			/* Memory allocation failed */
4982 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4983 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4984 			connp = first_connp;
4985 			break;
4986 		}
4987 
4988 		CONN_INC_REF(connp);
4989 		mutex_exit(&connfp->connf_lock);
4990 
4991 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
4992 		    ira);
4993 
4994 		mutex_enter(&connfp->connf_lock);
4995 		/* Follow the next pointer before releasing the conn. */
4996 		next_connp = connp->conn_next;
4997 		CONN_DEC_REF(connp);
4998 		connp = next_connp;
4999 	}
5000 
5001 	/* Last one.  Send it upstream. */
5002 	mutex_exit(&connfp->connf_lock);
5003 
5004 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5005 
5006 	CONN_DEC_REF(connp);
5007 }
5008 
5009 /*
5010  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5011  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5012  * is not consumed.
5013  *
5014  * One of three things can happen, all of which affect the passed-in mblk:
5015  *
5016  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5017  *
5018  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5019  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5020  *
5021  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5022  */
5023 mblk_t *
5024 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5025 {
5026 	int shift, plen, iph_len;
5027 	ipha_t *ipha;
5028 	udpha_t *udpha;
5029 	uint32_t *spi;
5030 	uint32_t esp_ports;
5031 	uint8_t *orptr;
5032 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5033 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5034 
5035 	ipha = (ipha_t *)mp->b_rptr;
5036 	iph_len = ira->ira_ip_hdr_length;
5037 	plen = ira->ira_pktlen;
5038 
5039 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5040 		/*
5041 		 * Most likely a keepalive for the benefit of an intervening
5042 		 * NAT.  These aren't for us, per se, so drop it.
5043 		 *
5044 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5045 		 * byte packets (keepalives are 1-byte), but we'll drop them
5046 		 * also.
5047 		 */
5048 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5049 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5050 		return (NULL);
5051 	}
5052 
5053 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5054 		/* might as well pull it all up - it might be ESP. */
5055 		if (!pullupmsg(mp, -1)) {
5056 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5057 			    DROPPER(ipss, ipds_esp_nomem),
5058 			    &ipss->ipsec_dropper);
5059 			return (NULL);
5060 		}
5061 
5062 		ipha = (ipha_t *)mp->b_rptr;
5063 	}
5064 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5065 	if (*spi == 0) {
5066 		/* UDP packet - remove 0-spi. */
5067 		shift = sizeof (uint32_t);
5068 	} else {
5069 		/* ESP-in-UDP packet - reduce to ESP. */
5070 		ipha->ipha_protocol = IPPROTO_ESP;
5071 		shift = sizeof (udpha_t);
5072 	}
5073 
5074 	/* Fix IP header */
5075 	ira->ira_pktlen = (plen - shift);
5076 	ipha->ipha_length = htons(ira->ira_pktlen);
5077 	ipha->ipha_hdr_checksum = 0;
5078 
5079 	orptr = mp->b_rptr;
5080 	mp->b_rptr += shift;
5081 
5082 	udpha = (udpha_t *)(orptr + iph_len);
5083 	if (*spi == 0) {
5084 		ASSERT((uint8_t *)ipha == orptr);
5085 		udpha->uha_length = htons(plen - shift - iph_len);
5086 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5087 		esp_ports = 0;
5088 	} else {
5089 		esp_ports = *((uint32_t *)udpha);
5090 		ASSERT(esp_ports != 0);
5091 	}
5092 	ovbcopy(orptr, orptr + shift, iph_len);
5093 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5094 		ipha = (ipha_t *)(orptr + shift);
5095 
5096 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5097 		ira->ira_esp_udp_ports = esp_ports;
5098 		ip_fanout_v4(mp, ipha, ira);
5099 		return (NULL);
5100 	}
5101 	return (mp);
5102 }
5103 
5104 /*
5105  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5106  * Handles IPv4 and IPv6.
5107  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5108  * Caller is responsible for dropping references to the conn.
5109  */
5110 void
5111 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5112     ip_recv_attr_t *ira)
5113 {
5114 	ill_t		*ill = ira->ira_ill;
5115 	ip_stack_t	*ipst = ill->ill_ipst;
5116 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5117 	boolean_t	secure;
5118 	iaflags_t	iraflags = ira->ira_flags;
5119 
5120 	secure = iraflags & IRAF_IPSEC_SECURE;
5121 
5122 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5123 	    !canputnext(connp->conn_rq)) {
5124 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5125 		freemsg(mp);
5126 		return;
5127 	}
5128 
5129 	if (((iraflags & IRAF_IS_IPV4) ?
5130 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5131 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5132 	    secure) {
5133 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5134 		    ip6h, ira);
5135 		if (mp == NULL) {
5136 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5137 			/* Note that mp is NULL */
5138 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5139 			return;
5140 		}
5141 	}
5142 
5143 	/*
5144 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5145 	 * check. Only ip_fanout_v4 has that check.
5146 	 */
5147 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5148 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5149 	} else {
5150 		ill_t *rill = ira->ira_rill;
5151 
5152 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5153 		ira->ira_ill = ira->ira_rill = NULL;
5154 		/* Send it upstream */
5155 		(connp->conn_recv)(connp, mp, NULL, ira);
5156 		ira->ira_ill = ill;
5157 		ira->ira_rill = rill;
5158 	}
5159 }
5160 
5161 /*
5162  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5163  * (Unicast fanout is handled in ip_input_v4.)
5164  *
5165  * If SO_REUSEADDR is set all multicast and broadcast packets
5166  * will be delivered to all conns bound to the same port.
5167  *
5168  * If there is at least one matching AF_INET receiver, then we will
5169  * ignore any AF_INET6 receivers.
5170  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5171  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5172  * packets.
5173  *
5174  * Zones notes:
5175  * Earlier in ip_input on a system with multiple shared-IP zones we
5176  * duplicate the multicast and broadcast packets and send them up
5177  * with each explicit zoneid that exists on that ill.
5178  * This means that here we can match the zoneid with SO_ALLZONES being special.
5179  */
5180 void
5181 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5182     ip_recv_attr_t *ira)
5183 {
5184 	ipaddr_t	laddr;
5185 	in6_addr_t	v6faddr;
5186 	conn_t		*connp;
5187 	connf_t		*connfp;
5188 	ipaddr_t	faddr;
5189 	ill_t		*ill = ira->ira_ill;
5190 	ip_stack_t	*ipst = ill->ill_ipst;
5191 
5192 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5193 
5194 	laddr = ipha->ipha_dst;
5195 	faddr = ipha->ipha_src;
5196 
5197 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5198 	mutex_enter(&connfp->connf_lock);
5199 	connp = connfp->connf_head;
5200 
5201 	/*
5202 	 * If SO_REUSEADDR has been set on the first we send the
5203 	 * packet to all clients that have joined the group and
5204 	 * match the port.
5205 	 */
5206 	while (connp != NULL) {
5207 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5208 		    conn_wantpacket(connp, ira, ipha) &&
5209 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5210 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5211 			break;
5212 		connp = connp->conn_next;
5213 	}
5214 
5215 	if (connp == NULL)
5216 		goto notfound;
5217 
5218 	CONN_INC_REF(connp);
5219 
5220 	if (connp->conn_reuseaddr) {
5221 		conn_t		*first_connp = connp;
5222 		conn_t		*next_connp;
5223 		mblk_t		*mp1;
5224 
5225 		connp = connp->conn_next;
5226 		for (;;) {
5227 			while (connp != NULL) {
5228 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5229 				    fport, faddr) &&
5230 				    conn_wantpacket(connp, ira, ipha) &&
5231 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5232 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5233 				    ira, connp)))
5234 					break;
5235 				connp = connp->conn_next;
5236 			}
5237 			if (connp == NULL) {
5238 				/* No more interested clients */
5239 				connp = first_connp;
5240 				break;
5241 			}
5242 			if (((mp1 = dupmsg(mp)) == NULL) &&
5243 			    ((mp1 = copymsg(mp)) == NULL)) {
5244 				/* Memory allocation failed */
5245 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5246 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5247 				connp = first_connp;
5248 				break;
5249 			}
5250 			CONN_INC_REF(connp);
5251 			mutex_exit(&connfp->connf_lock);
5252 
5253 			IP_STAT(ipst, ip_udp_fanmb);
5254 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5255 			    NULL, ira);
5256 			mutex_enter(&connfp->connf_lock);
5257 			/* Follow the next pointer before releasing the conn */
5258 			next_connp = connp->conn_next;
5259 			CONN_DEC_REF(connp);
5260 			connp = next_connp;
5261 		}
5262 	}
5263 
5264 	/* Last one.  Send it upstream. */
5265 	mutex_exit(&connfp->connf_lock);
5266 	IP_STAT(ipst, ip_udp_fanmb);
5267 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5268 	CONN_DEC_REF(connp);
5269 	return;
5270 
5271 notfound:
5272 	mutex_exit(&connfp->connf_lock);
5273 	/*
5274 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5275 	 * have already been matched above, since they live in the IPv4
5276 	 * fanout tables. This implies we only need to
5277 	 * check for IPv6 in6addr_any endpoints here.
5278 	 * Thus we compare using ipv6_all_zeros instead of the destination
5279 	 * address, except for the multicast group membership lookup which
5280 	 * uses the IPv4 destination.
5281 	 */
5282 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5283 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5284 	mutex_enter(&connfp->connf_lock);
5285 	connp = connfp->connf_head;
5286 	/*
5287 	 * IPv4 multicast packet being delivered to an AF_INET6
5288 	 * in6addr_any endpoint.
5289 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5290 	 * and not conn_wantpacket_v6() since any multicast membership is
5291 	 * for an IPv4-mapped multicast address.
5292 	 */
5293 	while (connp != NULL) {
5294 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5295 		    fport, v6faddr) &&
5296 		    conn_wantpacket(connp, ira, ipha) &&
5297 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5298 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5299 			break;
5300 		connp = connp->conn_next;
5301 	}
5302 
5303 	if (connp == NULL) {
5304 		/*
5305 		 * No one bound to this port.  Is
5306 		 * there a client that wants all
5307 		 * unclaimed datagrams?
5308 		 */
5309 		mutex_exit(&connfp->connf_lock);
5310 
5311 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5312 		    NULL) {
5313 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5314 			ip_fanout_proto_v4(mp, ipha, ira);
5315 		} else {
5316 			/*
5317 			 * We used to attempt to send an icmp error here, but
5318 			 * since this is known to be a multicast packet
5319 			 * and we don't send icmp errors in response to
5320 			 * multicast, just drop the packet and give up sooner.
5321 			 */
5322 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5323 			freemsg(mp);
5324 		}
5325 		return;
5326 	}
5327 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5328 
5329 	/*
5330 	 * If SO_REUSEADDR has been set on the first we send the
5331 	 * packet to all clients that have joined the group and
5332 	 * match the port.
5333 	 */
5334 	if (connp->conn_reuseaddr) {
5335 		conn_t		*first_connp = connp;
5336 		conn_t		*next_connp;
5337 		mblk_t		*mp1;
5338 
5339 		CONN_INC_REF(connp);
5340 		connp = connp->conn_next;
5341 		for (;;) {
5342 			while (connp != NULL) {
5343 				if (IPCL_UDP_MATCH_V6(connp, lport,
5344 				    ipv6_all_zeros, fport, v6faddr) &&
5345 				    conn_wantpacket(connp, ira, ipha) &&
5346 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5347 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5348 				    ira, connp)))
5349 					break;
5350 				connp = connp->conn_next;
5351 			}
5352 			if (connp == NULL) {
5353 				/* No more interested clients */
5354 				connp = first_connp;
5355 				break;
5356 			}
5357 			if (((mp1 = dupmsg(mp)) == NULL) &&
5358 			    ((mp1 = copymsg(mp)) == NULL)) {
5359 				/* Memory allocation failed */
5360 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5361 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5362 				connp = first_connp;
5363 				break;
5364 			}
5365 			CONN_INC_REF(connp);
5366 			mutex_exit(&connfp->connf_lock);
5367 
5368 			IP_STAT(ipst, ip_udp_fanmb);
5369 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5370 			    NULL, ira);
5371 			mutex_enter(&connfp->connf_lock);
5372 			/* Follow the next pointer before releasing the conn */
5373 			next_connp = connp->conn_next;
5374 			CONN_DEC_REF(connp);
5375 			connp = next_connp;
5376 		}
5377 	}
5378 
5379 	/* Last one.  Send it upstream. */
5380 	mutex_exit(&connfp->connf_lock);
5381 	IP_STAT(ipst, ip_udp_fanmb);
5382 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5383 	CONN_DEC_REF(connp);
5384 }
5385 
5386 /*
5387  * Split an incoming packet's IPv4 options into the label and the other options.
5388  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5389  * clearing out any leftover label or options.
5390  * Otherwise it just makes ipp point into the packet.
5391  *
5392  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5393  */
5394 int
5395 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5396 {
5397 	uchar_t		*opt;
5398 	uint32_t	totallen;
5399 	uint32_t	optval;
5400 	uint32_t	optlen;
5401 
5402 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5403 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5404 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5405 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5406 
5407 	/*
5408 	 * Get length (in 4 byte octets) of IP header options.
5409 	 */
5410 	totallen = ipha->ipha_version_and_hdr_length -
5411 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5412 
5413 	if (totallen == 0) {
5414 		if (!allocate)
5415 			return (0);
5416 
5417 		/* Clear out anything from a previous packet */
5418 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5419 			kmem_free(ipp->ipp_ipv4_options,
5420 			    ipp->ipp_ipv4_options_len);
5421 			ipp->ipp_ipv4_options = NULL;
5422 			ipp->ipp_ipv4_options_len = 0;
5423 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5424 		}
5425 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5426 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5427 			ipp->ipp_label_v4 = NULL;
5428 			ipp->ipp_label_len_v4 = 0;
5429 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5430 		}
5431 		return (0);
5432 	}
5433 
5434 	totallen <<= 2;
5435 	opt = (uchar_t *)&ipha[1];
5436 	if (!is_system_labeled()) {
5437 
5438 	copyall:
5439 		if (!allocate) {
5440 			if (totallen != 0) {
5441 				ipp->ipp_ipv4_options = opt;
5442 				ipp->ipp_ipv4_options_len = totallen;
5443 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5444 			}
5445 			return (0);
5446 		}
5447 		/* Just copy all of options */
5448 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5449 			if (totallen == ipp->ipp_ipv4_options_len) {
5450 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5451 				return (0);
5452 			}
5453 			kmem_free(ipp->ipp_ipv4_options,
5454 			    ipp->ipp_ipv4_options_len);
5455 			ipp->ipp_ipv4_options = NULL;
5456 			ipp->ipp_ipv4_options_len = 0;
5457 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5458 		}
5459 		if (totallen == 0)
5460 			return (0);
5461 
5462 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5463 		if (ipp->ipp_ipv4_options == NULL)
5464 			return (ENOMEM);
5465 		ipp->ipp_ipv4_options_len = totallen;
5466 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5467 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5468 		return (0);
5469 	}
5470 
5471 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5472 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5473 		ipp->ipp_label_v4 = NULL;
5474 		ipp->ipp_label_len_v4 = 0;
5475 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5476 	}
5477 
5478 	/*
5479 	 * Search for CIPSO option.
5480 	 * We assume CIPSO is first in options if it is present.
5481 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5482 	 * prior to the CIPSO option.
5483 	 */
5484 	while (totallen != 0) {
5485 		switch (optval = opt[IPOPT_OPTVAL]) {
5486 		case IPOPT_EOL:
5487 			return (0);
5488 		case IPOPT_NOP:
5489 			optlen = 1;
5490 			break;
5491 		default:
5492 			if (totallen <= IPOPT_OLEN)
5493 				return (EINVAL);
5494 			optlen = opt[IPOPT_OLEN];
5495 			if (optlen < 2)
5496 				return (EINVAL);
5497 		}
5498 		if (optlen > totallen)
5499 			return (EINVAL);
5500 
5501 		switch (optval) {
5502 		case IPOPT_COMSEC:
5503 			if (!allocate) {
5504 				ipp->ipp_label_v4 = opt;
5505 				ipp->ipp_label_len_v4 = optlen;
5506 				ipp->ipp_fields |= IPPF_LABEL_V4;
5507 			} else {
5508 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5509 				    KM_NOSLEEP);
5510 				if (ipp->ipp_label_v4 == NULL)
5511 					return (ENOMEM);
5512 				ipp->ipp_label_len_v4 = optlen;
5513 				ipp->ipp_fields |= IPPF_LABEL_V4;
5514 				bcopy(opt, ipp->ipp_label_v4, optlen);
5515 			}
5516 			totallen -= optlen;
5517 			opt += optlen;
5518 
5519 			/* Skip padding bytes until we get to a multiple of 4 */
5520 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5521 				totallen--;
5522 				opt++;
5523 			}
5524 			/* Remaining as ipp_ipv4_options */
5525 			goto copyall;
5526 		}
5527 		totallen -= optlen;
5528 		opt += optlen;
5529 	}
5530 	/* No CIPSO found; return everything as ipp_ipv4_options */
5531 	totallen = ipha->ipha_version_and_hdr_length -
5532 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5533 	totallen <<= 2;
5534 	opt = (uchar_t *)&ipha[1];
5535 	goto copyall;
5536 }
5537 
5538 /*
5539  * Efficient versions of lookup for an IRE when we only
5540  * match the address.
5541  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5542  * Does not handle multicast addresses.
5543  */
5544 uint_t
5545 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5546 {
5547 	ire_t *ire;
5548 	uint_t result;
5549 
5550 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5551 	ASSERT(ire != NULL);
5552 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5553 		result = IRE_NOROUTE;
5554 	else
5555 		result = ire->ire_type;
5556 	ire_refrele(ire);
5557 	return (result);
5558 }
5559 
5560 /*
5561  * Efficient versions of lookup for an IRE when we only
5562  * match the address.
5563  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5564  * Does not handle multicast addresses.
5565  */
5566 uint_t
5567 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5568 {
5569 	ire_t *ire;
5570 	uint_t result;
5571 
5572 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5573 	ASSERT(ire != NULL);
5574 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5575 		result = IRE_NOROUTE;
5576 	else
5577 		result = ire->ire_type;
5578 	ire_refrele(ire);
5579 	return (result);
5580 }
5581 
5582 /*
5583  * Nobody should be sending
5584  * packets up this stream
5585  */
5586 static void
5587 ip_lrput(queue_t *q, mblk_t *mp)
5588 {
5589 	switch (mp->b_datap->db_type) {
5590 	case M_FLUSH:
5591 		/* Turn around */
5592 		if (*mp->b_rptr & FLUSHW) {
5593 			*mp->b_rptr &= ~FLUSHR;
5594 			qreply(q, mp);
5595 			return;
5596 		}
5597 		break;
5598 	}
5599 	freemsg(mp);
5600 }
5601 
5602 /* Nobody should be sending packets down this stream */
5603 /* ARGSUSED */
5604 void
5605 ip_lwput(queue_t *q, mblk_t *mp)
5606 {
5607 	freemsg(mp);
5608 }
5609 
5610 /*
5611  * Move the first hop in any source route to ipha_dst and remove that part of
5612  * the source route.  Called by other protocols.  Errors in option formatting
5613  * are ignored - will be handled by ip_output_options. Return the final
5614  * destination (either ipha_dst or the last entry in a source route.)
5615  */
5616 ipaddr_t
5617 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5618 {
5619 	ipoptp_t	opts;
5620 	uchar_t		*opt;
5621 	uint8_t		optval;
5622 	uint8_t		optlen;
5623 	ipaddr_t	dst;
5624 	int		i;
5625 	ip_stack_t	*ipst = ns->netstack_ip;
5626 
5627 	ip2dbg(("ip_massage_options\n"));
5628 	dst = ipha->ipha_dst;
5629 	for (optval = ipoptp_first(&opts, ipha);
5630 	    optval != IPOPT_EOL;
5631 	    optval = ipoptp_next(&opts)) {
5632 		opt = opts.ipoptp_cur;
5633 		switch (optval) {
5634 			uint8_t off;
5635 		case IPOPT_SSRR:
5636 		case IPOPT_LSRR:
5637 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5638 				ip1dbg(("ip_massage_options: bad src route\n"));
5639 				break;
5640 			}
5641 			optlen = opts.ipoptp_len;
5642 			off = opt[IPOPT_OFFSET];
5643 			off--;
5644 		redo_srr:
5645 			if (optlen < IP_ADDR_LEN ||
5646 			    off > optlen - IP_ADDR_LEN) {
5647 				/* End of source route */
5648 				ip1dbg(("ip_massage_options: end of SR\n"));
5649 				break;
5650 			}
5651 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5652 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5653 			    ntohl(dst)));
5654 			/*
5655 			 * Check if our address is present more than
5656 			 * once as consecutive hops in source route.
5657 			 * XXX verify per-interface ip_forwarding
5658 			 * for source route?
5659 			 */
5660 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5661 				off += IP_ADDR_LEN;
5662 				goto redo_srr;
5663 			}
5664 			if (dst == htonl(INADDR_LOOPBACK)) {
5665 				ip1dbg(("ip_massage_options: loopback addr in "
5666 				    "source route!\n"));
5667 				break;
5668 			}
5669 			/*
5670 			 * Update ipha_dst to be the first hop and remove the
5671 			 * first hop from the source route (by overwriting
5672 			 * part of the option with NOP options).
5673 			 */
5674 			ipha->ipha_dst = dst;
5675 			/* Put the last entry in dst */
5676 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5677 			    3;
5678 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5679 
5680 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5681 			    ntohl(dst)));
5682 			/* Move down and overwrite */
5683 			opt[IP_ADDR_LEN] = opt[0];
5684 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5685 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5686 			for (i = 0; i < IP_ADDR_LEN; i++)
5687 				opt[i] = IPOPT_NOP;
5688 			break;
5689 		}
5690 	}
5691 	return (dst);
5692 }
5693 
5694 /*
5695  * Return the network mask
5696  * associated with the specified address.
5697  */
5698 ipaddr_t
5699 ip_net_mask(ipaddr_t addr)
5700 {
5701 	uchar_t	*up = (uchar_t *)&addr;
5702 	ipaddr_t mask = 0;
5703 	uchar_t	*maskp = (uchar_t *)&mask;
5704 
5705 #if defined(__i386) || defined(__amd64)
5706 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5707 #endif
5708 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5709 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5710 #endif
5711 	if (CLASSD(addr)) {
5712 		maskp[0] = 0xF0;
5713 		return (mask);
5714 	}
5715 
5716 	/* We assume Class E default netmask to be 32 */
5717 	if (CLASSE(addr))
5718 		return (0xffffffffU);
5719 
5720 	if (addr == 0)
5721 		return (0);
5722 	maskp[0] = 0xFF;
5723 	if ((up[0] & 0x80) == 0)
5724 		return (mask);
5725 
5726 	maskp[1] = 0xFF;
5727 	if ((up[0] & 0xC0) == 0x80)
5728 		return (mask);
5729 
5730 	maskp[2] = 0xFF;
5731 	if ((up[0] & 0xE0) == 0xC0)
5732 		return (mask);
5733 
5734 	/* Otherwise return no mask */
5735 	return ((ipaddr_t)0);
5736 }
5737 
5738 /* Name/Value Table Lookup Routine */
5739 char *
5740 ip_nv_lookup(nv_t *nv, int value)
5741 {
5742 	if (!nv)
5743 		return (NULL);
5744 	for (; nv->nv_name; nv++) {
5745 		if (nv->nv_value == value)
5746 			return (nv->nv_name);
5747 	}
5748 	return ("unknown");
5749 }
5750 
5751 static int
5752 ip_wait_for_info_ack(ill_t *ill)
5753 {
5754 	int err;
5755 
5756 	mutex_enter(&ill->ill_lock);
5757 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5758 		/*
5759 		 * Return value of 0 indicates a pending signal.
5760 		 */
5761 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5762 		if (err == 0) {
5763 			mutex_exit(&ill->ill_lock);
5764 			return (EINTR);
5765 		}
5766 	}
5767 	mutex_exit(&ill->ill_lock);
5768 	/*
5769 	 * ip_rput_other could have set an error  in ill_error on
5770 	 * receipt of M_ERROR.
5771 	 */
5772 	return (ill->ill_error);
5773 }
5774 
5775 /*
5776  * This is a module open, i.e. this is a control stream for access
5777  * to a DLPI device.  We allocate an ill_t as the instance data in
5778  * this case.
5779  */
5780 static int
5781 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5782 {
5783 	ill_t	*ill;
5784 	int	err;
5785 	zoneid_t zoneid;
5786 	netstack_t *ns;
5787 	ip_stack_t *ipst;
5788 
5789 	/*
5790 	 * Prevent unprivileged processes from pushing IP so that
5791 	 * they can't send raw IP.
5792 	 */
5793 	if (secpolicy_net_rawaccess(credp) != 0)
5794 		return (EPERM);
5795 
5796 	ns = netstack_find_by_cred(credp);
5797 	ASSERT(ns != NULL);
5798 	ipst = ns->netstack_ip;
5799 	ASSERT(ipst != NULL);
5800 
5801 	/*
5802 	 * For exclusive stacks we set the zoneid to zero
5803 	 * to make IP operate as if in the global zone.
5804 	 */
5805 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5806 		zoneid = GLOBAL_ZONEID;
5807 	else
5808 		zoneid = crgetzoneid(credp);
5809 
5810 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5811 	q->q_ptr = WR(q)->q_ptr = ill;
5812 	ill->ill_ipst = ipst;
5813 	ill->ill_zoneid = zoneid;
5814 
5815 	/*
5816 	 * ill_init initializes the ill fields and then sends down
5817 	 * down a DL_INFO_REQ after calling qprocson.
5818 	 */
5819 	err = ill_init(q, ill);
5820 
5821 	if (err != 0) {
5822 		mi_free(ill);
5823 		netstack_rele(ipst->ips_netstack);
5824 		q->q_ptr = NULL;
5825 		WR(q)->q_ptr = NULL;
5826 		return (err);
5827 	}
5828 
5829 	/*
5830 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5831 	 *
5832 	 * ill_init initializes the ipsq marking this thread as
5833 	 * writer
5834 	 */
5835 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5836 	err = ip_wait_for_info_ack(ill);
5837 	if (err == 0)
5838 		ill->ill_credp = credp;
5839 	else
5840 		goto fail;
5841 
5842 	crhold(credp);
5843 
5844 	mutex_enter(&ipst->ips_ip_mi_lock);
5845 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5846 	    sflag, credp);
5847 	mutex_exit(&ipst->ips_ip_mi_lock);
5848 fail:
5849 	if (err) {
5850 		(void) ip_close(q, 0);
5851 		return (err);
5852 	}
5853 	return (0);
5854 }
5855 
5856 /* For /dev/ip aka AF_INET open */
5857 int
5858 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5859 {
5860 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5861 }
5862 
5863 /* For /dev/ip6 aka AF_INET6 open */
5864 int
5865 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5866 {
5867 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5868 }
5869 
5870 /* IP open routine. */
5871 int
5872 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5873     boolean_t isv6)
5874 {
5875 	conn_t 		*connp;
5876 	major_t		maj;
5877 	zoneid_t	zoneid;
5878 	netstack_t	*ns;
5879 	ip_stack_t	*ipst;
5880 
5881 	/* Allow reopen. */
5882 	if (q->q_ptr != NULL)
5883 		return (0);
5884 
5885 	if (sflag & MODOPEN) {
5886 		/* This is a module open */
5887 		return (ip_modopen(q, devp, flag, sflag, credp));
5888 	}
5889 
5890 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5891 		/*
5892 		 * Non streams based socket looking for a stream
5893 		 * to access IP
5894 		 */
5895 		return (ip_helper_stream_setup(q, devp, flag, sflag,
5896 		    credp, isv6));
5897 	}
5898 
5899 	ns = netstack_find_by_cred(credp);
5900 	ASSERT(ns != NULL);
5901 	ipst = ns->netstack_ip;
5902 	ASSERT(ipst != NULL);
5903 
5904 	/*
5905 	 * For exclusive stacks we set the zoneid to zero
5906 	 * to make IP operate as if in the global zone.
5907 	 */
5908 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5909 		zoneid = GLOBAL_ZONEID;
5910 	else
5911 		zoneid = crgetzoneid(credp);
5912 
5913 	/*
5914 	 * We are opening as a device. This is an IP client stream, and we
5915 	 * allocate an conn_t as the instance data.
5916 	 */
5917 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
5918 
5919 	/*
5920 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
5921 	 * done by netstack_find_by_cred()
5922 	 */
5923 	netstack_rele(ipst->ips_netstack);
5924 
5925 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
5926 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
5927 	connp->conn_ixa->ixa_zoneid = zoneid;
5928 	connp->conn_zoneid = zoneid;
5929 
5930 	connp->conn_rq = q;
5931 	q->q_ptr = WR(q)->q_ptr = connp;
5932 
5933 	/* Minor tells us which /dev entry was opened */
5934 	if (isv6) {
5935 		connp->conn_family = AF_INET6;
5936 		connp->conn_ipversion = IPV6_VERSION;
5937 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
5938 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
5939 	} else {
5940 		connp->conn_family = AF_INET;
5941 		connp->conn_ipversion = IPV4_VERSION;
5942 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
5943 	}
5944 
5945 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
5946 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
5947 		connp->conn_minor_arena = ip_minor_arena_la;
5948 	} else {
5949 		/*
5950 		 * Either minor numbers in the large arena were exhausted
5951 		 * or a non socket application is doing the open.
5952 		 * Try to allocate from the small arena.
5953 		 */
5954 		if ((connp->conn_dev =
5955 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
5956 			/* CONN_DEC_REF takes care of netstack_rele() */
5957 			q->q_ptr = WR(q)->q_ptr = NULL;
5958 			CONN_DEC_REF(connp);
5959 			return (EBUSY);
5960 		}
5961 		connp->conn_minor_arena = ip_minor_arena_sa;
5962 	}
5963 
5964 	maj = getemajor(*devp);
5965 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
5966 
5967 	/*
5968 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
5969 	 */
5970 	connp->conn_cred = credp;
5971 	connp->conn_cpid = curproc->p_pid;
5972 	/* Cache things in ixa without an extra refhold */
5973 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
5974 	connp->conn_ixa->ixa_cred = connp->conn_cred;
5975 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
5976 	if (is_system_labeled())
5977 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
5978 
5979 	/*
5980 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
5981 	 */
5982 	connp->conn_recv = ip_conn_input;
5983 	connp->conn_recvicmp = ip_conn_input_icmp;
5984 
5985 	crhold(connp->conn_cred);
5986 
5987 	/*
5988 	 * If the caller has the process-wide flag set, then default to MAC
5989 	 * exempt mode.  This allows read-down to unlabeled hosts.
5990 	 */
5991 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5992 		connp->conn_mac_mode = CONN_MAC_AWARE;
5993 
5994 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
5995 
5996 	connp->conn_rq = q;
5997 	connp->conn_wq = WR(q);
5998 
5999 	/* Non-zero default values */
6000 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6001 
6002 	/*
6003 	 * Make the conn globally visible to walkers
6004 	 */
6005 	ASSERT(connp->conn_ref == 1);
6006 	mutex_enter(&connp->conn_lock);
6007 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6008 	mutex_exit(&connp->conn_lock);
6009 
6010 	qprocson(q);
6011 
6012 	return (0);
6013 }
6014 
6015 /*
6016  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6017  * all of them are copied to the conn_t. If the req is "zero", the policy is
6018  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6019  * fields.
6020  * We keep only the latest setting of the policy and thus policy setting
6021  * is not incremental/cumulative.
6022  *
6023  * Requests to set policies with multiple alternative actions will
6024  * go through a different API.
6025  */
6026 int
6027 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6028 {
6029 	uint_t ah_req = 0;
6030 	uint_t esp_req = 0;
6031 	uint_t se_req = 0;
6032 	ipsec_act_t *actp = NULL;
6033 	uint_t nact;
6034 	ipsec_policy_head_t *ph;
6035 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6036 	int error = 0;
6037 	netstack_t	*ns = connp->conn_netstack;
6038 	ip_stack_t	*ipst = ns->netstack_ip;
6039 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6040 
6041 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6042 
6043 	/*
6044 	 * The IP_SEC_OPT option does not allow variable length parameters,
6045 	 * hence a request cannot be NULL.
6046 	 */
6047 	if (req == NULL)
6048 		return (EINVAL);
6049 
6050 	ah_req = req->ipsr_ah_req;
6051 	esp_req = req->ipsr_esp_req;
6052 	se_req = req->ipsr_self_encap_req;
6053 
6054 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6055 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6056 		return (EINVAL);
6057 
6058 	/*
6059 	 * Are we dealing with a request to reset the policy (i.e.
6060 	 * zero requests).
6061 	 */
6062 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6063 	    (esp_req & REQ_MASK) == 0 &&
6064 	    (se_req & REQ_MASK) == 0);
6065 
6066 	if (!is_pol_reset) {
6067 		/*
6068 		 * If we couldn't load IPsec, fail with "protocol
6069 		 * not supported".
6070 		 * IPsec may not have been loaded for a request with zero
6071 		 * policies, so we don't fail in this case.
6072 		 */
6073 		mutex_enter(&ipss->ipsec_loader_lock);
6074 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6075 			mutex_exit(&ipss->ipsec_loader_lock);
6076 			return (EPROTONOSUPPORT);
6077 		}
6078 		mutex_exit(&ipss->ipsec_loader_lock);
6079 
6080 		/*
6081 		 * Test for valid requests. Invalid algorithms
6082 		 * need to be tested by IPsec code because new
6083 		 * algorithms can be added dynamically.
6084 		 */
6085 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6086 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6087 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6088 			return (EINVAL);
6089 		}
6090 
6091 		/*
6092 		 * Only privileged users can issue these
6093 		 * requests.
6094 		 */
6095 		if (((ah_req & IPSEC_PREF_NEVER) ||
6096 		    (esp_req & IPSEC_PREF_NEVER) ||
6097 		    (se_req & IPSEC_PREF_NEVER)) &&
6098 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6099 			return (EPERM);
6100 		}
6101 
6102 		/*
6103 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6104 		 * are mutually exclusive.
6105 		 */
6106 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6107 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6108 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6109 			/* Both of them are set */
6110 			return (EINVAL);
6111 		}
6112 	}
6113 
6114 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6115 
6116 	/*
6117 	 * If we have already cached policies in conn_connect(), don't
6118 	 * let them change now. We cache policies for connections
6119 	 * whose src,dst [addr, port] is known.
6120 	 */
6121 	if (connp->conn_policy_cached) {
6122 		return (EINVAL);
6123 	}
6124 
6125 	/*
6126 	 * We have a zero policies, reset the connection policy if already
6127 	 * set. This will cause the connection to inherit the
6128 	 * global policy, if any.
6129 	 */
6130 	if (is_pol_reset) {
6131 		if (connp->conn_policy != NULL) {
6132 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6133 			connp->conn_policy = NULL;
6134 		}
6135 		connp->conn_in_enforce_policy = B_FALSE;
6136 		connp->conn_out_enforce_policy = B_FALSE;
6137 		return (0);
6138 	}
6139 
6140 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6141 	    ipst->ips_netstack);
6142 	if (ph == NULL)
6143 		goto enomem;
6144 
6145 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6146 	if (actp == NULL)
6147 		goto enomem;
6148 
6149 	/*
6150 	 * Always insert IPv4 policy entries, since they can also apply to
6151 	 * ipv6 sockets being used in ipv4-compat mode.
6152 	 */
6153 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6154 	    IPSEC_TYPE_INBOUND, ns))
6155 		goto enomem;
6156 	is_pol_inserted = B_TRUE;
6157 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6158 	    IPSEC_TYPE_OUTBOUND, ns))
6159 		goto enomem;
6160 
6161 	/*
6162 	 * We're looking at a v6 socket, also insert the v6-specific
6163 	 * entries.
6164 	 */
6165 	if (connp->conn_family == AF_INET6) {
6166 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6167 		    IPSEC_TYPE_INBOUND, ns))
6168 			goto enomem;
6169 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6170 		    IPSEC_TYPE_OUTBOUND, ns))
6171 			goto enomem;
6172 	}
6173 
6174 	ipsec_actvec_free(actp, nact);
6175 
6176 	/*
6177 	 * If the requests need security, set enforce_policy.
6178 	 * If the requests are IPSEC_PREF_NEVER, one should
6179 	 * still set conn_out_enforce_policy so that ip_set_destination
6180 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6181 	 * for connections that we don't cache policy in at connect time,
6182 	 * if global policy matches in ip_output_attach_policy, we
6183 	 * don't wrongly inherit global policy. Similarly, we need
6184 	 * to set conn_in_enforce_policy also so that we don't verify
6185 	 * policy wrongly.
6186 	 */
6187 	if ((ah_req & REQ_MASK) != 0 ||
6188 	    (esp_req & REQ_MASK) != 0 ||
6189 	    (se_req & REQ_MASK) != 0) {
6190 		connp->conn_in_enforce_policy = B_TRUE;
6191 		connp->conn_out_enforce_policy = B_TRUE;
6192 	}
6193 
6194 	return (error);
6195 #undef REQ_MASK
6196 
6197 	/*
6198 	 * Common memory-allocation-failure exit path.
6199 	 */
6200 enomem:
6201 	if (actp != NULL)
6202 		ipsec_actvec_free(actp, nact);
6203 	if (is_pol_inserted)
6204 		ipsec_polhead_flush(ph, ns);
6205 	return (ENOMEM);
6206 }
6207 
6208 /*
6209  * Set socket options for joining and leaving multicast groups.
6210  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6211  * The caller has already check that the option name is consistent with
6212  * the address family of the socket.
6213  */
6214 int
6215 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6216     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6217 {
6218 	int		*i1 = (int *)invalp;
6219 	int		error = 0;
6220 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6221 	struct ip_mreq	*v4_mreqp;
6222 	struct ipv6_mreq *v6_mreqp;
6223 	struct group_req *greqp;
6224 	ire_t *ire;
6225 	boolean_t done = B_FALSE;
6226 	ipaddr_t ifaddr;
6227 	in6_addr_t v6group;
6228 	uint_t ifindex;
6229 	boolean_t mcast_opt = B_TRUE;
6230 	mcast_record_t fmode;
6231 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6232 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6233 
6234 	switch (name) {
6235 	case IP_ADD_MEMBERSHIP:
6236 	case IPV6_JOIN_GROUP:
6237 		mcast_opt = B_FALSE;
6238 		/* FALLTHRU */
6239 	case MCAST_JOIN_GROUP:
6240 		fmode = MODE_IS_EXCLUDE;
6241 		optfn = ip_opt_add_group;
6242 		break;
6243 
6244 	case IP_DROP_MEMBERSHIP:
6245 	case IPV6_LEAVE_GROUP:
6246 		mcast_opt = B_FALSE;
6247 		/* FALLTHRU */
6248 	case MCAST_LEAVE_GROUP:
6249 		fmode = MODE_IS_INCLUDE;
6250 		optfn = ip_opt_delete_group;
6251 		break;
6252 	default:
6253 		ASSERT(0);
6254 	}
6255 
6256 	if (mcast_opt) {
6257 		struct sockaddr_in *sin;
6258 		struct sockaddr_in6 *sin6;
6259 
6260 		greqp = (struct group_req *)i1;
6261 		if (greqp->gr_group.ss_family == AF_INET) {
6262 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6263 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6264 		} else {
6265 			if (!inet6)
6266 				return (EINVAL);	/* Not on INET socket */
6267 
6268 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6269 			v6group = sin6->sin6_addr;
6270 		}
6271 		ifaddr = INADDR_ANY;
6272 		ifindex = greqp->gr_interface;
6273 	} else if (inet6) {
6274 		v6_mreqp = (struct ipv6_mreq *)i1;
6275 		v6group = v6_mreqp->ipv6mr_multiaddr;
6276 		ifaddr = INADDR_ANY;
6277 		ifindex = v6_mreqp->ipv6mr_interface;
6278 	} else {
6279 		v4_mreqp = (struct ip_mreq *)i1;
6280 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6281 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6282 		ifindex = 0;
6283 	}
6284 
6285 	/*
6286 	 * In the multirouting case, we need to replicate
6287 	 * the request on all interfaces that will take part
6288 	 * in replication.  We do so because multirouting is
6289 	 * reflective, thus we will probably receive multi-
6290 	 * casts on those interfaces.
6291 	 * The ip_multirt_apply_membership() succeeds if
6292 	 * the operation succeeds on at least one interface.
6293 	 */
6294 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6295 		ipaddr_t group;
6296 
6297 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6298 
6299 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6300 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6301 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6302 	} else {
6303 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6304 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6305 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6306 	}
6307 	if (ire != NULL) {
6308 		if (ire->ire_flags & RTF_MULTIRT) {
6309 			error = ip_multirt_apply_membership(optfn, ire, connp,
6310 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6311 			done = B_TRUE;
6312 		}
6313 		ire_refrele(ire);
6314 	}
6315 
6316 	if (!done) {
6317 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6318 		    fmode, &ipv6_all_zeros);
6319 	}
6320 	return (error);
6321 }
6322 
6323 /*
6324  * Set socket options for joining and leaving multicast groups
6325  * for specific sources.
6326  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6327  * The caller has already check that the option name is consistent with
6328  * the address family of the socket.
6329  */
6330 int
6331 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6332     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6333 {
6334 	int		*i1 = (int *)invalp;
6335 	int		error = 0;
6336 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6337 	struct ip_mreq_source *imreqp;
6338 	struct group_source_req *gsreqp;
6339 	in6_addr_t v6group, v6src;
6340 	uint32_t ifindex;
6341 	ipaddr_t ifaddr;
6342 	boolean_t mcast_opt = B_TRUE;
6343 	mcast_record_t fmode;
6344 	ire_t *ire;
6345 	boolean_t done = B_FALSE;
6346 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6347 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6348 
6349 	switch (name) {
6350 	case IP_BLOCK_SOURCE:
6351 		mcast_opt = B_FALSE;
6352 		/* FALLTHRU */
6353 	case MCAST_BLOCK_SOURCE:
6354 		fmode = MODE_IS_EXCLUDE;
6355 		optfn = ip_opt_add_group;
6356 		break;
6357 
6358 	case IP_UNBLOCK_SOURCE:
6359 		mcast_opt = B_FALSE;
6360 		/* FALLTHRU */
6361 	case MCAST_UNBLOCK_SOURCE:
6362 		fmode = MODE_IS_EXCLUDE;
6363 		optfn = ip_opt_delete_group;
6364 		break;
6365 
6366 	case IP_ADD_SOURCE_MEMBERSHIP:
6367 		mcast_opt = B_FALSE;
6368 		/* FALLTHRU */
6369 	case MCAST_JOIN_SOURCE_GROUP:
6370 		fmode = MODE_IS_INCLUDE;
6371 		optfn = ip_opt_add_group;
6372 		break;
6373 
6374 	case IP_DROP_SOURCE_MEMBERSHIP:
6375 		mcast_opt = B_FALSE;
6376 		/* FALLTHRU */
6377 	case MCAST_LEAVE_SOURCE_GROUP:
6378 		fmode = MODE_IS_INCLUDE;
6379 		optfn = ip_opt_delete_group;
6380 		break;
6381 	default:
6382 		ASSERT(0);
6383 	}
6384 
6385 	if (mcast_opt) {
6386 		gsreqp = (struct group_source_req *)i1;
6387 		ifindex = gsreqp->gsr_interface;
6388 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6389 			struct sockaddr_in *s;
6390 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6391 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6392 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6393 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6394 		} else {
6395 			struct sockaddr_in6 *s6;
6396 
6397 			if (!inet6)
6398 				return (EINVAL);	/* Not on INET socket */
6399 
6400 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6401 			v6group = s6->sin6_addr;
6402 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6403 			v6src = s6->sin6_addr;
6404 		}
6405 		ifaddr = INADDR_ANY;
6406 	} else {
6407 		imreqp = (struct ip_mreq_source *)i1;
6408 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6409 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6410 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6411 		ifindex = 0;
6412 	}
6413 
6414 	/*
6415 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6416 	 */
6417 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6418 		v6src = ipv6_all_zeros;
6419 
6420 	/*
6421 	 * In the multirouting case, we need to replicate
6422 	 * the request as noted in the mcast cases above.
6423 	 */
6424 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6425 		ipaddr_t group;
6426 
6427 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6428 
6429 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6430 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6431 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6432 	} else {
6433 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6434 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6435 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6436 	}
6437 	if (ire != NULL) {
6438 		if (ire->ire_flags & RTF_MULTIRT) {
6439 			error = ip_multirt_apply_membership(optfn, ire, connp,
6440 			    checkonly, &v6group, fmode, &v6src);
6441 			done = B_TRUE;
6442 		}
6443 		ire_refrele(ire);
6444 	}
6445 	if (!done) {
6446 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6447 		    fmode, &v6src);
6448 	}
6449 	return (error);
6450 }
6451 
6452 /*
6453  * Given a destination address and a pointer to where to put the information
6454  * this routine fills in the mtuinfo.
6455  * The socket must be connected.
6456  * For sctp conn_faddr is the primary address.
6457  */
6458 int
6459 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6460 {
6461 	uint32_t	pmtu = IP_MAXPACKET;
6462 	uint_t		scopeid;
6463 
6464 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6465 		return (-1);
6466 
6467 	/* In case we never sent or called ip_set_destination_v4/v6 */
6468 	if (ixa->ixa_ire != NULL)
6469 		pmtu = ip_get_pmtu(ixa);
6470 
6471 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6472 		scopeid = ixa->ixa_scopeid;
6473 	else
6474 		scopeid = 0;
6475 
6476 	bzero(mtuinfo, sizeof (*mtuinfo));
6477 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6478 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6479 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6480 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6481 	mtuinfo->ip6m_mtu = pmtu;
6482 
6483 	return (sizeof (struct ip6_mtuinfo));
6484 }
6485 
6486 /*
6487  * When the src multihoming is changed from weak to [strong, preferred]
6488  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6489  * and identify routes that were created by user-applications in the
6490  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6491  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6492  * is selected by finding an interface route for the gateway.
6493  */
6494 /* ARGSUSED */
6495 void
6496 ip_ire_rebind_walker(ire_t *ire, void *notused)
6497 {
6498 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6499 		return;
6500 	ire_rebind(ire);
6501 	ire_delete(ire);
6502 }
6503 
6504 /*
6505  * When the src multihoming is changed from  [strong, preferred] to weak,
6506  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6507  * set any entries that were created by user-applications in the unbound state
6508  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6509  */
6510 /* ARGSUSED */
6511 void
6512 ip_ire_unbind_walker(ire_t *ire, void *notused)
6513 {
6514 	ire_t *new_ire;
6515 
6516 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6517 		return;
6518 	if (ire->ire_ipversion == IPV6_VERSION) {
6519 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6520 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6521 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6522 	} else {
6523 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6524 		    (uchar_t *)&ire->ire_mask,
6525 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6526 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6527 	}
6528 	if (new_ire == NULL)
6529 		return;
6530 	new_ire->ire_unbound = B_TRUE;
6531 	/*
6532 	 * The bound ire must first be deleted so that we don't return
6533 	 * the existing one on the attempt to add the unbound new_ire.
6534 	 */
6535 	ire_delete(ire);
6536 	new_ire = ire_add(new_ire);
6537 	if (new_ire != NULL)
6538 		ire_refrele(new_ire);
6539 }
6540 
6541 /*
6542  * When the settings of ip*_strict_src_multihoming tunables are changed,
6543  * all cached routes need to be recomputed. This recomputation needs to be
6544  * done when going from weaker to stronger modes so that the cached ire
6545  * for the connection does not violate the current ip*_strict_src_multihoming
6546  * setting. It also needs to be done when going from stronger to weaker modes,
6547  * so that we fall back to matching on the longest-matching-route (as opposed
6548  * to a shorter match that may have been selected in the strong mode
6549  * to satisfy src_multihoming settings).
6550  *
6551  * The cached ixa_ire entires for all conn_t entries are marked as
6552  * "verify" so that they will be recomputed for the next packet.
6553  */
6554 void
6555 conn_ire_revalidate(conn_t *connp, void *arg)
6556 {
6557 	boolean_t isv6 = (boolean_t)arg;
6558 
6559 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6560 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6561 		return;
6562 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6563 }
6564 
6565 /*
6566  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6567  * When an ipf is passed here for the first time, if
6568  * we already have in-order fragments on the queue, we convert from the fast-
6569  * path reassembly scheme to the hard-case scheme.  From then on, additional
6570  * fragments are reassembled here.  We keep track of the start and end offsets
6571  * of each piece, and the number of holes in the chain.  When the hole count
6572  * goes to zero, we are done!
6573  *
6574  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6575  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6576  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6577  * after the call to ip_reassemble().
6578  */
6579 int
6580 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6581     size_t msg_len)
6582 {
6583 	uint_t	end;
6584 	mblk_t	*next_mp;
6585 	mblk_t	*mp1;
6586 	uint_t	offset;
6587 	boolean_t incr_dups = B_TRUE;
6588 	boolean_t offset_zero_seen = B_FALSE;
6589 	boolean_t pkt_boundary_checked = B_FALSE;
6590 
6591 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6592 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6593 
6594 	/* Add in byte count */
6595 	ipf->ipf_count += msg_len;
6596 	if (ipf->ipf_end) {
6597 		/*
6598 		 * We were part way through in-order reassembly, but now there
6599 		 * is a hole.  We walk through messages already queued, and
6600 		 * mark them for hard case reassembly.  We know that up till
6601 		 * now they were in order starting from offset zero.
6602 		 */
6603 		offset = 0;
6604 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6605 			IP_REASS_SET_START(mp1, offset);
6606 			if (offset == 0) {
6607 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6608 				offset = -ipf->ipf_nf_hdr_len;
6609 			}
6610 			offset += mp1->b_wptr - mp1->b_rptr;
6611 			IP_REASS_SET_END(mp1, offset);
6612 		}
6613 		/* One hole at the end. */
6614 		ipf->ipf_hole_cnt = 1;
6615 		/* Brand it as a hard case, forever. */
6616 		ipf->ipf_end = 0;
6617 	}
6618 	/* Walk through all the new pieces. */
6619 	do {
6620 		end = start + (mp->b_wptr - mp->b_rptr);
6621 		/*
6622 		 * If start is 0, decrease 'end' only for the first mblk of
6623 		 * the fragment. Otherwise 'end' can get wrong value in the
6624 		 * second pass of the loop if first mblk is exactly the
6625 		 * size of ipf_nf_hdr_len.
6626 		 */
6627 		if (start == 0 && !offset_zero_seen) {
6628 			/* First segment */
6629 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6630 			end -= ipf->ipf_nf_hdr_len;
6631 			offset_zero_seen = B_TRUE;
6632 		}
6633 		next_mp = mp->b_cont;
6634 		/*
6635 		 * We are checking to see if there is any interesing data
6636 		 * to process.  If there isn't and the mblk isn't the
6637 		 * one which carries the unfragmentable header then we
6638 		 * drop it.  It's possible to have just the unfragmentable
6639 		 * header come through without any data.  That needs to be
6640 		 * saved.
6641 		 *
6642 		 * If the assert at the top of this function holds then the
6643 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6644 		 * is infrequently traveled enough that the test is left in
6645 		 * to protect against future code changes which break that
6646 		 * invariant.
6647 		 */
6648 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6649 			/* Empty.  Blast it. */
6650 			IP_REASS_SET_START(mp, 0);
6651 			IP_REASS_SET_END(mp, 0);
6652 			/*
6653 			 * If the ipf points to the mblk we are about to free,
6654 			 * update ipf to point to the next mblk (or NULL
6655 			 * if none).
6656 			 */
6657 			if (ipf->ipf_mp->b_cont == mp)
6658 				ipf->ipf_mp->b_cont = next_mp;
6659 			freeb(mp);
6660 			continue;
6661 		}
6662 		mp->b_cont = NULL;
6663 		IP_REASS_SET_START(mp, start);
6664 		IP_REASS_SET_END(mp, end);
6665 		if (!ipf->ipf_tail_mp) {
6666 			ipf->ipf_tail_mp = mp;
6667 			ipf->ipf_mp->b_cont = mp;
6668 			if (start == 0 || !more) {
6669 				ipf->ipf_hole_cnt = 1;
6670 				/*
6671 				 * if the first fragment comes in more than one
6672 				 * mblk, this loop will be executed for each
6673 				 * mblk. Need to adjust hole count so exiting
6674 				 * this routine will leave hole count at 1.
6675 				 */
6676 				if (next_mp)
6677 					ipf->ipf_hole_cnt++;
6678 			} else
6679 				ipf->ipf_hole_cnt = 2;
6680 			continue;
6681 		} else if (ipf->ipf_last_frag_seen && !more &&
6682 		    !pkt_boundary_checked) {
6683 			/*
6684 			 * We check datagram boundary only if this fragment
6685 			 * claims to be the last fragment and we have seen a
6686 			 * last fragment in the past too. We do this only
6687 			 * once for a given fragment.
6688 			 *
6689 			 * start cannot be 0 here as fragments with start=0
6690 			 * and MF=0 gets handled as a complete packet. These
6691 			 * fragments should not reach here.
6692 			 */
6693 
6694 			if (start + msgdsize(mp) !=
6695 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6696 				/*
6697 				 * We have two fragments both of which claim
6698 				 * to be the last fragment but gives conflicting
6699 				 * information about the whole datagram size.
6700 				 * Something fishy is going on. Drop the
6701 				 * fragment and free up the reassembly list.
6702 				 */
6703 				return (IP_REASS_FAILED);
6704 			}
6705 
6706 			/*
6707 			 * We shouldn't come to this code block again for this
6708 			 * particular fragment.
6709 			 */
6710 			pkt_boundary_checked = B_TRUE;
6711 		}
6712 
6713 		/* New stuff at or beyond tail? */
6714 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6715 		if (start >= offset) {
6716 			if (ipf->ipf_last_frag_seen) {
6717 				/* current fragment is beyond last fragment */
6718 				return (IP_REASS_FAILED);
6719 			}
6720 			/* Link it on end. */
6721 			ipf->ipf_tail_mp->b_cont = mp;
6722 			ipf->ipf_tail_mp = mp;
6723 			if (more) {
6724 				if (start != offset)
6725 					ipf->ipf_hole_cnt++;
6726 			} else if (start == offset && next_mp == NULL)
6727 					ipf->ipf_hole_cnt--;
6728 			continue;
6729 		}
6730 		mp1 = ipf->ipf_mp->b_cont;
6731 		offset = IP_REASS_START(mp1);
6732 		/* New stuff at the front? */
6733 		if (start < offset) {
6734 			if (start == 0) {
6735 				if (end >= offset) {
6736 					/* Nailed the hole at the begining. */
6737 					ipf->ipf_hole_cnt--;
6738 				}
6739 			} else if (end < offset) {
6740 				/*
6741 				 * A hole, stuff, and a hole where there used
6742 				 * to be just a hole.
6743 				 */
6744 				ipf->ipf_hole_cnt++;
6745 			}
6746 			mp->b_cont = mp1;
6747 			/* Check for overlap. */
6748 			while (end > offset) {
6749 				if (end < IP_REASS_END(mp1)) {
6750 					mp->b_wptr -= end - offset;
6751 					IP_REASS_SET_END(mp, offset);
6752 					BUMP_MIB(ill->ill_ip_mib,
6753 					    ipIfStatsReasmPartDups);
6754 					break;
6755 				}
6756 				/* Did we cover another hole? */
6757 				if ((mp1->b_cont &&
6758 				    IP_REASS_END(mp1) !=
6759 				    IP_REASS_START(mp1->b_cont) &&
6760 				    end >= IP_REASS_START(mp1->b_cont)) ||
6761 				    (!ipf->ipf_last_frag_seen && !more)) {
6762 					ipf->ipf_hole_cnt--;
6763 				}
6764 				/* Clip out mp1. */
6765 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6766 					/*
6767 					 * After clipping out mp1, this guy
6768 					 * is now hanging off the end.
6769 					 */
6770 					ipf->ipf_tail_mp = mp;
6771 				}
6772 				IP_REASS_SET_START(mp1, 0);
6773 				IP_REASS_SET_END(mp1, 0);
6774 				/* Subtract byte count */
6775 				ipf->ipf_count -= mp1->b_datap->db_lim -
6776 				    mp1->b_datap->db_base;
6777 				freeb(mp1);
6778 				BUMP_MIB(ill->ill_ip_mib,
6779 				    ipIfStatsReasmPartDups);
6780 				mp1 = mp->b_cont;
6781 				if (!mp1)
6782 					break;
6783 				offset = IP_REASS_START(mp1);
6784 			}
6785 			ipf->ipf_mp->b_cont = mp;
6786 			continue;
6787 		}
6788 		/*
6789 		 * The new piece starts somewhere between the start of the head
6790 		 * and before the end of the tail.
6791 		 */
6792 		for (; mp1; mp1 = mp1->b_cont) {
6793 			offset = IP_REASS_END(mp1);
6794 			if (start < offset) {
6795 				if (end <= offset) {
6796 					/* Nothing new. */
6797 					IP_REASS_SET_START(mp, 0);
6798 					IP_REASS_SET_END(mp, 0);
6799 					/* Subtract byte count */
6800 					ipf->ipf_count -= mp->b_datap->db_lim -
6801 					    mp->b_datap->db_base;
6802 					if (incr_dups) {
6803 						ipf->ipf_num_dups++;
6804 						incr_dups = B_FALSE;
6805 					}
6806 					freeb(mp);
6807 					BUMP_MIB(ill->ill_ip_mib,
6808 					    ipIfStatsReasmDuplicates);
6809 					break;
6810 				}
6811 				/*
6812 				 * Trim redundant stuff off beginning of new
6813 				 * piece.
6814 				 */
6815 				IP_REASS_SET_START(mp, offset);
6816 				mp->b_rptr += offset - start;
6817 				BUMP_MIB(ill->ill_ip_mib,
6818 				    ipIfStatsReasmPartDups);
6819 				start = offset;
6820 				if (!mp1->b_cont) {
6821 					/*
6822 					 * After trimming, this guy is now
6823 					 * hanging off the end.
6824 					 */
6825 					mp1->b_cont = mp;
6826 					ipf->ipf_tail_mp = mp;
6827 					if (!more) {
6828 						ipf->ipf_hole_cnt--;
6829 					}
6830 					break;
6831 				}
6832 			}
6833 			if (start >= IP_REASS_START(mp1->b_cont))
6834 				continue;
6835 			/* Fill a hole */
6836 			if (start > offset)
6837 				ipf->ipf_hole_cnt++;
6838 			mp->b_cont = mp1->b_cont;
6839 			mp1->b_cont = mp;
6840 			mp1 = mp->b_cont;
6841 			offset = IP_REASS_START(mp1);
6842 			if (end >= offset) {
6843 				ipf->ipf_hole_cnt--;
6844 				/* Check for overlap. */
6845 				while (end > offset) {
6846 					if (end < IP_REASS_END(mp1)) {
6847 						mp->b_wptr -= end - offset;
6848 						IP_REASS_SET_END(mp, offset);
6849 						/*
6850 						 * TODO we might bump
6851 						 * this up twice if there is
6852 						 * overlap at both ends.
6853 						 */
6854 						BUMP_MIB(ill->ill_ip_mib,
6855 						    ipIfStatsReasmPartDups);
6856 						break;
6857 					}
6858 					/* Did we cover another hole? */
6859 					if ((mp1->b_cont &&
6860 					    IP_REASS_END(mp1)
6861 					    != IP_REASS_START(mp1->b_cont) &&
6862 					    end >=
6863 					    IP_REASS_START(mp1->b_cont)) ||
6864 					    (!ipf->ipf_last_frag_seen &&
6865 					    !more)) {
6866 						ipf->ipf_hole_cnt--;
6867 					}
6868 					/* Clip out mp1. */
6869 					if ((mp->b_cont = mp1->b_cont) ==
6870 					    NULL) {
6871 						/*
6872 						 * After clipping out mp1,
6873 						 * this guy is now hanging
6874 						 * off the end.
6875 						 */
6876 						ipf->ipf_tail_mp = mp;
6877 					}
6878 					IP_REASS_SET_START(mp1, 0);
6879 					IP_REASS_SET_END(mp1, 0);
6880 					/* Subtract byte count */
6881 					ipf->ipf_count -=
6882 					    mp1->b_datap->db_lim -
6883 					    mp1->b_datap->db_base;
6884 					freeb(mp1);
6885 					BUMP_MIB(ill->ill_ip_mib,
6886 					    ipIfStatsReasmPartDups);
6887 					mp1 = mp->b_cont;
6888 					if (!mp1)
6889 						break;
6890 					offset = IP_REASS_START(mp1);
6891 				}
6892 			}
6893 			break;
6894 		}
6895 	} while (start = end, mp = next_mp);
6896 
6897 	/* Fragment just processed could be the last one. Remember this fact */
6898 	if (!more)
6899 		ipf->ipf_last_frag_seen = B_TRUE;
6900 
6901 	/* Still got holes? */
6902 	if (ipf->ipf_hole_cnt)
6903 		return (IP_REASS_PARTIAL);
6904 	/* Clean up overloaded fields to avoid upstream disasters. */
6905 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6906 		IP_REASS_SET_START(mp1, 0);
6907 		IP_REASS_SET_END(mp1, 0);
6908 	}
6909 	return (IP_REASS_COMPLETE);
6910 }
6911 
6912 /*
6913  * Fragmentation reassembly.  Each ILL has a hash table for
6914  * queuing packets undergoing reassembly for all IPIFs
6915  * associated with the ILL.  The hash is based on the packet
6916  * IP ident field.  The ILL frag hash table was allocated
6917  * as a timer block at the time the ILL was created.  Whenever
6918  * there is anything on the reassembly queue, the timer will
6919  * be running.  Returns the reassembled packet if reassembly completes.
6920  */
6921 mblk_t *
6922 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
6923 {
6924 	uint32_t	frag_offset_flags;
6925 	mblk_t		*t_mp;
6926 	ipaddr_t	dst;
6927 	uint8_t		proto = ipha->ipha_protocol;
6928 	uint32_t	sum_val;
6929 	uint16_t	sum_flags;
6930 	ipf_t		*ipf;
6931 	ipf_t		**ipfp;
6932 	ipfb_t		*ipfb;
6933 	uint16_t	ident;
6934 	uint32_t	offset;
6935 	ipaddr_t	src;
6936 	uint_t		hdr_length;
6937 	uint32_t	end;
6938 	mblk_t		*mp1;
6939 	mblk_t		*tail_mp;
6940 	size_t		count;
6941 	size_t		msg_len;
6942 	uint8_t		ecn_info = 0;
6943 	uint32_t	packet_size;
6944 	boolean_t	pruned = B_FALSE;
6945 	ill_t		*ill = ira->ira_ill;
6946 	ip_stack_t	*ipst = ill->ill_ipst;
6947 
6948 	/*
6949 	 * Drop the fragmented as early as possible, if
6950 	 * we don't have resource(s) to re-assemble.
6951 	 */
6952 	if (ipst->ips_ip_reass_queue_bytes == 0) {
6953 		freemsg(mp);
6954 		return (NULL);
6955 	}
6956 
6957 	/* Check for fragmentation offset; return if there's none */
6958 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
6959 	    (IPH_MF | IPH_OFFSET)) == 0)
6960 		return (mp);
6961 
6962 	/*
6963 	 * We utilize hardware computed checksum info only for UDP since
6964 	 * IP fragmentation is a normal occurrence for the protocol.  In
6965 	 * addition, checksum offload support for IP fragments carrying
6966 	 * UDP payload is commonly implemented across network adapters.
6967 	 */
6968 	ASSERT(ira->ira_rill != NULL);
6969 	if (proto == IPPROTO_UDP && dohwcksum &&
6970 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
6971 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
6972 		mblk_t *mp1 = mp->b_cont;
6973 		int32_t len;
6974 
6975 		/* Record checksum information from the packet */
6976 		sum_val = (uint32_t)DB_CKSUM16(mp);
6977 		sum_flags = DB_CKSUMFLAGS(mp);
6978 
6979 		/* IP payload offset from beginning of mblk */
6980 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
6981 
6982 		if ((sum_flags & HCK_PARTIALCKSUM) &&
6983 		    (mp1 == NULL || mp1->b_cont == NULL) &&
6984 		    offset >= DB_CKSUMSTART(mp) &&
6985 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
6986 			uint32_t adj;
6987 			/*
6988 			 * Partial checksum has been calculated by hardware
6989 			 * and attached to the packet; in addition, any
6990 			 * prepended extraneous data is even byte aligned.
6991 			 * If any such data exists, we adjust the checksum;
6992 			 * this would also handle any postpended data.
6993 			 */
6994 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
6995 			    mp, mp1, len, adj);
6996 
6997 			/* One's complement subtract extraneous checksum */
6998 			if (adj >= sum_val)
6999 				sum_val = ~(adj - sum_val) & 0xFFFF;
7000 			else
7001 				sum_val -= adj;
7002 		}
7003 	} else {
7004 		sum_val = 0;
7005 		sum_flags = 0;
7006 	}
7007 
7008 	/* Clear hardware checksumming flag */
7009 	DB_CKSUMFLAGS(mp) = 0;
7010 
7011 	ident = ipha->ipha_ident;
7012 	offset = (frag_offset_flags << 3) & 0xFFFF;
7013 	src = ipha->ipha_src;
7014 	dst = ipha->ipha_dst;
7015 	hdr_length = IPH_HDR_LENGTH(ipha);
7016 	end = ntohs(ipha->ipha_length) - hdr_length;
7017 
7018 	/* If end == 0 then we have a packet with no data, so just free it */
7019 	if (end == 0) {
7020 		freemsg(mp);
7021 		return (NULL);
7022 	}
7023 
7024 	/* Record the ECN field info. */
7025 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7026 	if (offset != 0) {
7027 		/*
7028 		 * If this isn't the first piece, strip the header, and
7029 		 * add the offset to the end value.
7030 		 */
7031 		mp->b_rptr += hdr_length;
7032 		end += offset;
7033 	}
7034 
7035 	/* Handle vnic loopback of fragments */
7036 	if (mp->b_datap->db_ref > 2)
7037 		msg_len = 0;
7038 	else
7039 		msg_len = MBLKSIZE(mp);
7040 
7041 	tail_mp = mp;
7042 	while (tail_mp->b_cont != NULL) {
7043 		tail_mp = tail_mp->b_cont;
7044 		if (tail_mp->b_datap->db_ref <= 2)
7045 			msg_len += MBLKSIZE(tail_mp);
7046 	}
7047 
7048 	/* If the reassembly list for this ILL will get too big, prune it */
7049 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7050 	    ipst->ips_ip_reass_queue_bytes) {
7051 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7052 		    uint_t, ill->ill_frag_count,
7053 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7054 		ill_frag_prune(ill,
7055 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7056 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7057 		pruned = B_TRUE;
7058 	}
7059 
7060 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7061 	mutex_enter(&ipfb->ipfb_lock);
7062 
7063 	ipfp = &ipfb->ipfb_ipf;
7064 	/* Try to find an existing fragment queue for this packet. */
7065 	for (;;) {
7066 		ipf = ipfp[0];
7067 		if (ipf != NULL) {
7068 			/*
7069 			 * It has to match on ident and src/dst address.
7070 			 */
7071 			if (ipf->ipf_ident == ident &&
7072 			    ipf->ipf_src == src &&
7073 			    ipf->ipf_dst == dst &&
7074 			    ipf->ipf_protocol == proto) {
7075 				/*
7076 				 * If we have received too many
7077 				 * duplicate fragments for this packet
7078 				 * free it.
7079 				 */
7080 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7081 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7082 					freemsg(mp);
7083 					mutex_exit(&ipfb->ipfb_lock);
7084 					return (NULL);
7085 				}
7086 				/* Found it. */
7087 				break;
7088 			}
7089 			ipfp = &ipf->ipf_hash_next;
7090 			continue;
7091 		}
7092 
7093 		/*
7094 		 * If we pruned the list, do we want to store this new
7095 		 * fragment?. We apply an optimization here based on the
7096 		 * fact that most fragments will be received in order.
7097 		 * So if the offset of this incoming fragment is zero,
7098 		 * it is the first fragment of a new packet. We will
7099 		 * keep it.  Otherwise drop the fragment, as we have
7100 		 * probably pruned the packet already (since the
7101 		 * packet cannot be found).
7102 		 */
7103 		if (pruned && offset != 0) {
7104 			mutex_exit(&ipfb->ipfb_lock);
7105 			freemsg(mp);
7106 			return (NULL);
7107 		}
7108 
7109 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7110 			/*
7111 			 * Too many fragmented packets in this hash
7112 			 * bucket. Free the oldest.
7113 			 */
7114 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7115 		}
7116 
7117 		/* New guy.  Allocate a frag message. */
7118 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7119 		if (mp1 == NULL) {
7120 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7121 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7122 			freemsg(mp);
7123 reass_done:
7124 			mutex_exit(&ipfb->ipfb_lock);
7125 			return (NULL);
7126 		}
7127 
7128 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7129 		mp1->b_cont = mp;
7130 
7131 		/* Initialize the fragment header. */
7132 		ipf = (ipf_t *)mp1->b_rptr;
7133 		ipf->ipf_mp = mp1;
7134 		ipf->ipf_ptphn = ipfp;
7135 		ipfp[0] = ipf;
7136 		ipf->ipf_hash_next = NULL;
7137 		ipf->ipf_ident = ident;
7138 		ipf->ipf_protocol = proto;
7139 		ipf->ipf_src = src;
7140 		ipf->ipf_dst = dst;
7141 		ipf->ipf_nf_hdr_len = 0;
7142 		/* Record reassembly start time. */
7143 		ipf->ipf_timestamp = gethrestime_sec();
7144 		/* Record ipf generation and account for frag header */
7145 		ipf->ipf_gen = ill->ill_ipf_gen++;
7146 		ipf->ipf_count = MBLKSIZE(mp1);
7147 		ipf->ipf_last_frag_seen = B_FALSE;
7148 		ipf->ipf_ecn = ecn_info;
7149 		ipf->ipf_num_dups = 0;
7150 		ipfb->ipfb_frag_pkts++;
7151 		ipf->ipf_checksum = 0;
7152 		ipf->ipf_checksum_flags = 0;
7153 
7154 		/* Store checksum value in fragment header */
7155 		if (sum_flags != 0) {
7156 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7157 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7158 			ipf->ipf_checksum = sum_val;
7159 			ipf->ipf_checksum_flags = sum_flags;
7160 		}
7161 
7162 		/*
7163 		 * We handle reassembly two ways.  In the easy case,
7164 		 * where all the fragments show up in order, we do
7165 		 * minimal bookkeeping, and just clip new pieces on
7166 		 * the end.  If we ever see a hole, then we go off
7167 		 * to ip_reassemble which has to mark the pieces and
7168 		 * keep track of the number of holes, etc.  Obviously,
7169 		 * the point of having both mechanisms is so we can
7170 		 * handle the easy case as efficiently as possible.
7171 		 */
7172 		if (offset == 0) {
7173 			/* Easy case, in-order reassembly so far. */
7174 			ipf->ipf_count += msg_len;
7175 			ipf->ipf_tail_mp = tail_mp;
7176 			/*
7177 			 * Keep track of next expected offset in
7178 			 * ipf_end.
7179 			 */
7180 			ipf->ipf_end = end;
7181 			ipf->ipf_nf_hdr_len = hdr_length;
7182 		} else {
7183 			/* Hard case, hole at the beginning. */
7184 			ipf->ipf_tail_mp = NULL;
7185 			/*
7186 			 * ipf_end == 0 means that we have given up
7187 			 * on easy reassembly.
7188 			 */
7189 			ipf->ipf_end = 0;
7190 
7191 			/* Forget checksum offload from now on */
7192 			ipf->ipf_checksum_flags = 0;
7193 
7194 			/*
7195 			 * ipf_hole_cnt is set by ip_reassemble.
7196 			 * ipf_count is updated by ip_reassemble.
7197 			 * No need to check for return value here
7198 			 * as we don't expect reassembly to complete
7199 			 * or fail for the first fragment itself.
7200 			 */
7201 			(void) ip_reassemble(mp, ipf,
7202 			    (frag_offset_flags & IPH_OFFSET) << 3,
7203 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7204 		}
7205 		/* Update per ipfb and ill byte counts */
7206 		ipfb->ipfb_count += ipf->ipf_count;
7207 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7208 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7209 		/* If the frag timer wasn't already going, start it. */
7210 		mutex_enter(&ill->ill_lock);
7211 		ill_frag_timer_start(ill);
7212 		mutex_exit(&ill->ill_lock);
7213 		goto reass_done;
7214 	}
7215 
7216 	/*
7217 	 * If the packet's flag has changed (it could be coming up
7218 	 * from an interface different than the previous, therefore
7219 	 * possibly different checksum capability), then forget about
7220 	 * any stored checksum states.  Otherwise add the value to
7221 	 * the existing one stored in the fragment header.
7222 	 */
7223 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7224 		sum_val += ipf->ipf_checksum;
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 	} else if (ipf->ipf_checksum_flags != 0) {
7229 		/* Forget checksum offload from now on */
7230 		ipf->ipf_checksum_flags = 0;
7231 	}
7232 
7233 	/*
7234 	 * We have a new piece of a datagram which is already being
7235 	 * reassembled.  Update the ECN info if all IP fragments
7236 	 * are ECN capable.  If there is one which is not, clear
7237 	 * all the info.  If there is at least one which has CE
7238 	 * code point, IP needs to report that up to transport.
7239 	 */
7240 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7241 		if (ecn_info == IPH_ECN_CE)
7242 			ipf->ipf_ecn = IPH_ECN_CE;
7243 	} else {
7244 		ipf->ipf_ecn = IPH_ECN_NECT;
7245 	}
7246 	if (offset && ipf->ipf_end == offset) {
7247 		/* The new fragment fits at the end */
7248 		ipf->ipf_tail_mp->b_cont = mp;
7249 		/* Update the byte count */
7250 		ipf->ipf_count += msg_len;
7251 		/* Update per ipfb and ill byte counts */
7252 		ipfb->ipfb_count += msg_len;
7253 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7254 		atomic_add_32(&ill->ill_frag_count, msg_len);
7255 		if (frag_offset_flags & IPH_MF) {
7256 			/* More to come. */
7257 			ipf->ipf_end = end;
7258 			ipf->ipf_tail_mp = tail_mp;
7259 			goto reass_done;
7260 		}
7261 	} else {
7262 		/* Go do the hard cases. */
7263 		int ret;
7264 
7265 		if (offset == 0)
7266 			ipf->ipf_nf_hdr_len = hdr_length;
7267 
7268 		/* Save current byte count */
7269 		count = ipf->ipf_count;
7270 		ret = ip_reassemble(mp, ipf,
7271 		    (frag_offset_flags & IPH_OFFSET) << 3,
7272 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7273 		/* Count of bytes added and subtracted (freeb()ed) */
7274 		count = ipf->ipf_count - count;
7275 		if (count) {
7276 			/* Update per ipfb and ill byte counts */
7277 			ipfb->ipfb_count += count;
7278 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7279 			atomic_add_32(&ill->ill_frag_count, count);
7280 		}
7281 		if (ret == IP_REASS_PARTIAL) {
7282 			goto reass_done;
7283 		} else if (ret == IP_REASS_FAILED) {
7284 			/* Reassembly failed. Free up all resources */
7285 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7286 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7287 				IP_REASS_SET_START(t_mp, 0);
7288 				IP_REASS_SET_END(t_mp, 0);
7289 			}
7290 			freemsg(mp);
7291 			goto reass_done;
7292 		}
7293 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7294 	}
7295 	/*
7296 	 * We have completed reassembly.  Unhook the frag header from
7297 	 * the reassembly list.
7298 	 *
7299 	 * Before we free the frag header, record the ECN info
7300 	 * to report back to the transport.
7301 	 */
7302 	ecn_info = ipf->ipf_ecn;
7303 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7304 	ipfp = ipf->ipf_ptphn;
7305 
7306 	/* We need to supply these to caller */
7307 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7308 		sum_val = ipf->ipf_checksum;
7309 	else
7310 		sum_val = 0;
7311 
7312 	mp1 = ipf->ipf_mp;
7313 	count = ipf->ipf_count;
7314 	ipf = ipf->ipf_hash_next;
7315 	if (ipf != NULL)
7316 		ipf->ipf_ptphn = ipfp;
7317 	ipfp[0] = ipf;
7318 	atomic_add_32(&ill->ill_frag_count, -count);
7319 	ASSERT(ipfb->ipfb_count >= count);
7320 	ipfb->ipfb_count -= count;
7321 	ipfb->ipfb_frag_pkts--;
7322 	mutex_exit(&ipfb->ipfb_lock);
7323 	/* Ditch the frag header. */
7324 	mp = mp1->b_cont;
7325 
7326 	freeb(mp1);
7327 
7328 	/* Restore original IP length in header. */
7329 	packet_size = (uint32_t)msgdsize(mp);
7330 	if (packet_size > IP_MAXPACKET) {
7331 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7332 		ip_drop_input("Reassembled packet too large", mp, ill);
7333 		freemsg(mp);
7334 		return (NULL);
7335 	}
7336 
7337 	if (DB_REF(mp) > 1) {
7338 		mblk_t *mp2 = copymsg(mp);
7339 
7340 		if (mp2 == NULL) {
7341 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7342 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7343 			freemsg(mp);
7344 			return (NULL);
7345 		}
7346 		freemsg(mp);
7347 		mp = mp2;
7348 	}
7349 	ipha = (ipha_t *)mp->b_rptr;
7350 
7351 	ipha->ipha_length = htons((uint16_t)packet_size);
7352 	/* We're now complete, zip the frag state */
7353 	ipha->ipha_fragment_offset_and_flags = 0;
7354 	/* Record the ECN info. */
7355 	ipha->ipha_type_of_service &= 0xFC;
7356 	ipha->ipha_type_of_service |= ecn_info;
7357 
7358 	/* Update the receive attributes */
7359 	ira->ira_pktlen = packet_size;
7360 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7361 
7362 	/* Reassembly is successful; set checksum information in packet */
7363 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7364 	DB_CKSUMFLAGS(mp) = sum_flags;
7365 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7366 
7367 	return (mp);
7368 }
7369 
7370 /*
7371  * Pullup function that should be used for IP input in order to
7372  * ensure we do not loose the L2 source address; we need the l2 source
7373  * address for IP_RECVSLLA and for ndp_input.
7374  *
7375  * We return either NULL or b_rptr.
7376  */
7377 void *
7378 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7379 {
7380 	ill_t		*ill = ira->ira_ill;
7381 
7382 	if (ip_rput_pullups++ == 0) {
7383 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7384 		    "ip_pullup: %s forced us to "
7385 		    " pullup pkt, hdr len %ld, hdr addr %p",
7386 		    ill->ill_name, len, (void *)mp->b_rptr);
7387 	}
7388 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7389 		ip_setl2src(mp, ira, ira->ira_rill);
7390 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7391 	if (!pullupmsg(mp, len))
7392 		return (NULL);
7393 	else
7394 		return (mp->b_rptr);
7395 }
7396 
7397 /*
7398  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7399  * When called from the ULP ira_rill will be NULL hence the caller has to
7400  * pass in the ill.
7401  */
7402 /* ARGSUSED */
7403 void
7404 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7405 {
7406 	const uchar_t *addr;
7407 	int alen;
7408 
7409 	if (ira->ira_flags & IRAF_L2SRC_SET)
7410 		return;
7411 
7412 	ASSERT(ill != NULL);
7413 	alen = ill->ill_phys_addr_length;
7414 	ASSERT(alen <= sizeof (ira->ira_l2src));
7415 	if (ira->ira_mhip != NULL &&
7416 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7417 		bcopy(addr, ira->ira_l2src, alen);
7418 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7419 	    (addr = ill->ill_phys_addr) != NULL) {
7420 		bcopy(addr, ira->ira_l2src, alen);
7421 	} else {
7422 		bzero(ira->ira_l2src, alen);
7423 	}
7424 	ira->ira_flags |= IRAF_L2SRC_SET;
7425 }
7426 
7427 /*
7428  * check ip header length and align it.
7429  */
7430 mblk_t *
7431 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7432 {
7433 	ill_t	*ill = ira->ira_ill;
7434 	ssize_t len;
7435 
7436 	len = MBLKL(mp);
7437 
7438 	if (!OK_32PTR(mp->b_rptr))
7439 		IP_STAT(ill->ill_ipst, ip_notaligned);
7440 	else
7441 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7442 
7443 	/* Guard against bogus device drivers */
7444 	if (len < 0) {
7445 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7446 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7447 		freemsg(mp);
7448 		return (NULL);
7449 	}
7450 
7451 	if (len == 0) {
7452 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7453 		mblk_t *mp1 = mp->b_cont;
7454 
7455 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7456 			ip_setl2src(mp, ira, ira->ira_rill);
7457 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7458 
7459 		freeb(mp);
7460 		mp = mp1;
7461 		if (mp == NULL)
7462 			return (NULL);
7463 
7464 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7465 			return (mp);
7466 	}
7467 	if (ip_pullup(mp, min_size, ira) == NULL) {
7468 		if (msgdsize(mp) < min_size) {
7469 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7470 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7471 		} else {
7472 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7473 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7474 		}
7475 		freemsg(mp);
7476 		return (NULL);
7477 	}
7478 	return (mp);
7479 }
7480 
7481 /*
7482  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7483  */
7484 mblk_t *
7485 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7486     uint_t min_size, ip_recv_attr_t *ira)
7487 {
7488 	ill_t	*ill = ira->ira_ill;
7489 
7490 	/*
7491 	 * Make sure we have data length consistent
7492 	 * with the IP header.
7493 	 */
7494 	if (mp->b_cont == NULL) {
7495 		/* pkt_len is based on ipha_len, not the mblk length */
7496 		if (pkt_len < min_size) {
7497 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7498 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7499 			freemsg(mp);
7500 			return (NULL);
7501 		}
7502 		if (len < 0) {
7503 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7504 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7505 			freemsg(mp);
7506 			return (NULL);
7507 		}
7508 		/* Drop any pad */
7509 		mp->b_wptr = rptr + pkt_len;
7510 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7511 		ASSERT(pkt_len >= min_size);
7512 		if (pkt_len < min_size) {
7513 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7514 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7515 			freemsg(mp);
7516 			return (NULL);
7517 		}
7518 		if (len < 0) {
7519 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7520 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7521 			freemsg(mp);
7522 			return (NULL);
7523 		}
7524 		/* Drop any pad */
7525 		(void) adjmsg(mp, -len);
7526 		/*
7527 		 * adjmsg may have freed an mblk from the chain, hence
7528 		 * invalidate any hw checksum here. This will force IP to
7529 		 * calculate the checksum in sw, but only for this packet.
7530 		 */
7531 		DB_CKSUMFLAGS(mp) = 0;
7532 		IP_STAT(ill->ill_ipst, ip_multimblk);
7533 	}
7534 	return (mp);
7535 }
7536 
7537 /*
7538  * Check that the IPv4 opt_len is consistent with the packet and pullup
7539  * the options.
7540  */
7541 mblk_t *
7542 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7543     ip_recv_attr_t *ira)
7544 {
7545 	ill_t	*ill = ira->ira_ill;
7546 	ssize_t len;
7547 
7548 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7549 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7550 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7551 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7552 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7553 		freemsg(mp);
7554 		return (NULL);
7555 	}
7556 
7557 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7558 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7559 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7560 		freemsg(mp);
7561 		return (NULL);
7562 	}
7563 	/*
7564 	 * Recompute complete header length and make sure we
7565 	 * have access to all of it.
7566 	 */
7567 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7568 	if (len > (mp->b_wptr - mp->b_rptr)) {
7569 		if (len > pkt_len) {
7570 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7571 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7572 			freemsg(mp);
7573 			return (NULL);
7574 		}
7575 		if (ip_pullup(mp, len, ira) == NULL) {
7576 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7577 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7578 			freemsg(mp);
7579 			return (NULL);
7580 		}
7581 	}
7582 	return (mp);
7583 }
7584 
7585 /*
7586  * Returns a new ire, or the same ire, or NULL.
7587  * If a different IRE is returned, then it is held; the caller
7588  * needs to release it.
7589  * In no case is there any hold/release on the ire argument.
7590  */
7591 ire_t *
7592 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7593 {
7594 	ire_t		*new_ire;
7595 	ill_t		*ire_ill;
7596 	uint_t		ifindex;
7597 	ip_stack_t	*ipst = ill->ill_ipst;
7598 	boolean_t	strict_check = B_FALSE;
7599 
7600 	/*
7601 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7602 	 * issue (e.g. packet received on an underlying interface matched an
7603 	 * IRE_LOCAL on its associated group interface).
7604 	 */
7605 	ASSERT(ire->ire_ill != NULL);
7606 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7607 		return (ire);
7608 
7609 	/*
7610 	 * Do another ire lookup here, using the ingress ill, to see if the
7611 	 * interface is in a usesrc group.
7612 	 * As long as the ills belong to the same group, we don't consider
7613 	 * them to be arriving on the wrong interface. Thus, if the switch
7614 	 * is doing inbound load spreading, we won't drop packets when the
7615 	 * ip*_strict_dst_multihoming switch is on.
7616 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7617 	 * where the local address may not be unique. In this case we were
7618 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7619 	 * actually returned. The new lookup, which is more specific, should
7620 	 * only find the IRE_LOCAL associated with the ingress ill if one
7621 	 * exists.
7622 	 */
7623 	if (ire->ire_ipversion == IPV4_VERSION) {
7624 		if (ipst->ips_ip_strict_dst_multihoming)
7625 			strict_check = B_TRUE;
7626 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7627 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7628 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7629 	} else {
7630 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7631 		if (ipst->ips_ipv6_strict_dst_multihoming)
7632 			strict_check = B_TRUE;
7633 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7634 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7635 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7636 	}
7637 	/*
7638 	 * If the same ire that was returned in ip_input() is found then this
7639 	 * is an indication that usesrc groups are in use. The packet
7640 	 * arrived on a different ill in the group than the one associated with
7641 	 * the destination address.  If a different ire was found then the same
7642 	 * IP address must be hosted on multiple ills. This is possible with
7643 	 * unnumbered point2point interfaces. We switch to use this new ire in
7644 	 * order to have accurate interface statistics.
7645 	 */
7646 	if (new_ire != NULL) {
7647 		/* Note: held in one case but not the other? Caller handles */
7648 		if (new_ire != ire)
7649 			return (new_ire);
7650 		/* Unchanged */
7651 		ire_refrele(new_ire);
7652 		return (ire);
7653 	}
7654 
7655 	/*
7656 	 * Chase pointers once and store locally.
7657 	 */
7658 	ASSERT(ire->ire_ill != NULL);
7659 	ire_ill = ire->ire_ill;
7660 	ifindex = ill->ill_usesrc_ifindex;
7661 
7662 	/*
7663 	 * Check if it's a legal address on the 'usesrc' interface.
7664 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7665 	 * can just check phyint_ifindex.
7666 	 */
7667 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7668 		return (ire);
7669 	}
7670 
7671 	/*
7672 	 * If the ip*_strict_dst_multihoming switch is on then we can
7673 	 * only accept this packet if the interface is marked as routing.
7674 	 */
7675 	if (!(strict_check))
7676 		return (ire);
7677 
7678 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7679 		return (ire);
7680 	}
7681 	return (NULL);
7682 }
7683 
7684 /*
7685  * This function is used to construct a mac_header_info_s from a
7686  * DL_UNITDATA_IND message.
7687  * The address fields in the mhi structure points into the message,
7688  * thus the caller can't use those fields after freeing the message.
7689  *
7690  * We determine whether the packet received is a non-unicast packet
7691  * and in doing so, determine whether or not it is broadcast vs multicast.
7692  * For it to be a broadcast packet, we must have the appropriate mblk_t
7693  * hanging off the ill_t.  If this is either not present or doesn't match
7694  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7695  * to be multicast.  Thus NICs that have no broadcast address (or no
7696  * capability for one, such as point to point links) cannot return as
7697  * the packet being broadcast.
7698  */
7699 void
7700 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7701 {
7702 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7703 	mblk_t *bmp;
7704 	uint_t extra_offset;
7705 
7706 	bzero(mhip, sizeof (struct mac_header_info_s));
7707 
7708 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7709 
7710 	if (ill->ill_sap_length < 0)
7711 		extra_offset = 0;
7712 	else
7713 		extra_offset = ill->ill_sap_length;
7714 
7715 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7716 	    extra_offset;
7717 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7718 	    extra_offset;
7719 
7720 	if (!ind->dl_group_address)
7721 		return;
7722 
7723 	/* Multicast or broadcast */
7724 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7725 
7726 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7727 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7728 	    (bmp = ill->ill_bcast_mp) != NULL) {
7729 		dl_unitdata_req_t *dlur;
7730 		uint8_t *bphys_addr;
7731 
7732 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7733 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7734 		    extra_offset;
7735 
7736 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7737 		    ind->dl_dest_addr_length) == 0)
7738 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7739 	}
7740 }
7741 
7742 /*
7743  * This function is used to construct a mac_header_info_s from a
7744  * M_DATA fastpath message from a DLPI driver.
7745  * The address fields in the mhi structure points into the message,
7746  * thus the caller can't use those fields after freeing the message.
7747  *
7748  * We determine whether the packet received is a non-unicast packet
7749  * and in doing so, determine whether or not it is broadcast vs multicast.
7750  * For it to be a broadcast packet, we must have the appropriate mblk_t
7751  * hanging off the ill_t.  If this is either not present or doesn't match
7752  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7753  * to be multicast.  Thus NICs that have no broadcast address (or no
7754  * capability for one, such as point to point links) cannot return as
7755  * the packet being broadcast.
7756  */
7757 void
7758 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7759 {
7760 	mblk_t *bmp;
7761 	struct ether_header *pether;
7762 
7763 	bzero(mhip, sizeof (struct mac_header_info_s));
7764 
7765 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7766 
7767 	pether = (struct ether_header *)((char *)mp->b_rptr
7768 	    - sizeof (struct ether_header));
7769 
7770 	/*
7771 	 * Make sure the interface is an ethernet type, since we don't
7772 	 * know the header format for anything but Ethernet. Also make
7773 	 * sure we are pointing correctly above db_base.
7774 	 */
7775 	if (ill->ill_type != IFT_ETHER)
7776 		return;
7777 
7778 retry:
7779 	if ((uchar_t *)pether < mp->b_datap->db_base)
7780 		return;
7781 
7782 	/* Is there a VLAN tag? */
7783 	if (ill->ill_isv6) {
7784 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7785 			pether = (struct ether_header *)((char *)pether - 4);
7786 			goto retry;
7787 		}
7788 	} else {
7789 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7790 			pether = (struct ether_header *)((char *)pether - 4);
7791 			goto retry;
7792 		}
7793 	}
7794 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7795 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7796 
7797 	if (!(mhip->mhi_daddr[0] & 0x01))
7798 		return;
7799 
7800 	/* Multicast or broadcast */
7801 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7802 
7803 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7804 		dl_unitdata_req_t *dlur;
7805 		uint8_t *bphys_addr;
7806 		uint_t	addrlen;
7807 
7808 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7809 		addrlen = dlur->dl_dest_addr_length;
7810 		if (ill->ill_sap_length < 0) {
7811 			bphys_addr = (uchar_t *)dlur +
7812 			    dlur->dl_dest_addr_offset;
7813 			addrlen += ill->ill_sap_length;
7814 		} else {
7815 			bphys_addr = (uchar_t *)dlur +
7816 			    dlur->dl_dest_addr_offset +
7817 			    ill->ill_sap_length;
7818 			addrlen -= ill->ill_sap_length;
7819 		}
7820 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7821 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7822 	}
7823 }
7824 
7825 /*
7826  * Handle anything but M_DATA messages
7827  * We see the DL_UNITDATA_IND which are part
7828  * of the data path, and also the other messages from the driver.
7829  */
7830 void
7831 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7832 {
7833 	mblk_t		*first_mp;
7834 	struct iocblk   *iocp;
7835 	struct mac_header_info_s mhi;
7836 
7837 	switch (DB_TYPE(mp)) {
7838 	case M_PROTO:
7839 	case M_PCPROTO: {
7840 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7841 		    DL_UNITDATA_IND) {
7842 			/* Go handle anything other than data elsewhere. */
7843 			ip_rput_dlpi(ill, mp);
7844 			return;
7845 		}
7846 
7847 		first_mp = mp;
7848 		mp = first_mp->b_cont;
7849 		first_mp->b_cont = NULL;
7850 
7851 		if (mp == NULL) {
7852 			freeb(first_mp);
7853 			return;
7854 		}
7855 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7856 		if (ill->ill_isv6)
7857 			ip_input_v6(ill, NULL, mp, &mhi);
7858 		else
7859 			ip_input(ill, NULL, mp, &mhi);
7860 
7861 		/* Ditch the DLPI header. */
7862 		freeb(first_mp);
7863 		return;
7864 	}
7865 	case M_IOCACK:
7866 		iocp = (struct iocblk *)mp->b_rptr;
7867 		switch (iocp->ioc_cmd) {
7868 		case DL_IOC_HDR_INFO:
7869 			ill_fastpath_ack(ill, mp);
7870 			return;
7871 		default:
7872 			putnext(ill->ill_rq, mp);
7873 			return;
7874 		}
7875 		/* FALLTHRU */
7876 	case M_ERROR:
7877 	case M_HANGUP:
7878 		mutex_enter(&ill->ill_lock);
7879 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7880 			mutex_exit(&ill->ill_lock);
7881 			freemsg(mp);
7882 			return;
7883 		}
7884 		ill_refhold_locked(ill);
7885 		mutex_exit(&ill->ill_lock);
7886 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7887 		    B_FALSE);
7888 		return;
7889 	case M_CTL:
7890 		putnext(ill->ill_rq, mp);
7891 		return;
7892 	case M_IOCNAK:
7893 		ip1dbg(("got iocnak "));
7894 		iocp = (struct iocblk *)mp->b_rptr;
7895 		switch (iocp->ioc_cmd) {
7896 		case DL_IOC_HDR_INFO:
7897 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7898 			return;
7899 		default:
7900 			break;
7901 		}
7902 		/* FALLTHRU */
7903 	default:
7904 		putnext(ill->ill_rq, mp);
7905 		return;
7906 	}
7907 }
7908 
7909 /* Read side put procedure.  Packets coming from the wire arrive here. */
7910 void
7911 ip_rput(queue_t *q, mblk_t *mp)
7912 {
7913 	ill_t	*ill;
7914 	union DL_primitives *dl;
7915 
7916 	ill = (ill_t *)q->q_ptr;
7917 
7918 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
7919 		/*
7920 		 * If things are opening or closing, only accept high-priority
7921 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
7922 		 * created; on close, things hanging off the ill may have been
7923 		 * freed already.)
7924 		 */
7925 		dl = (union DL_primitives *)mp->b_rptr;
7926 		if (DB_TYPE(mp) != M_PCPROTO ||
7927 		    dl->dl_primitive == DL_UNITDATA_IND) {
7928 			inet_freemsg(mp);
7929 			return;
7930 		}
7931 	}
7932 	if (DB_TYPE(mp) == M_DATA) {
7933 		struct mac_header_info_s mhi;
7934 
7935 		ip_mdata_to_mhi(ill, mp, &mhi);
7936 		ip_input(ill, NULL, mp, &mhi);
7937 	} else {
7938 		ip_rput_notdata(ill, mp);
7939 	}
7940 }
7941 
7942 /*
7943  * Move the information to a copy.
7944  */
7945 mblk_t *
7946 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
7947 {
7948 	mblk_t		*mp1;
7949 	ill_t		*ill = ira->ira_ill;
7950 	ip_stack_t	*ipst = ill->ill_ipst;
7951 
7952 	IP_STAT(ipst, ip_db_ref);
7953 
7954 	/* Make sure we have ira_l2src before we loose the original mblk */
7955 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7956 		ip_setl2src(mp, ira, ira->ira_rill);
7957 
7958 	mp1 = copymsg(mp);
7959 	if (mp1 == NULL) {
7960 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7961 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
7962 		freemsg(mp);
7963 		return (NULL);
7964 	}
7965 	/* preserve the hardware checksum flags and data, if present */
7966 	if (DB_CKSUMFLAGS(mp) != 0) {
7967 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
7968 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
7969 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
7970 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
7971 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
7972 	}
7973 	freemsg(mp);
7974 	return (mp1);
7975 }
7976 
7977 static void
7978 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
7979     t_uscalar_t err)
7980 {
7981 	if (dl_err == DL_SYSERR) {
7982 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
7983 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
7984 		    ill->ill_name, dl_primstr(prim), err);
7985 		return;
7986 	}
7987 
7988 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
7989 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
7990 	    dl_errstr(dl_err));
7991 }
7992 
7993 /*
7994  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
7995  * than DL_UNITDATA_IND messages. If we need to process this message
7996  * exclusively, we call qwriter_ip, in which case we also need to call
7997  * ill_refhold before that, since qwriter_ip does an ill_refrele.
7998  */
7999 void
8000 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8001 {
8002 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8003 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8004 	queue_t		*q = ill->ill_rq;
8005 	t_uscalar_t	prim = dloa->dl_primitive;
8006 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8007 
8008 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8009 	    char *, dl_primstr(prim), ill_t *, ill);
8010 	ip1dbg(("ip_rput_dlpi"));
8011 
8012 	/*
8013 	 * If we received an ACK but didn't send a request for it, then it
8014 	 * can't be part of any pending operation; discard up-front.
8015 	 */
8016 	switch (prim) {
8017 	case DL_ERROR_ACK:
8018 		reqprim = dlea->dl_error_primitive;
8019 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8020 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8021 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8022 		    dlea->dl_unix_errno));
8023 		break;
8024 	case DL_OK_ACK:
8025 		reqprim = dloa->dl_correct_primitive;
8026 		break;
8027 	case DL_INFO_ACK:
8028 		reqprim = DL_INFO_REQ;
8029 		break;
8030 	case DL_BIND_ACK:
8031 		reqprim = DL_BIND_REQ;
8032 		break;
8033 	case DL_PHYS_ADDR_ACK:
8034 		reqprim = DL_PHYS_ADDR_REQ;
8035 		break;
8036 	case DL_NOTIFY_ACK:
8037 		reqprim = DL_NOTIFY_REQ;
8038 		break;
8039 	case DL_CAPABILITY_ACK:
8040 		reqprim = DL_CAPABILITY_REQ;
8041 		break;
8042 	}
8043 
8044 	if (prim != DL_NOTIFY_IND) {
8045 		if (reqprim == DL_PRIM_INVAL ||
8046 		    !ill_dlpi_pending(ill, reqprim)) {
8047 			/* Not a DLPI message we support or expected */
8048 			freemsg(mp);
8049 			return;
8050 		}
8051 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8052 		    dl_primstr(reqprim)));
8053 	}
8054 
8055 	switch (reqprim) {
8056 	case DL_UNBIND_REQ:
8057 		/*
8058 		 * NOTE: we mark the unbind as complete even if we got a
8059 		 * DL_ERROR_ACK, since there's not much else we can do.
8060 		 */
8061 		mutex_enter(&ill->ill_lock);
8062 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8063 		cv_signal(&ill->ill_cv);
8064 		mutex_exit(&ill->ill_lock);
8065 		break;
8066 
8067 	case DL_ENABMULTI_REQ:
8068 		if (prim == DL_OK_ACK) {
8069 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8070 				ill->ill_dlpi_multicast_state = IDS_OK;
8071 		}
8072 		break;
8073 	}
8074 
8075 	/*
8076 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8077 	 * need to become writer to continue to process it.  Because an
8078 	 * exclusive operation doesn't complete until replies to all queued
8079 	 * DLPI messages have been received, we know we're in the middle of an
8080 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8081 	 *
8082 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8083 	 * Since this is on the ill stream we unconditionally bump up the
8084 	 * refcount without doing ILL_CAN_LOOKUP().
8085 	 */
8086 	ill_refhold(ill);
8087 	if (prim == DL_NOTIFY_IND)
8088 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8089 	else
8090 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8091 }
8092 
8093 /*
8094  * Handling of DLPI messages that require exclusive access to the ipsq.
8095  *
8096  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8097  * happen here. (along with mi_copy_done)
8098  */
8099 /* ARGSUSED */
8100 static void
8101 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8102 {
8103 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8104 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8105 	int		err = 0;
8106 	ill_t		*ill = (ill_t *)q->q_ptr;
8107 	ipif_t		*ipif = NULL;
8108 	mblk_t		*mp1 = NULL;
8109 	conn_t		*connp = NULL;
8110 	t_uscalar_t	paddrreq;
8111 	mblk_t		*mp_hw;
8112 	boolean_t	success;
8113 	boolean_t	ioctl_aborted = B_FALSE;
8114 	boolean_t	log = B_TRUE;
8115 
8116 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8117 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8118 
8119 	ip1dbg(("ip_rput_dlpi_writer .."));
8120 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8121 	ASSERT(IAM_WRITER_ILL(ill));
8122 
8123 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8124 	/*
8125 	 * The current ioctl could have been aborted by the user and a new
8126 	 * ioctl to bring up another ill could have started. We could still
8127 	 * get a response from the driver later.
8128 	 */
8129 	if (ipif != NULL && ipif->ipif_ill != ill)
8130 		ioctl_aborted = B_TRUE;
8131 
8132 	switch (dloa->dl_primitive) {
8133 	case DL_ERROR_ACK:
8134 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8135 		    dl_primstr(dlea->dl_error_primitive)));
8136 
8137 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8138 		    char *, dl_primstr(dlea->dl_error_primitive),
8139 		    ill_t *, ill);
8140 
8141 		switch (dlea->dl_error_primitive) {
8142 		case DL_DISABMULTI_REQ:
8143 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8144 			break;
8145 		case DL_PROMISCON_REQ:
8146 		case DL_PROMISCOFF_REQ:
8147 		case DL_UNBIND_REQ:
8148 		case DL_ATTACH_REQ:
8149 		case DL_INFO_REQ:
8150 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8151 			break;
8152 		case DL_NOTIFY_REQ:
8153 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8154 			log = B_FALSE;
8155 			break;
8156 		case DL_PHYS_ADDR_REQ:
8157 			/*
8158 			 * For IPv6 only, there are two additional
8159 			 * phys_addr_req's sent to the driver to get the
8160 			 * IPv6 token and lla. This allows IP to acquire
8161 			 * the hardware address format for a given interface
8162 			 * without having built in knowledge of the hardware
8163 			 * address. ill_phys_addr_pend keeps track of the last
8164 			 * DL_PAR sent so we know which response we are
8165 			 * dealing with. ill_dlpi_done will update
8166 			 * ill_phys_addr_pend when it sends the next req.
8167 			 * We don't complete the IOCTL until all three DL_PARs
8168 			 * have been attempted, so set *_len to 0 and break.
8169 			 */
8170 			paddrreq = ill->ill_phys_addr_pend;
8171 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8172 			if (paddrreq == DL_IPV6_TOKEN) {
8173 				ill->ill_token_length = 0;
8174 				log = B_FALSE;
8175 				break;
8176 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8177 				ill->ill_nd_lla_len = 0;
8178 				log = B_FALSE;
8179 				break;
8180 			}
8181 			/*
8182 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8183 			 * We presumably have an IOCTL hanging out waiting
8184 			 * for completion. Find it and complete the IOCTL
8185 			 * with the error noted.
8186 			 * However, ill_dl_phys was called on an ill queue
8187 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8188 			 * set. But the ioctl is known to be pending on ill_wq.
8189 			 */
8190 			if (!ill->ill_ifname_pending)
8191 				break;
8192 			ill->ill_ifname_pending = 0;
8193 			if (!ioctl_aborted)
8194 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8195 			if (mp1 != NULL) {
8196 				/*
8197 				 * This operation (SIOCSLIFNAME) must have
8198 				 * happened on the ill. Assert there is no conn
8199 				 */
8200 				ASSERT(connp == NULL);
8201 				q = ill->ill_wq;
8202 			}
8203 			break;
8204 		case DL_BIND_REQ:
8205 			ill_dlpi_done(ill, DL_BIND_REQ);
8206 			if (ill->ill_ifname_pending)
8207 				break;
8208 			/*
8209 			 * Something went wrong with the bind.  We presumably
8210 			 * have an IOCTL hanging out waiting for completion.
8211 			 * Find it, take down the interface that was coming
8212 			 * up, and complete the IOCTL with the error noted.
8213 			 */
8214 			if (!ioctl_aborted)
8215 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8216 			if (mp1 != NULL) {
8217 				/*
8218 				 * This might be a result of a DL_NOTE_REPLUMB
8219 				 * notification. In that case, connp is NULL.
8220 				 */
8221 				if (connp != NULL)
8222 					q = CONNP_TO_WQ(connp);
8223 
8224 				(void) ipif_down(ipif, NULL, NULL);
8225 				/* error is set below the switch */
8226 			}
8227 			break;
8228 		case DL_ENABMULTI_REQ:
8229 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8230 
8231 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8232 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8233 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8234 
8235 				printf("ip: joining multicasts failed (%d)"
8236 				    " on %s - will use link layer "
8237 				    "broadcasts for multicast\n",
8238 				    dlea->dl_errno, ill->ill_name);
8239 
8240 				/*
8241 				 * Set up for multi_bcast; We are the
8242 				 * writer, so ok to access ill->ill_ipif
8243 				 * without any lock.
8244 				 */
8245 				mutex_enter(&ill->ill_phyint->phyint_lock);
8246 				ill->ill_phyint->phyint_flags |=
8247 				    PHYI_MULTI_BCAST;
8248 				mutex_exit(&ill->ill_phyint->phyint_lock);
8249 
8250 			}
8251 			freemsg(mp);	/* Don't want to pass this up */
8252 			return;
8253 		case DL_CAPABILITY_REQ:
8254 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8255 			    "DL_CAPABILITY REQ\n"));
8256 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8257 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8258 			ill_capability_done(ill);
8259 			freemsg(mp);
8260 			return;
8261 		}
8262 		/*
8263 		 * Note the error for IOCTL completion (mp1 is set when
8264 		 * ready to complete ioctl). If ill_ifname_pending_err is
8265 		 * set, an error occured during plumbing (ill_ifname_pending),
8266 		 * so we want to report that error.
8267 		 *
8268 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8269 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8270 		 * expected to get errack'd if the driver doesn't support
8271 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8272 		 * if these error conditions are encountered.
8273 		 */
8274 		if (mp1 != NULL) {
8275 			if (ill->ill_ifname_pending_err != 0)  {
8276 				err = ill->ill_ifname_pending_err;
8277 				ill->ill_ifname_pending_err = 0;
8278 			} else {
8279 				err = dlea->dl_unix_errno ?
8280 				    dlea->dl_unix_errno : ENXIO;
8281 			}
8282 		/*
8283 		 * If we're plumbing an interface and an error hasn't already
8284 		 * been saved, set ill_ifname_pending_err to the error passed
8285 		 * up. Ignore the error if log is B_FALSE (see comment above).
8286 		 */
8287 		} else if (log && ill->ill_ifname_pending &&
8288 		    ill->ill_ifname_pending_err == 0) {
8289 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8290 			    dlea->dl_unix_errno : ENXIO;
8291 		}
8292 
8293 		if (log)
8294 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8295 			    dlea->dl_errno, dlea->dl_unix_errno);
8296 		break;
8297 	case DL_CAPABILITY_ACK:
8298 		ill_capability_ack(ill, mp);
8299 		/*
8300 		 * The message has been handed off to ill_capability_ack
8301 		 * and must not be freed below
8302 		 */
8303 		mp = NULL;
8304 		break;
8305 
8306 	case DL_INFO_ACK:
8307 		/* Call a routine to handle this one. */
8308 		ill_dlpi_done(ill, DL_INFO_REQ);
8309 		ip_ll_subnet_defaults(ill, mp);
8310 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8311 		return;
8312 	case DL_BIND_ACK:
8313 		/*
8314 		 * We should have an IOCTL waiting on this unless
8315 		 * sent by ill_dl_phys, in which case just return
8316 		 */
8317 		ill_dlpi_done(ill, DL_BIND_REQ);
8318 		if (ill->ill_ifname_pending) {
8319 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8320 			    ill_t *, ill, mblk_t *, mp);
8321 			break;
8322 		}
8323 		if (!ioctl_aborted)
8324 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8325 		if (mp1 == NULL) {
8326 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8327 			break;
8328 		}
8329 		/*
8330 		 * mp1 was added by ill_dl_up(). if that is a result of
8331 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8332 		 */
8333 		if (connp != NULL)
8334 			q = CONNP_TO_WQ(connp);
8335 		/*
8336 		 * We are exclusive. So nothing can change even after
8337 		 * we get the pending mp.
8338 		 */
8339 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8340 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8341 
8342 		mutex_enter(&ill->ill_lock);
8343 		ill->ill_dl_up = 1;
8344 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8345 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8346 		mutex_exit(&ill->ill_lock);
8347 
8348 		/*
8349 		 * Now bring up the resolver; when that is complete, we'll
8350 		 * create IREs.  Note that we intentionally mirror what
8351 		 * ipif_up() would have done, because we got here by way of
8352 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8353 		 */
8354 		if (ill->ill_isv6) {
8355 			/*
8356 			 * v6 interfaces.
8357 			 * Unlike ARP which has to do another bind
8358 			 * and attach, once we get here we are
8359 			 * done with NDP
8360 			 */
8361 			(void) ipif_resolver_up(ipif, Res_act_initial);
8362 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8363 				err = ipif_up_done_v6(ipif);
8364 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8365 			/*
8366 			 * ARP and other v4 external resolvers.
8367 			 * Leave the pending mblk intact so that
8368 			 * the ioctl completes in ip_rput().
8369 			 */
8370 			if (connp != NULL)
8371 				mutex_enter(&connp->conn_lock);
8372 			mutex_enter(&ill->ill_lock);
8373 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8374 			mutex_exit(&ill->ill_lock);
8375 			if (connp != NULL)
8376 				mutex_exit(&connp->conn_lock);
8377 			if (success) {
8378 				err = ipif_resolver_up(ipif, Res_act_initial);
8379 				if (err == EINPROGRESS) {
8380 					freemsg(mp);
8381 					return;
8382 				}
8383 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8384 			} else {
8385 				/* The conn has started closing */
8386 				err = EINTR;
8387 			}
8388 		} else {
8389 			/*
8390 			 * This one is complete. Reply to pending ioctl.
8391 			 */
8392 			(void) ipif_resolver_up(ipif, Res_act_initial);
8393 			err = ipif_up_done(ipif);
8394 		}
8395 
8396 		if ((err == 0) && (ill->ill_up_ipifs)) {
8397 			err = ill_up_ipifs(ill, q, mp1);
8398 			if (err == EINPROGRESS) {
8399 				freemsg(mp);
8400 				return;
8401 			}
8402 		}
8403 
8404 		/*
8405 		 * If we have a moved ipif to bring up, and everything has
8406 		 * succeeded to this point, bring it up on the IPMP ill.
8407 		 * Otherwise, leave it down -- the admin can try to bring it
8408 		 * up by hand if need be.
8409 		 */
8410 		if (ill->ill_move_ipif != NULL) {
8411 			if (err != 0) {
8412 				ill->ill_move_ipif = NULL;
8413 			} else {
8414 				ipif = ill->ill_move_ipif;
8415 				ill->ill_move_ipif = NULL;
8416 				err = ipif_up(ipif, q, mp1);
8417 				if (err == EINPROGRESS) {
8418 					freemsg(mp);
8419 					return;
8420 				}
8421 			}
8422 		}
8423 		break;
8424 
8425 	case DL_NOTIFY_IND: {
8426 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8427 		uint_t orig_mtu;
8428 
8429 		switch (notify->dl_notification) {
8430 		case DL_NOTE_PHYS_ADDR:
8431 			err = ill_set_phys_addr(ill, mp);
8432 			break;
8433 
8434 		case DL_NOTE_REPLUMB:
8435 			/*
8436 			 * Directly return after calling ill_replumb().
8437 			 * Note that we should not free mp as it is reused
8438 			 * in the ill_replumb() function.
8439 			 */
8440 			err = ill_replumb(ill, mp);
8441 			return;
8442 
8443 		case DL_NOTE_FASTPATH_FLUSH:
8444 			nce_flush(ill, B_FALSE);
8445 			break;
8446 
8447 		case DL_NOTE_SDU_SIZE:
8448 			/*
8449 			 * The dce and fragmentation code can cope with
8450 			 * this changing while packets are being sent.
8451 			 * When packets are sent ip_output will discover
8452 			 * a change.
8453 			 *
8454 			 * Change the MTU size of the interface.
8455 			 */
8456 			mutex_enter(&ill->ill_lock);
8457 			ill->ill_current_frag = (uint_t)notify->dl_data;
8458 			if (ill->ill_current_frag > ill->ill_max_frag)
8459 				ill->ill_max_frag = ill->ill_current_frag;
8460 
8461 			orig_mtu = ill->ill_mtu;
8462 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8463 				ill->ill_mtu = ill->ill_current_frag;
8464 
8465 				/*
8466 				 * If ill_user_mtu was set (via
8467 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8468 				 */
8469 				if (ill->ill_user_mtu != 0 &&
8470 				    ill->ill_user_mtu < ill->ill_mtu)
8471 					ill->ill_mtu = ill->ill_user_mtu;
8472 
8473 				if (ill->ill_isv6) {
8474 					if (ill->ill_mtu < IPV6_MIN_MTU)
8475 						ill->ill_mtu = IPV6_MIN_MTU;
8476 				} else {
8477 					if (ill->ill_mtu < IP_MIN_MTU)
8478 						ill->ill_mtu = IP_MIN_MTU;
8479 				}
8480 			}
8481 			mutex_exit(&ill->ill_lock);
8482 			/*
8483 			 * Make sure all dce_generation checks find out
8484 			 * that ill_mtu has changed.
8485 			 */
8486 			if (orig_mtu != ill->ill_mtu) {
8487 				dce_increment_all_generations(ill->ill_isv6,
8488 				    ill->ill_ipst);
8489 			}
8490 
8491 			/*
8492 			 * Refresh IPMP meta-interface MTU if necessary.
8493 			 */
8494 			if (IS_UNDER_IPMP(ill))
8495 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8496 			break;
8497 
8498 		case DL_NOTE_LINK_UP:
8499 		case DL_NOTE_LINK_DOWN: {
8500 			/*
8501 			 * We are writer. ill / phyint / ipsq assocs stable.
8502 			 * The RUNNING flag reflects the state of the link.
8503 			 */
8504 			phyint_t *phyint = ill->ill_phyint;
8505 			uint64_t new_phyint_flags;
8506 			boolean_t changed = B_FALSE;
8507 			boolean_t went_up;
8508 
8509 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8510 			mutex_enter(&phyint->phyint_lock);
8511 
8512 			new_phyint_flags = went_up ?
8513 			    phyint->phyint_flags | PHYI_RUNNING :
8514 			    phyint->phyint_flags & ~PHYI_RUNNING;
8515 
8516 			if (IS_IPMP(ill)) {
8517 				new_phyint_flags = went_up ?
8518 				    new_phyint_flags & ~PHYI_FAILED :
8519 				    new_phyint_flags | PHYI_FAILED;
8520 			}
8521 
8522 			if (new_phyint_flags != phyint->phyint_flags) {
8523 				phyint->phyint_flags = new_phyint_flags;
8524 				changed = B_TRUE;
8525 			}
8526 			mutex_exit(&phyint->phyint_lock);
8527 			/*
8528 			 * ill_restart_dad handles the DAD restart and routing
8529 			 * socket notification logic.
8530 			 */
8531 			if (changed) {
8532 				ill_restart_dad(phyint->phyint_illv4, went_up);
8533 				ill_restart_dad(phyint->phyint_illv6, went_up);
8534 			}
8535 			break;
8536 		}
8537 		case DL_NOTE_PROMISC_ON_PHYS: {
8538 			phyint_t *phyint = ill->ill_phyint;
8539 
8540 			mutex_enter(&phyint->phyint_lock);
8541 			phyint->phyint_flags |= PHYI_PROMISC;
8542 			mutex_exit(&phyint->phyint_lock);
8543 			break;
8544 		}
8545 		case DL_NOTE_PROMISC_OFF_PHYS: {
8546 			phyint_t *phyint = ill->ill_phyint;
8547 
8548 			mutex_enter(&phyint->phyint_lock);
8549 			phyint->phyint_flags &= ~PHYI_PROMISC;
8550 			mutex_exit(&phyint->phyint_lock);
8551 			break;
8552 		}
8553 		case DL_NOTE_CAPAB_RENEG:
8554 			/*
8555 			 * Something changed on the driver side.
8556 			 * It wants us to renegotiate the capabilities
8557 			 * on this ill. One possible cause is the aggregation
8558 			 * interface under us where a port got added or
8559 			 * went away.
8560 			 *
8561 			 * If the capability negotiation is already done
8562 			 * or is in progress, reset the capabilities and
8563 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8564 			 * so that when the ack comes back, we can start
8565 			 * the renegotiation process.
8566 			 *
8567 			 * Note that if ill_capab_reneg is already B_TRUE
8568 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8569 			 * the capability resetting request has been sent
8570 			 * and the renegotiation has not been started yet;
8571 			 * nothing needs to be done in this case.
8572 			 */
8573 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8574 			ill_capability_reset(ill, B_TRUE);
8575 			ipsq_current_finish(ipsq);
8576 			break;
8577 		default:
8578 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8579 			    "type 0x%x for DL_NOTIFY_IND\n",
8580 			    notify->dl_notification));
8581 			break;
8582 		}
8583 
8584 		/*
8585 		 * As this is an asynchronous operation, we
8586 		 * should not call ill_dlpi_done
8587 		 */
8588 		break;
8589 	}
8590 	case DL_NOTIFY_ACK: {
8591 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8592 
8593 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8594 			ill->ill_note_link = 1;
8595 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8596 		break;
8597 	}
8598 	case DL_PHYS_ADDR_ACK: {
8599 		/*
8600 		 * As part of plumbing the interface via SIOCSLIFNAME,
8601 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8602 		 * whose answers we receive here.  As each answer is received,
8603 		 * we call ill_dlpi_done() to dispatch the next request as
8604 		 * we're processing the current one.  Once all answers have
8605 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8606 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8607 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8608 		 * available, but we know the ioctl is pending on ill_wq.)
8609 		 */
8610 		uint_t	paddrlen, paddroff;
8611 		uint8_t	*addr;
8612 
8613 		paddrreq = ill->ill_phys_addr_pend;
8614 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8615 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8616 		addr = mp->b_rptr + paddroff;
8617 
8618 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8619 		if (paddrreq == DL_IPV6_TOKEN) {
8620 			/*
8621 			 * bcopy to low-order bits of ill_token
8622 			 *
8623 			 * XXX Temporary hack - currently, all known tokens
8624 			 * are 64 bits, so I'll cheat for the moment.
8625 			 */
8626 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8627 			ill->ill_token_length = paddrlen;
8628 			break;
8629 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8630 			ASSERT(ill->ill_nd_lla_mp == NULL);
8631 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8632 			mp = NULL;
8633 			break;
8634 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8635 			ASSERT(ill->ill_dest_addr_mp == NULL);
8636 			ill->ill_dest_addr_mp = mp;
8637 			ill->ill_dest_addr = addr;
8638 			mp = NULL;
8639 			if (ill->ill_isv6) {
8640 				ill_setdesttoken(ill);
8641 				ipif_setdestlinklocal(ill->ill_ipif);
8642 			}
8643 			break;
8644 		}
8645 
8646 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8647 		ASSERT(ill->ill_phys_addr_mp == NULL);
8648 		if (!ill->ill_ifname_pending)
8649 			break;
8650 		ill->ill_ifname_pending = 0;
8651 		if (!ioctl_aborted)
8652 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8653 		if (mp1 != NULL) {
8654 			ASSERT(connp == NULL);
8655 			q = ill->ill_wq;
8656 		}
8657 		/*
8658 		 * If any error acks received during the plumbing sequence,
8659 		 * ill_ifname_pending_err will be set. Break out and send up
8660 		 * the error to the pending ioctl.
8661 		 */
8662 		if (ill->ill_ifname_pending_err != 0) {
8663 			err = ill->ill_ifname_pending_err;
8664 			ill->ill_ifname_pending_err = 0;
8665 			break;
8666 		}
8667 
8668 		ill->ill_phys_addr_mp = mp;
8669 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8670 		mp = NULL;
8671 
8672 		/*
8673 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8674 		 * provider doesn't support physical addresses.  We check both
8675 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8676 		 * not have physical addresses, but historically adversises a
8677 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8678 		 * its DL_PHYS_ADDR_ACK.
8679 		 */
8680 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8681 			ill->ill_phys_addr = NULL;
8682 		} else if (paddrlen != ill->ill_phys_addr_length) {
8683 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8684 			    paddrlen, ill->ill_phys_addr_length));
8685 			err = EINVAL;
8686 			break;
8687 		}
8688 
8689 		if (ill->ill_nd_lla_mp == NULL) {
8690 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8691 				err = ENOMEM;
8692 				break;
8693 			}
8694 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8695 		}
8696 
8697 		if (ill->ill_isv6) {
8698 			ill_setdefaulttoken(ill);
8699 			ipif_setlinklocal(ill->ill_ipif);
8700 		}
8701 		break;
8702 	}
8703 	case DL_OK_ACK:
8704 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8705 		    dl_primstr((int)dloa->dl_correct_primitive),
8706 		    dloa->dl_correct_primitive));
8707 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8708 		    char *, dl_primstr(dloa->dl_correct_primitive),
8709 		    ill_t *, ill);
8710 
8711 		switch (dloa->dl_correct_primitive) {
8712 		case DL_ENABMULTI_REQ:
8713 		case DL_DISABMULTI_REQ:
8714 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8715 			break;
8716 		case DL_PROMISCON_REQ:
8717 		case DL_PROMISCOFF_REQ:
8718 		case DL_UNBIND_REQ:
8719 		case DL_ATTACH_REQ:
8720 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8721 			break;
8722 		}
8723 		break;
8724 	default:
8725 		break;
8726 	}
8727 
8728 	freemsg(mp);
8729 	if (mp1 == NULL)
8730 		return;
8731 
8732 	/*
8733 	 * The operation must complete without EINPROGRESS since
8734 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8735 	 * the operation will be stuck forever inside the IPSQ.
8736 	 */
8737 	ASSERT(err != EINPROGRESS);
8738 
8739 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8740 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8741 	    ipif_t *, NULL);
8742 
8743 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8744 	case 0:
8745 		ipsq_current_finish(ipsq);
8746 		break;
8747 
8748 	case SIOCSLIFNAME:
8749 	case IF_UNITSEL: {
8750 		ill_t *ill_other = ILL_OTHER(ill);
8751 
8752 		/*
8753 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8754 		 * ill has a peer which is in an IPMP group, then place ill
8755 		 * into the same group.  One catch: although ifconfig plumbs
8756 		 * the appropriate IPMP meta-interface prior to plumbing this
8757 		 * ill, it is possible for multiple ifconfig applications to
8758 		 * race (or for another application to adjust plumbing), in
8759 		 * which case the IPMP meta-interface we need will be missing.
8760 		 * If so, kick the phyint out of the group.
8761 		 */
8762 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8763 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8764 			ipmp_illgrp_t	*illg;
8765 
8766 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8767 			if (illg == NULL)
8768 				ipmp_phyint_leave_grp(ill->ill_phyint);
8769 			else
8770 				ipmp_ill_join_illgrp(ill, illg);
8771 		}
8772 
8773 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8774 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8775 		else
8776 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8777 		break;
8778 	}
8779 	case SIOCLIFADDIF:
8780 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8781 		break;
8782 
8783 	default:
8784 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8785 		break;
8786 	}
8787 }
8788 
8789 /*
8790  * ip_rput_other is called by ip_rput to handle messages modifying the global
8791  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8792  */
8793 /* ARGSUSED */
8794 void
8795 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8796 {
8797 	ill_t		*ill = q->q_ptr;
8798 	struct iocblk	*iocp;
8799 
8800 	ip1dbg(("ip_rput_other "));
8801 	if (ipsq != NULL) {
8802 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8803 		ASSERT(ipsq->ipsq_xop ==
8804 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8805 	}
8806 
8807 	switch (mp->b_datap->db_type) {
8808 	case M_ERROR:
8809 	case M_HANGUP:
8810 		/*
8811 		 * The device has a problem.  We force the ILL down.  It can
8812 		 * be brought up again manually using SIOCSIFFLAGS (via
8813 		 * ifconfig or equivalent).
8814 		 */
8815 		ASSERT(ipsq != NULL);
8816 		if (mp->b_rptr < mp->b_wptr)
8817 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8818 		if (ill->ill_error == 0)
8819 			ill->ill_error = ENXIO;
8820 		if (!ill_down_start(q, mp))
8821 			return;
8822 		ipif_all_down_tail(ipsq, q, mp, NULL);
8823 		break;
8824 	case M_IOCNAK: {
8825 		iocp = (struct iocblk *)mp->b_rptr;
8826 
8827 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8828 		/*
8829 		 * If this was the first attempt, turn off the fastpath
8830 		 * probing.
8831 		 */
8832 		mutex_enter(&ill->ill_lock);
8833 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8834 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8835 			mutex_exit(&ill->ill_lock);
8836 			/*
8837 			 * don't flush the nce_t entries: we use them
8838 			 * as an index to the ncec itself.
8839 			 */
8840 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8841 			    ill->ill_name));
8842 		} else {
8843 			mutex_exit(&ill->ill_lock);
8844 		}
8845 		freemsg(mp);
8846 		break;
8847 	}
8848 	default:
8849 		ASSERT(0);
8850 		break;
8851 	}
8852 }
8853 
8854 /*
8855  * Update any source route, record route or timestamp options
8856  * When it fails it has consumed the message and BUMPed the MIB.
8857  */
8858 boolean_t
8859 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8860     ip_recv_attr_t *ira)
8861 {
8862 	ipoptp_t	opts;
8863 	uchar_t		*opt;
8864 	uint8_t		optval;
8865 	uint8_t		optlen;
8866 	ipaddr_t	dst;
8867 	ipaddr_t	ifaddr;
8868 	uint32_t	ts;
8869 	timestruc_t	now;
8870 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
8871 
8872 	ip2dbg(("ip_forward_options\n"));
8873 	dst = ipha->ipha_dst;
8874 	for (optval = ipoptp_first(&opts, ipha);
8875 	    optval != IPOPT_EOL;
8876 	    optval = ipoptp_next(&opts)) {
8877 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
8878 		opt = opts.ipoptp_cur;
8879 		optlen = opts.ipoptp_len;
8880 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
8881 		    optval, opts.ipoptp_len));
8882 		switch (optval) {
8883 			uint32_t off;
8884 		case IPOPT_SSRR:
8885 		case IPOPT_LSRR:
8886 			/* Check if adminstratively disabled */
8887 			if (!ipst->ips_ip_forward_src_routed) {
8888 				BUMP_MIB(dst_ill->ill_ip_mib,
8889 				    ipIfStatsForwProhibits);
8890 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
8891 				    mp, dst_ill);
8892 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
8893 				    ira);
8894 				return (B_FALSE);
8895 			}
8896 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8897 				/*
8898 				 * Must be partial since ip_input_options
8899 				 * checked for strict.
8900 				 */
8901 				break;
8902 			}
8903 			off = opt[IPOPT_OFFSET];
8904 			off--;
8905 		redo_srr:
8906 			if (optlen < IP_ADDR_LEN ||
8907 			    off > optlen - IP_ADDR_LEN) {
8908 				/* End of source route */
8909 				ip1dbg((
8910 				    "ip_forward_options: end of SR\n"));
8911 				break;
8912 			}
8913 			/* Pick a reasonable address on the outbound if */
8914 			ASSERT(dst_ill != NULL);
8915 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8916 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8917 			    NULL) != 0) {
8918 				/* No source! Shouldn't happen */
8919 				ifaddr = INADDR_ANY;
8920 			}
8921 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8922 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8923 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
8924 			    ntohl(dst)));
8925 
8926 			/*
8927 			 * Check if our address is present more than
8928 			 * once as consecutive hops in source route.
8929 			 */
8930 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
8931 				off += IP_ADDR_LEN;
8932 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8933 				goto redo_srr;
8934 			}
8935 			ipha->ipha_dst = dst;
8936 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8937 			break;
8938 		case IPOPT_RR:
8939 			off = opt[IPOPT_OFFSET];
8940 			off--;
8941 			if (optlen < IP_ADDR_LEN ||
8942 			    off > optlen - IP_ADDR_LEN) {
8943 				/* No more room - ignore */
8944 				ip1dbg((
8945 				    "ip_forward_options: end of RR\n"));
8946 				break;
8947 			}
8948 			/* Pick a reasonable address on the outbound if */
8949 			ASSERT(dst_ill != NULL);
8950 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8951 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8952 			    NULL) != 0) {
8953 				/* No source! Shouldn't happen */
8954 				ifaddr = INADDR_ANY;
8955 			}
8956 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8957 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8958 			break;
8959 		case IPOPT_TS:
8960 			/* Insert timestamp if there is room */
8961 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
8962 			case IPOPT_TS_TSONLY:
8963 				off = IPOPT_TS_TIMELEN;
8964 				break;
8965 			case IPOPT_TS_PRESPEC:
8966 			case IPOPT_TS_PRESPEC_RFC791:
8967 				/* Verify that the address matched */
8968 				off = opt[IPOPT_OFFSET] - 1;
8969 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8970 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8971 					/* Not for us */
8972 					break;
8973 				}
8974 				/* FALLTHRU */
8975 			case IPOPT_TS_TSANDADDR:
8976 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
8977 				break;
8978 			default:
8979 				/*
8980 				 * ip_*put_options should have already
8981 				 * dropped this packet.
8982 				 */
8983 				cmn_err(CE_PANIC, "ip_forward_options: "
8984 				    "unknown IT - bug in ip_input_options?\n");
8985 				return (B_TRUE);	/* Keep "lint" happy */
8986 			}
8987 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
8988 				/* Increase overflow counter */
8989 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
8990 				opt[IPOPT_POS_OV_FLG] =
8991 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
8992 				    (off << 4));
8993 				break;
8994 			}
8995 			off = opt[IPOPT_OFFSET] - 1;
8996 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
8997 			case IPOPT_TS_PRESPEC:
8998 			case IPOPT_TS_PRESPEC_RFC791:
8999 			case IPOPT_TS_TSANDADDR:
9000 				/* Pick a reasonable addr on the outbound if */
9001 				ASSERT(dst_ill != NULL);
9002 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9003 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9004 				    NULL, NULL) != 0) {
9005 					/* No source! Shouldn't happen */
9006 					ifaddr = INADDR_ANY;
9007 				}
9008 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9009 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9010 				/* FALLTHRU */
9011 			case IPOPT_TS_TSONLY:
9012 				off = opt[IPOPT_OFFSET] - 1;
9013 				/* Compute # of milliseconds since midnight */
9014 				gethrestime(&now);
9015 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9016 				    now.tv_nsec / (NANOSEC / MILLISEC);
9017 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9018 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9019 				break;
9020 			}
9021 			break;
9022 		}
9023 	}
9024 	return (B_TRUE);
9025 }
9026 
9027 /*
9028  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9029  * returns 'true' if there are still fragments left on the queue, in
9030  * which case we restart the timer.
9031  */
9032 void
9033 ill_frag_timer(void *arg)
9034 {
9035 	ill_t	*ill = (ill_t *)arg;
9036 	boolean_t frag_pending;
9037 	ip_stack_t *ipst = ill->ill_ipst;
9038 	time_t	timeout;
9039 
9040 	mutex_enter(&ill->ill_lock);
9041 	ASSERT(!ill->ill_fragtimer_executing);
9042 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9043 		ill->ill_frag_timer_id = 0;
9044 		mutex_exit(&ill->ill_lock);
9045 		return;
9046 	}
9047 	ill->ill_fragtimer_executing = 1;
9048 	mutex_exit(&ill->ill_lock);
9049 
9050 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9051 	    ipst->ips_ip_reassembly_timeout);
9052 
9053 	frag_pending = ill_frag_timeout(ill, timeout);
9054 
9055 	/*
9056 	 * Restart the timer, if we have fragments pending or if someone
9057 	 * wanted us to be scheduled again.
9058 	 */
9059 	mutex_enter(&ill->ill_lock);
9060 	ill->ill_fragtimer_executing = 0;
9061 	ill->ill_frag_timer_id = 0;
9062 	if (frag_pending || ill->ill_fragtimer_needrestart)
9063 		ill_frag_timer_start(ill);
9064 	mutex_exit(&ill->ill_lock);
9065 }
9066 
9067 void
9068 ill_frag_timer_start(ill_t *ill)
9069 {
9070 	ip_stack_t *ipst = ill->ill_ipst;
9071 	clock_t	timeo_ms;
9072 
9073 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9074 
9075 	/* If the ill is closing or opening don't proceed */
9076 	if (ill->ill_state_flags & ILL_CONDEMNED)
9077 		return;
9078 
9079 	if (ill->ill_fragtimer_executing) {
9080 		/*
9081 		 * ill_frag_timer is currently executing. Just record the
9082 		 * the fact that we want the timer to be restarted.
9083 		 * ill_frag_timer will post a timeout before it returns,
9084 		 * ensuring it will be called again.
9085 		 */
9086 		ill->ill_fragtimer_needrestart = 1;
9087 		return;
9088 	}
9089 
9090 	if (ill->ill_frag_timer_id == 0) {
9091 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9092 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9093 
9094 		/*
9095 		 * The timer is neither running nor is the timeout handler
9096 		 * executing. Post a timeout so that ill_frag_timer will be
9097 		 * called
9098 		 */
9099 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9100 		    MSEC_TO_TICK(timeo_ms >> 1));
9101 		ill->ill_fragtimer_needrestart = 0;
9102 	}
9103 }
9104 
9105 /*
9106  * Update any source route, record route or timestamp options.
9107  * Check that we are at end of strict source route.
9108  * The options have already been checked for sanity in ip_input_options().
9109  */
9110 boolean_t
9111 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9112 {
9113 	ipoptp_t	opts;
9114 	uchar_t		*opt;
9115 	uint8_t		optval;
9116 	uint8_t		optlen;
9117 	ipaddr_t	dst;
9118 	ipaddr_t	ifaddr;
9119 	uint32_t	ts;
9120 	timestruc_t	now;
9121 	ill_t		*ill = ira->ira_ill;
9122 	ip_stack_t	*ipst = ill->ill_ipst;
9123 
9124 	ip2dbg(("ip_input_local_options\n"));
9125 
9126 	for (optval = ipoptp_first(&opts, ipha);
9127 	    optval != IPOPT_EOL;
9128 	    optval = ipoptp_next(&opts)) {
9129 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9130 		opt = opts.ipoptp_cur;
9131 		optlen = opts.ipoptp_len;
9132 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9133 		    optval, optlen));
9134 		switch (optval) {
9135 			uint32_t off;
9136 		case IPOPT_SSRR:
9137 		case IPOPT_LSRR:
9138 			off = opt[IPOPT_OFFSET];
9139 			off--;
9140 			if (optlen < IP_ADDR_LEN ||
9141 			    off > optlen - IP_ADDR_LEN) {
9142 				/* End of source route */
9143 				ip1dbg(("ip_input_local_options: end of SR\n"));
9144 				break;
9145 			}
9146 			/*
9147 			 * This will only happen if two consecutive entries
9148 			 * in the source route contains our address or if
9149 			 * it is a packet with a loose source route which
9150 			 * reaches us before consuming the whole source route
9151 			 */
9152 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9153 			if (optval == IPOPT_SSRR) {
9154 				goto bad_src_route;
9155 			}
9156 			/*
9157 			 * Hack: instead of dropping the packet truncate the
9158 			 * source route to what has been used by filling the
9159 			 * rest with IPOPT_NOP.
9160 			 */
9161 			opt[IPOPT_OLEN] = (uint8_t)off;
9162 			while (off < optlen) {
9163 				opt[off++] = IPOPT_NOP;
9164 			}
9165 			break;
9166 		case IPOPT_RR:
9167 			off = opt[IPOPT_OFFSET];
9168 			off--;
9169 			if (optlen < IP_ADDR_LEN ||
9170 			    off > optlen - IP_ADDR_LEN) {
9171 				/* No more room - ignore */
9172 				ip1dbg((
9173 				    "ip_input_local_options: end of RR\n"));
9174 				break;
9175 			}
9176 			/* Pick a reasonable address on the outbound if */
9177 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9178 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9179 			    NULL) != 0) {
9180 				/* No source! Shouldn't happen */
9181 				ifaddr = INADDR_ANY;
9182 			}
9183 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9184 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9185 			break;
9186 		case IPOPT_TS:
9187 			/* Insert timestamp if there is romm */
9188 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9189 			case IPOPT_TS_TSONLY:
9190 				off = IPOPT_TS_TIMELEN;
9191 				break;
9192 			case IPOPT_TS_PRESPEC:
9193 			case IPOPT_TS_PRESPEC_RFC791:
9194 				/* Verify that the address matched */
9195 				off = opt[IPOPT_OFFSET] - 1;
9196 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9197 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9198 					/* Not for us */
9199 					break;
9200 				}
9201 				/* FALLTHRU */
9202 			case IPOPT_TS_TSANDADDR:
9203 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9204 				break;
9205 			default:
9206 				/*
9207 				 * ip_*put_options should have already
9208 				 * dropped this packet.
9209 				 */
9210 				cmn_err(CE_PANIC, "ip_input_local_options: "
9211 				    "unknown IT - bug in ip_input_options?\n");
9212 				return (B_TRUE);	/* Keep "lint" happy */
9213 			}
9214 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9215 				/* Increase overflow counter */
9216 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9217 				opt[IPOPT_POS_OV_FLG] =
9218 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9219 				    (off << 4));
9220 				break;
9221 			}
9222 			off = opt[IPOPT_OFFSET] - 1;
9223 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9224 			case IPOPT_TS_PRESPEC:
9225 			case IPOPT_TS_PRESPEC_RFC791:
9226 			case IPOPT_TS_TSANDADDR:
9227 				/* Pick a reasonable addr on the outbound if */
9228 				if (ip_select_source_v4(ill, INADDR_ANY,
9229 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9230 				    &ifaddr, NULL, NULL) != 0) {
9231 					/* No source! Shouldn't happen */
9232 					ifaddr = INADDR_ANY;
9233 				}
9234 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9235 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9236 				/* FALLTHRU */
9237 			case IPOPT_TS_TSONLY:
9238 				off = opt[IPOPT_OFFSET] - 1;
9239 				/* Compute # of milliseconds since midnight */
9240 				gethrestime(&now);
9241 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9242 				    now.tv_nsec / (NANOSEC / MILLISEC);
9243 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9244 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9245 				break;
9246 			}
9247 			break;
9248 		}
9249 	}
9250 	return (B_TRUE);
9251 
9252 bad_src_route:
9253 	/* make sure we clear any indication of a hardware checksum */
9254 	DB_CKSUMFLAGS(mp) = 0;
9255 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9256 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9257 	return (B_FALSE);
9258 
9259 }
9260 
9261 /*
9262  * Process IP options in an inbound packet.  Always returns the nexthop.
9263  * Normally this is the passed in nexthop, but if there is an option
9264  * that effects the nexthop (such as a source route) that will be returned.
9265  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9266  * and mp freed.
9267  */
9268 ipaddr_t
9269 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9270     ip_recv_attr_t *ira, int *errorp)
9271 {
9272 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9273 	ipoptp_t	opts;
9274 	uchar_t		*opt;
9275 	uint8_t		optval;
9276 	uint8_t		optlen;
9277 	intptr_t	code = 0;
9278 	ire_t		*ire;
9279 
9280 	ip2dbg(("ip_input_options\n"));
9281 	*errorp = 0;
9282 	for (optval = ipoptp_first(&opts, ipha);
9283 	    optval != IPOPT_EOL;
9284 	    optval = ipoptp_next(&opts)) {
9285 		opt = opts.ipoptp_cur;
9286 		optlen = opts.ipoptp_len;
9287 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9288 		    optval, optlen));
9289 		/*
9290 		 * Note: we need to verify the checksum before we
9291 		 * modify anything thus this routine only extracts the next
9292 		 * hop dst from any source route.
9293 		 */
9294 		switch (optval) {
9295 			uint32_t off;
9296 		case IPOPT_SSRR:
9297 		case IPOPT_LSRR:
9298 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9299 				if (optval == IPOPT_SSRR) {
9300 					ip1dbg(("ip_input_options: not next"
9301 					    " strict source route 0x%x\n",
9302 					    ntohl(dst)));
9303 					code = (char *)&ipha->ipha_dst -
9304 					    (char *)ipha;
9305 					goto param_prob; /* RouterReq's */
9306 				}
9307 				ip2dbg(("ip_input_options: "
9308 				    "not next source route 0x%x\n",
9309 				    ntohl(dst)));
9310 				break;
9311 			}
9312 
9313 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9314 				ip1dbg((
9315 				    "ip_input_options: bad option offset\n"));
9316 				code = (char *)&opt[IPOPT_OLEN] -
9317 				    (char *)ipha;
9318 				goto param_prob;
9319 			}
9320 			off = opt[IPOPT_OFFSET];
9321 			off--;
9322 		redo_srr:
9323 			if (optlen < IP_ADDR_LEN ||
9324 			    off > optlen - IP_ADDR_LEN) {
9325 				/* End of source route */
9326 				ip1dbg(("ip_input_options: end of SR\n"));
9327 				break;
9328 			}
9329 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9330 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9331 			    ntohl(dst)));
9332 
9333 			/*
9334 			 * Check if our address is present more than
9335 			 * once as consecutive hops in source route.
9336 			 * XXX verify per-interface ip_forwarding
9337 			 * for source route?
9338 			 */
9339 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9340 				off += IP_ADDR_LEN;
9341 				goto redo_srr;
9342 			}
9343 
9344 			if (dst == htonl(INADDR_LOOPBACK)) {
9345 				ip1dbg(("ip_input_options: loopback addr in "
9346 				    "source route!\n"));
9347 				goto bad_src_route;
9348 			}
9349 			/*
9350 			 * For strict: verify that dst is directly
9351 			 * reachable.
9352 			 */
9353 			if (optval == IPOPT_SSRR) {
9354 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9355 				    IRE_IF_ALL, NULL, ALL_ZONES,
9356 				    ira->ira_tsl,
9357 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9358 				    NULL);
9359 				if (ire == NULL) {
9360 					ip1dbg(("ip_input_options: SSRR not "
9361 					    "directly reachable: 0x%x\n",
9362 					    ntohl(dst)));
9363 					goto bad_src_route;
9364 				}
9365 				ire_refrele(ire);
9366 			}
9367 			/*
9368 			 * Defer update of the offset and the record route
9369 			 * until the packet is forwarded.
9370 			 */
9371 			break;
9372 		case IPOPT_RR:
9373 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9374 				ip1dbg((
9375 				    "ip_input_options: bad option offset\n"));
9376 				code = (char *)&opt[IPOPT_OLEN] -
9377 				    (char *)ipha;
9378 				goto param_prob;
9379 			}
9380 			break;
9381 		case IPOPT_TS:
9382 			/*
9383 			 * Verify that length >= 5 and that there is either
9384 			 * room for another timestamp or that the overflow
9385 			 * counter is not maxed out.
9386 			 */
9387 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9388 			if (optlen < IPOPT_MINLEN_IT) {
9389 				goto param_prob;
9390 			}
9391 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9392 				ip1dbg((
9393 				    "ip_input_options: bad option offset\n"));
9394 				code = (char *)&opt[IPOPT_OFFSET] -
9395 				    (char *)ipha;
9396 				goto param_prob;
9397 			}
9398 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9399 			case IPOPT_TS_TSONLY:
9400 				off = IPOPT_TS_TIMELEN;
9401 				break;
9402 			case IPOPT_TS_TSANDADDR:
9403 			case IPOPT_TS_PRESPEC:
9404 			case IPOPT_TS_PRESPEC_RFC791:
9405 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9406 				break;
9407 			default:
9408 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9409 				    (char *)ipha;
9410 				goto param_prob;
9411 			}
9412 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9413 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9414 				/*
9415 				 * No room and the overflow counter is 15
9416 				 * already.
9417 				 */
9418 				goto param_prob;
9419 			}
9420 			break;
9421 		}
9422 	}
9423 
9424 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9425 		return (dst);
9426 	}
9427 
9428 	ip1dbg(("ip_input_options: error processing IP options."));
9429 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9430 
9431 param_prob:
9432 	/* make sure we clear any indication of a hardware checksum */
9433 	DB_CKSUMFLAGS(mp) = 0;
9434 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9435 	icmp_param_problem(mp, (uint8_t)code, ira);
9436 	*errorp = -1;
9437 	return (dst);
9438 
9439 bad_src_route:
9440 	/* make sure we clear any indication of a hardware checksum */
9441 	DB_CKSUMFLAGS(mp) = 0;
9442 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9443 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9444 	*errorp = -1;
9445 	return (dst);
9446 }
9447 
9448 /*
9449  * IP & ICMP info in >=14 msg's ...
9450  *  - ip fixed part (mib2_ip_t)
9451  *  - icmp fixed part (mib2_icmp_t)
9452  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9453  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9454  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9455  *  - ipRouteAttributeTable (ip 102)	labeled routes
9456  *  - ip multicast membership (ip_member_t)
9457  *  - ip multicast source filtering (ip_grpsrc_t)
9458  *  - igmp fixed part (struct igmpstat)
9459  *  - multicast routing stats (struct mrtstat)
9460  *  - multicast routing vifs (array of struct vifctl)
9461  *  - multicast routing routes (array of struct mfcctl)
9462  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9463  *					One per ill plus one generic
9464  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9465  *					One per ill plus one generic
9466  *  - ipv6RouteEntry			all IPv6 IREs
9467  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9468  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9469  *  - ipv6AddrEntry			all IPv6 ipifs
9470  *  - ipv6 multicast membership (ipv6_member_t)
9471  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9472  *
9473  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9474  * already filled in by the caller.
9475  * Return value of 0 indicates that no messages were sent and caller
9476  * should free mpctl.
9477  */
9478 int
9479 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
9480 {
9481 	ip_stack_t *ipst;
9482 	sctp_stack_t *sctps;
9483 
9484 	if (q->q_next != NULL) {
9485 		ipst = ILLQ_TO_IPST(q);
9486 	} else {
9487 		ipst = CONNQ_TO_IPST(q);
9488 	}
9489 	ASSERT(ipst != NULL);
9490 	sctps = ipst->ips_netstack->netstack_sctp;
9491 
9492 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9493 		return (0);
9494 	}
9495 
9496 	/*
9497 	 * For the purposes of the (broken) packet shell use
9498 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9499 	 * to make TCP and UDP appear first in the list of mib items.
9500 	 * TBD: We could expand this and use it in netstat so that
9501 	 * the kernel doesn't have to produce large tables (connections,
9502 	 * routes, etc) when netstat only wants the statistics or a particular
9503 	 * table.
9504 	 */
9505 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9506 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9507 			return (1);
9508 		}
9509 	}
9510 
9511 	if (level != MIB2_TCP) {
9512 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
9513 			return (1);
9514 		}
9515 	}
9516 
9517 	if (level != MIB2_UDP) {
9518 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
9519 			return (1);
9520 		}
9521 	}
9522 
9523 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9524 	    ipst)) == NULL) {
9525 		return (1);
9526 	}
9527 
9528 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
9529 		return (1);
9530 	}
9531 
9532 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9533 		return (1);
9534 	}
9535 
9536 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9537 		return (1);
9538 	}
9539 
9540 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9541 		return (1);
9542 	}
9543 
9544 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9545 		return (1);
9546 	}
9547 
9548 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
9549 		return (1);
9550 	}
9551 
9552 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
9553 		return (1);
9554 	}
9555 
9556 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9557 		return (1);
9558 	}
9559 
9560 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9561 		return (1);
9562 	}
9563 
9564 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9565 		return (1);
9566 	}
9567 
9568 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9569 		return (1);
9570 	}
9571 
9572 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9573 		return (1);
9574 	}
9575 
9576 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9577 		return (1);
9578 	}
9579 
9580 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9581 	if (mpctl == NULL)
9582 		return (1);
9583 
9584 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9585 	if (mpctl == NULL)
9586 		return (1);
9587 
9588 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9589 		return (1);
9590 	}
9591 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9592 		return (1);
9593 	}
9594 	freemsg(mpctl);
9595 	return (1);
9596 }
9597 
9598 /* Get global (legacy) IPv4 statistics */
9599 static mblk_t *
9600 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9601     ip_stack_t *ipst)
9602 {
9603 	mib2_ip_t		old_ip_mib;
9604 	struct opthdr		*optp;
9605 	mblk_t			*mp2ctl;
9606 
9607 	/*
9608 	 * make a copy of the original message
9609 	 */
9610 	mp2ctl = copymsg(mpctl);
9611 
9612 	/* fixed length IP structure... */
9613 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9614 	optp->level = MIB2_IP;
9615 	optp->name = 0;
9616 	SET_MIB(old_ip_mib.ipForwarding,
9617 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9618 	SET_MIB(old_ip_mib.ipDefaultTTL,
9619 	    (uint32_t)ipst->ips_ip_def_ttl);
9620 	SET_MIB(old_ip_mib.ipReasmTimeout,
9621 	    ipst->ips_ip_reassembly_timeout);
9622 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9623 	    sizeof (mib2_ipAddrEntry_t));
9624 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9625 	    sizeof (mib2_ipRouteEntry_t));
9626 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9627 	    sizeof (mib2_ipNetToMediaEntry_t));
9628 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9629 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9630 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9631 	    sizeof (mib2_ipAttributeEntry_t));
9632 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9633 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9634 
9635 	/*
9636 	 * Grab the statistics from the new IP MIB
9637 	 */
9638 	SET_MIB(old_ip_mib.ipInReceives,
9639 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9640 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9641 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9642 	SET_MIB(old_ip_mib.ipForwDatagrams,
9643 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9644 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9645 	    ipmib->ipIfStatsInUnknownProtos);
9646 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9647 	SET_MIB(old_ip_mib.ipInDelivers,
9648 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9649 	SET_MIB(old_ip_mib.ipOutRequests,
9650 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9651 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9652 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9653 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9654 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9655 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9656 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9657 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9658 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9659 
9660 	/* ipRoutingDiscards is not being used */
9661 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9662 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9663 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9664 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9665 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9666 	    ipmib->ipIfStatsReasmDuplicates);
9667 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9668 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9669 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9670 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9671 	SET_MIB(old_ip_mib.rawipInOverflows,
9672 	    ipmib->rawipIfStatsInOverflows);
9673 
9674 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9675 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9676 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9677 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9678 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9679 	    ipmib->ipIfStatsOutSwitchIPVersion);
9680 
9681 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9682 	    (int)sizeof (old_ip_mib))) {
9683 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9684 		    (uint_t)sizeof (old_ip_mib)));
9685 	}
9686 
9687 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9688 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9689 	    (int)optp->level, (int)optp->name, (int)optp->len));
9690 	qreply(q, mpctl);
9691 	return (mp2ctl);
9692 }
9693 
9694 /* Per interface IPv4 statistics */
9695 static mblk_t *
9696 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9697 {
9698 	struct opthdr		*optp;
9699 	mblk_t			*mp2ctl;
9700 	ill_t			*ill;
9701 	ill_walk_context_t	ctx;
9702 	mblk_t			*mp_tail = NULL;
9703 	mib2_ipIfStatsEntry_t	global_ip_mib;
9704 
9705 	/*
9706 	 * Make a copy of the original message
9707 	 */
9708 	mp2ctl = copymsg(mpctl);
9709 
9710 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9711 	optp->level = MIB2_IP;
9712 	optp->name = MIB2_IP_TRAFFIC_STATS;
9713 	/* Include "unknown interface" ip_mib */
9714 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9715 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9716 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9717 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9718 	    (ipst->ips_ip_forwarding ? 1 : 2));
9719 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9720 	    (uint32_t)ipst->ips_ip_def_ttl);
9721 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9722 	    sizeof (mib2_ipIfStatsEntry_t));
9723 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9724 	    sizeof (mib2_ipAddrEntry_t));
9725 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9726 	    sizeof (mib2_ipRouteEntry_t));
9727 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9728 	    sizeof (mib2_ipNetToMediaEntry_t));
9729 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9730 	    sizeof (ip_member_t));
9731 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9732 	    sizeof (ip_grpsrc_t));
9733 
9734 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9735 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
9736 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9737 		    "failed to allocate %u bytes\n",
9738 		    (uint_t)sizeof (ipst->ips_ip_mib)));
9739 	}
9740 
9741 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9742 
9743 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9744 	ill = ILL_START_WALK_V4(&ctx, ipst);
9745 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9746 		ill->ill_ip_mib->ipIfStatsIfIndex =
9747 		    ill->ill_phyint->phyint_ifindex;
9748 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9749 		    (ipst->ips_ip_forwarding ? 1 : 2));
9750 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9751 		    (uint32_t)ipst->ips_ip_def_ttl);
9752 
9753 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9754 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9755 		    (char *)ill->ill_ip_mib,
9756 		    (int)sizeof (*ill->ill_ip_mib))) {
9757 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9758 			    "failed to allocate %u bytes\n",
9759 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9760 		}
9761 	}
9762 	rw_exit(&ipst->ips_ill_g_lock);
9763 
9764 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9765 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9766 	    "level %d, name %d, len %d\n",
9767 	    (int)optp->level, (int)optp->name, (int)optp->len));
9768 	qreply(q, mpctl);
9769 
9770 	if (mp2ctl == NULL)
9771 		return (NULL);
9772 
9773 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
9774 }
9775 
9776 /* Global IPv4 ICMP statistics */
9777 static mblk_t *
9778 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9779 {
9780 	struct opthdr		*optp;
9781 	mblk_t			*mp2ctl;
9782 
9783 	/*
9784 	 * Make a copy of the original message
9785 	 */
9786 	mp2ctl = copymsg(mpctl);
9787 
9788 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9789 	optp->level = MIB2_ICMP;
9790 	optp->name = 0;
9791 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9792 	    (int)sizeof (ipst->ips_icmp_mib))) {
9793 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9794 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9795 	}
9796 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9797 	ip3dbg(("ip_snmp_get_mib2_icmp: 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 /* Global IPv4 IGMP statistics */
9804 static mblk_t *
9805 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9806 {
9807 	struct opthdr		*optp;
9808 	mblk_t			*mp2ctl;
9809 
9810 	/*
9811 	 * make a copy of the original message
9812 	 */
9813 	mp2ctl = copymsg(mpctl);
9814 
9815 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9816 	optp->level = EXPER_IGMP;
9817 	optp->name = 0;
9818 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9819 	    (int)sizeof (ipst->ips_igmpstat))) {
9820 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9821 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9822 	}
9823 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9824 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9825 	    (int)optp->level, (int)optp->name, (int)optp->len));
9826 	qreply(q, mpctl);
9827 	return (mp2ctl);
9828 }
9829 
9830 /* Global IPv4 Multicast Routing statistics */
9831 static mblk_t *
9832 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9833 {
9834 	struct opthdr		*optp;
9835 	mblk_t			*mp2ctl;
9836 
9837 	/*
9838 	 * make a copy of the original message
9839 	 */
9840 	mp2ctl = copymsg(mpctl);
9841 
9842 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9843 	optp->level = EXPER_DVMRP;
9844 	optp->name = 0;
9845 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9846 		ip0dbg(("ip_mroute_stats: failed\n"));
9847 	}
9848 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9849 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9850 	    (int)optp->level, (int)optp->name, (int)optp->len));
9851 	qreply(q, mpctl);
9852 	return (mp2ctl);
9853 }
9854 
9855 /* IPv4 address information */
9856 static mblk_t *
9857 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9858 {
9859 	struct opthdr		*optp;
9860 	mblk_t			*mp2ctl;
9861 	mblk_t			*mp_tail = NULL;
9862 	ill_t			*ill;
9863 	ipif_t			*ipif;
9864 	uint_t			bitval;
9865 	mib2_ipAddrEntry_t	mae;
9866 	zoneid_t		zoneid;
9867 	ill_walk_context_t ctx;
9868 
9869 	/*
9870 	 * make a copy of the original message
9871 	 */
9872 	mp2ctl = copymsg(mpctl);
9873 
9874 	/* ipAddrEntryTable */
9875 
9876 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9877 	optp->level = MIB2_IP;
9878 	optp->name = MIB2_IP_ADDR;
9879 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9880 
9881 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9882 	ill = ILL_START_WALK_V4(&ctx, ipst);
9883 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9884 		for (ipif = ill->ill_ipif; ipif != NULL;
9885 		    ipif = ipif->ipif_next) {
9886 			if (ipif->ipif_zoneid != zoneid &&
9887 			    ipif->ipif_zoneid != ALL_ZONES)
9888 				continue;
9889 			/* Sum of count from dead IRE_LO* and our current */
9890 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9891 			if (ipif->ipif_ire_local != NULL) {
9892 				mae.ipAdEntInfo.ae_ibcnt +=
9893 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9894 			}
9895 			mae.ipAdEntInfo.ae_obcnt = 0;
9896 			mae.ipAdEntInfo.ae_focnt = 0;
9897 
9898 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
9899 			    OCTET_LENGTH);
9900 			mae.ipAdEntIfIndex.o_length =
9901 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
9902 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
9903 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
9904 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
9905 			mae.ipAdEntInfo.ae_subnet_len =
9906 			    ip_mask_to_plen(ipif->ipif_net_mask);
9907 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
9908 			for (bitval = 1;
9909 			    bitval &&
9910 			    !(bitval & ipif->ipif_brd_addr);
9911 			    bitval <<= 1)
9912 				noop;
9913 			mae.ipAdEntBcastAddr = bitval;
9914 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
9915 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
9916 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
9917 			mae.ipAdEntInfo.ae_broadcast_addr =
9918 			    ipif->ipif_brd_addr;
9919 			mae.ipAdEntInfo.ae_pp_dst_addr =
9920 			    ipif->ipif_pp_dst_addr;
9921 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
9922 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
9923 			mae.ipAdEntRetransmitTime =
9924 			    ill->ill_reachable_retrans_time;
9925 
9926 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9927 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
9928 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
9929 				    "allocate %u bytes\n",
9930 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
9931 			}
9932 		}
9933 	}
9934 	rw_exit(&ipst->ips_ill_g_lock);
9935 
9936 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9937 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
9938 	    (int)optp->level, (int)optp->name, (int)optp->len));
9939 	qreply(q, mpctl);
9940 	return (mp2ctl);
9941 }
9942 
9943 /* IPv6 address information */
9944 static mblk_t *
9945 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9946 {
9947 	struct opthdr		*optp;
9948 	mblk_t			*mp2ctl;
9949 	mblk_t			*mp_tail = NULL;
9950 	ill_t			*ill;
9951 	ipif_t			*ipif;
9952 	mib2_ipv6AddrEntry_t	mae6;
9953 	zoneid_t		zoneid;
9954 	ill_walk_context_t	ctx;
9955 
9956 	/*
9957 	 * make a copy of the original message
9958 	 */
9959 	mp2ctl = copymsg(mpctl);
9960 
9961 	/* ipv6AddrEntryTable */
9962 
9963 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9964 	optp->level = MIB2_IP6;
9965 	optp->name = MIB2_IP6_ADDR;
9966 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9967 
9968 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9969 	ill = ILL_START_WALK_V6(&ctx, ipst);
9970 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9971 		for (ipif = ill->ill_ipif; ipif != NULL;
9972 		    ipif = ipif->ipif_next) {
9973 			if (ipif->ipif_zoneid != zoneid &&
9974 			    ipif->ipif_zoneid != ALL_ZONES)
9975 				continue;
9976 			/* Sum of count from dead IRE_LO* and our current */
9977 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9978 			if (ipif->ipif_ire_local != NULL) {
9979 				mae6.ipv6AddrInfo.ae_ibcnt +=
9980 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9981 			}
9982 			mae6.ipv6AddrInfo.ae_obcnt = 0;
9983 			mae6.ipv6AddrInfo.ae_focnt = 0;
9984 
9985 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
9986 			    OCTET_LENGTH);
9987 			mae6.ipv6AddrIfIndex.o_length =
9988 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
9989 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
9990 			mae6.ipv6AddrPfxLength =
9991 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
9992 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
9993 			mae6.ipv6AddrInfo.ae_subnet_len =
9994 			    mae6.ipv6AddrPfxLength;
9995 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
9996 
9997 			/* Type: stateless(1), stateful(2), unknown(3) */
9998 			if (ipif->ipif_flags & IPIF_ADDRCONF)
9999 				mae6.ipv6AddrType = 1;
10000 			else
10001 				mae6.ipv6AddrType = 2;
10002 			/* Anycast: true(1), false(2) */
10003 			if (ipif->ipif_flags & IPIF_ANYCAST)
10004 				mae6.ipv6AddrAnycastFlag = 1;
10005 			else
10006 				mae6.ipv6AddrAnycastFlag = 2;
10007 
10008 			/*
10009 			 * Address status: preferred(1), deprecated(2),
10010 			 * invalid(3), inaccessible(4), unknown(5)
10011 			 */
10012 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10013 				mae6.ipv6AddrStatus = 3;
10014 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10015 				mae6.ipv6AddrStatus = 2;
10016 			else
10017 				mae6.ipv6AddrStatus = 1;
10018 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10019 			mae6.ipv6AddrInfo.ae_metric  =
10020 			    ipif->ipif_ill->ill_metric;
10021 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10022 			    ipif->ipif_v6pp_dst_addr;
10023 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10024 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10025 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10026 			mae6.ipv6AddrIdentifier = ill->ill_token;
10027 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10028 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10029 			mae6.ipv6AddrRetransmitTime =
10030 			    ill->ill_reachable_retrans_time;
10031 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10032 			    (char *)&mae6,
10033 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
10034 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10035 				    "allocate %u bytes\n",
10036 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
10037 			}
10038 		}
10039 	}
10040 	rw_exit(&ipst->ips_ill_g_lock);
10041 
10042 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10043 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10044 	    (int)optp->level, (int)optp->name, (int)optp->len));
10045 	qreply(q, mpctl);
10046 	return (mp2ctl);
10047 }
10048 
10049 /* IPv4 multicast group membership. */
10050 static mblk_t *
10051 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10052 {
10053 	struct opthdr		*optp;
10054 	mblk_t			*mp2ctl;
10055 	ill_t			*ill;
10056 	ipif_t			*ipif;
10057 	ilm_t			*ilm;
10058 	ip_member_t		ipm;
10059 	mblk_t			*mp_tail = NULL;
10060 	ill_walk_context_t	ctx;
10061 	zoneid_t		zoneid;
10062 
10063 	/*
10064 	 * make a copy of the original message
10065 	 */
10066 	mp2ctl = copymsg(mpctl);
10067 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10068 
10069 	/* ipGroupMember table */
10070 	optp = (struct opthdr *)&mpctl->b_rptr[
10071 	    sizeof (struct T_optmgmt_ack)];
10072 	optp->level = MIB2_IP;
10073 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10074 
10075 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10076 	ill = ILL_START_WALK_V4(&ctx, ipst);
10077 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10078 		/* Make sure the ill isn't going away. */
10079 		if (!ill_check_and_refhold(ill))
10080 			continue;
10081 		rw_exit(&ipst->ips_ill_g_lock);
10082 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10083 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10084 			if (ilm->ilm_zoneid != zoneid &&
10085 			    ilm->ilm_zoneid != ALL_ZONES)
10086 				continue;
10087 
10088 			/* Is there an ipif for ilm_ifaddr? */
10089 			for (ipif = ill->ill_ipif; ipif != NULL;
10090 			    ipif = ipif->ipif_next) {
10091 				if (!IPIF_IS_CONDEMNED(ipif) &&
10092 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10093 				    ilm->ilm_ifaddr != INADDR_ANY)
10094 					break;
10095 			}
10096 			if (ipif != NULL) {
10097 				ipif_get_name(ipif,
10098 				    ipm.ipGroupMemberIfIndex.o_bytes,
10099 				    OCTET_LENGTH);
10100 			} else {
10101 				ill_get_name(ill,
10102 				    ipm.ipGroupMemberIfIndex.o_bytes,
10103 				    OCTET_LENGTH);
10104 			}
10105 			ipm.ipGroupMemberIfIndex.o_length =
10106 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10107 
10108 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10109 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10110 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10111 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10112 			    (char *)&ipm, (int)sizeof (ipm))) {
10113 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10114 				    "failed to allocate %u bytes\n",
10115 				    (uint_t)sizeof (ipm)));
10116 			}
10117 		}
10118 		rw_exit(&ill->ill_mcast_lock);
10119 		ill_refrele(ill);
10120 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10121 	}
10122 	rw_exit(&ipst->ips_ill_g_lock);
10123 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10124 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10125 	    (int)optp->level, (int)optp->name, (int)optp->len));
10126 	qreply(q, mpctl);
10127 	return (mp2ctl);
10128 }
10129 
10130 /* IPv6 multicast group membership. */
10131 static mblk_t *
10132 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10133 {
10134 	struct opthdr		*optp;
10135 	mblk_t			*mp2ctl;
10136 	ill_t			*ill;
10137 	ilm_t			*ilm;
10138 	ipv6_member_t		ipm6;
10139 	mblk_t			*mp_tail = NULL;
10140 	ill_walk_context_t	ctx;
10141 	zoneid_t		zoneid;
10142 
10143 	/*
10144 	 * make a copy of the original message
10145 	 */
10146 	mp2ctl = copymsg(mpctl);
10147 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10148 
10149 	/* ip6GroupMember table */
10150 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10151 	optp->level = MIB2_IP6;
10152 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10153 
10154 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10155 	ill = ILL_START_WALK_V6(&ctx, ipst);
10156 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10157 		/* Make sure the ill isn't going away. */
10158 		if (!ill_check_and_refhold(ill))
10159 			continue;
10160 		rw_exit(&ipst->ips_ill_g_lock);
10161 		/*
10162 		 * Normally we don't have any members on under IPMP interfaces.
10163 		 * We report them as a debugging aid.
10164 		 */
10165 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10166 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10167 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10168 			if (ilm->ilm_zoneid != zoneid &&
10169 			    ilm->ilm_zoneid != ALL_ZONES)
10170 				continue;	/* not this zone */
10171 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10172 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10173 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10174 			if (!snmp_append_data2(mpctl->b_cont,
10175 			    &mp_tail,
10176 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10177 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10178 				    "failed to allocate %u bytes\n",
10179 				    (uint_t)sizeof (ipm6)));
10180 			}
10181 		}
10182 		rw_exit(&ill->ill_mcast_lock);
10183 		ill_refrele(ill);
10184 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10185 	}
10186 	rw_exit(&ipst->ips_ill_g_lock);
10187 
10188 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10189 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10190 	    (int)optp->level, (int)optp->name, (int)optp->len));
10191 	qreply(q, mpctl);
10192 	return (mp2ctl);
10193 }
10194 
10195 /* IP multicast filtered sources */
10196 static mblk_t *
10197 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10198 {
10199 	struct opthdr		*optp;
10200 	mblk_t			*mp2ctl;
10201 	ill_t			*ill;
10202 	ipif_t			*ipif;
10203 	ilm_t			*ilm;
10204 	ip_grpsrc_t		ips;
10205 	mblk_t			*mp_tail = NULL;
10206 	ill_walk_context_t	ctx;
10207 	zoneid_t		zoneid;
10208 	int			i;
10209 	slist_t			*sl;
10210 
10211 	/*
10212 	 * make a copy of the original message
10213 	 */
10214 	mp2ctl = copymsg(mpctl);
10215 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10216 
10217 	/* ipGroupSource table */
10218 	optp = (struct opthdr *)&mpctl->b_rptr[
10219 	    sizeof (struct T_optmgmt_ack)];
10220 	optp->level = MIB2_IP;
10221 	optp->name = EXPER_IP_GROUP_SOURCES;
10222 
10223 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10224 	ill = ILL_START_WALK_V4(&ctx, ipst);
10225 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10226 		/* Make sure the ill isn't going away. */
10227 		if (!ill_check_and_refhold(ill))
10228 			continue;
10229 		rw_exit(&ipst->ips_ill_g_lock);
10230 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10231 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10232 			sl = ilm->ilm_filter;
10233 			if (ilm->ilm_zoneid != zoneid &&
10234 			    ilm->ilm_zoneid != ALL_ZONES)
10235 				continue;
10236 			if (SLIST_IS_EMPTY(sl))
10237 				continue;
10238 
10239 			/* Is there an ipif for ilm_ifaddr? */
10240 			for (ipif = ill->ill_ipif; ipif != NULL;
10241 			    ipif = ipif->ipif_next) {
10242 				if (!IPIF_IS_CONDEMNED(ipif) &&
10243 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10244 				    ilm->ilm_ifaddr != INADDR_ANY)
10245 					break;
10246 			}
10247 			if (ipif != NULL) {
10248 				ipif_get_name(ipif,
10249 				    ips.ipGroupSourceIfIndex.o_bytes,
10250 				    OCTET_LENGTH);
10251 			} else {
10252 				ill_get_name(ill,
10253 				    ips.ipGroupSourceIfIndex.o_bytes,
10254 				    OCTET_LENGTH);
10255 			}
10256 			ips.ipGroupSourceIfIndex.o_length =
10257 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10258 
10259 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10260 			for (i = 0; i < sl->sl_numsrc; i++) {
10261 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10262 					continue;
10263 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10264 				    ips.ipGroupSourceAddress);
10265 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10266 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10267 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10268 					    " failed to allocate %u bytes\n",
10269 					    (uint_t)sizeof (ips)));
10270 				}
10271 			}
10272 		}
10273 		rw_exit(&ill->ill_mcast_lock);
10274 		ill_refrele(ill);
10275 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10276 	}
10277 	rw_exit(&ipst->ips_ill_g_lock);
10278 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10279 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10280 	    (int)optp->level, (int)optp->name, (int)optp->len));
10281 	qreply(q, mpctl);
10282 	return (mp2ctl);
10283 }
10284 
10285 /* IPv6 multicast filtered sources. */
10286 static mblk_t *
10287 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10288 {
10289 	struct opthdr		*optp;
10290 	mblk_t			*mp2ctl;
10291 	ill_t			*ill;
10292 	ilm_t			*ilm;
10293 	ipv6_grpsrc_t		ips6;
10294 	mblk_t			*mp_tail = NULL;
10295 	ill_walk_context_t	ctx;
10296 	zoneid_t		zoneid;
10297 	int			i;
10298 	slist_t			*sl;
10299 
10300 	/*
10301 	 * make a copy of the original message
10302 	 */
10303 	mp2ctl = copymsg(mpctl);
10304 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10305 
10306 	/* ip6GroupMember table */
10307 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10308 	optp->level = MIB2_IP6;
10309 	optp->name = EXPER_IP6_GROUP_SOURCES;
10310 
10311 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10312 	ill = ILL_START_WALK_V6(&ctx, ipst);
10313 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10314 		/* Make sure the ill isn't going away. */
10315 		if (!ill_check_and_refhold(ill))
10316 			continue;
10317 		rw_exit(&ipst->ips_ill_g_lock);
10318 		/*
10319 		 * Normally we don't have any members on under IPMP interfaces.
10320 		 * We report them as a debugging aid.
10321 		 */
10322 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10323 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10324 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10325 			sl = ilm->ilm_filter;
10326 			if (ilm->ilm_zoneid != zoneid &&
10327 			    ilm->ilm_zoneid != ALL_ZONES)
10328 				continue;
10329 			if (SLIST_IS_EMPTY(sl))
10330 				continue;
10331 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10332 			for (i = 0; i < sl->sl_numsrc; i++) {
10333 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10334 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10335 				    (char *)&ips6, (int)sizeof (ips6))) {
10336 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10337 					    "group_src: failed to allocate "
10338 					    "%u bytes\n",
10339 					    (uint_t)sizeof (ips6)));
10340 				}
10341 			}
10342 		}
10343 		rw_exit(&ill->ill_mcast_lock);
10344 		ill_refrele(ill);
10345 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10346 	}
10347 	rw_exit(&ipst->ips_ill_g_lock);
10348 
10349 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10350 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10351 	    (int)optp->level, (int)optp->name, (int)optp->len));
10352 	qreply(q, mpctl);
10353 	return (mp2ctl);
10354 }
10355 
10356 /* Multicast routing virtual interface table. */
10357 static mblk_t *
10358 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10359 {
10360 	struct opthdr		*optp;
10361 	mblk_t			*mp2ctl;
10362 
10363 	/*
10364 	 * make a copy of the original message
10365 	 */
10366 	mp2ctl = copymsg(mpctl);
10367 
10368 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10369 	optp->level = EXPER_DVMRP;
10370 	optp->name = EXPER_DVMRP_VIF;
10371 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10372 		ip0dbg(("ip_mroute_vif: failed\n"));
10373 	}
10374 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10375 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10376 	    (int)optp->level, (int)optp->name, (int)optp->len));
10377 	qreply(q, mpctl);
10378 	return (mp2ctl);
10379 }
10380 
10381 /* Multicast routing table. */
10382 static mblk_t *
10383 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10384 {
10385 	struct opthdr		*optp;
10386 	mblk_t			*mp2ctl;
10387 
10388 	/*
10389 	 * make a copy of the original message
10390 	 */
10391 	mp2ctl = copymsg(mpctl);
10392 
10393 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10394 	optp->level = EXPER_DVMRP;
10395 	optp->name = EXPER_DVMRP_MRT;
10396 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10397 		ip0dbg(("ip_mroute_mrt: failed\n"));
10398 	}
10399 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10400 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10401 	    (int)optp->level, (int)optp->name, (int)optp->len));
10402 	qreply(q, mpctl);
10403 	return (mp2ctl);
10404 }
10405 
10406 /*
10407  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10408  * in one IRE walk.
10409  */
10410 static mblk_t *
10411 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10412     ip_stack_t *ipst)
10413 {
10414 	struct opthdr	*optp;
10415 	mblk_t		*mp2ctl;	/* Returned */
10416 	mblk_t		*mp3ctl;	/* nettomedia */
10417 	mblk_t		*mp4ctl;	/* routeattrs */
10418 	iproutedata_t	ird;
10419 	zoneid_t	zoneid;
10420 
10421 	/*
10422 	 * make copies of the original message
10423 	 *	- mp2ctl is returned unchanged to the caller for his use
10424 	 *	- mpctl is sent upstream as ipRouteEntryTable
10425 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10426 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10427 	 */
10428 	mp2ctl = copymsg(mpctl);
10429 	mp3ctl = copymsg(mpctl);
10430 	mp4ctl = copymsg(mpctl);
10431 	if (mp3ctl == NULL || mp4ctl == NULL) {
10432 		freemsg(mp4ctl);
10433 		freemsg(mp3ctl);
10434 		freemsg(mp2ctl);
10435 		freemsg(mpctl);
10436 		return (NULL);
10437 	}
10438 
10439 	bzero(&ird, sizeof (ird));
10440 
10441 	ird.ird_route.lp_head = mpctl->b_cont;
10442 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10443 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10444 	/*
10445 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10446 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10447 	 * intended a temporary solution until a proper MIB API is provided
10448 	 * that provides complete filtering/caller-opt-in.
10449 	 */
10450 	if (level == EXPER_IP_AND_ALL_IRES)
10451 		ird.ird_flags |= IRD_REPORT_ALL;
10452 
10453 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10454 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10455 
10456 	/* ipRouteEntryTable in mpctl */
10457 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10458 	optp->level = MIB2_IP;
10459 	optp->name = MIB2_IP_ROUTE;
10460 	optp->len = msgdsize(ird.ird_route.lp_head);
10461 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10462 	    (int)optp->level, (int)optp->name, (int)optp->len));
10463 	qreply(q, mpctl);
10464 
10465 	/* ipNetToMediaEntryTable in mp3ctl */
10466 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10467 
10468 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10469 	optp->level = MIB2_IP;
10470 	optp->name = MIB2_IP_MEDIA;
10471 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10472 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10473 	    (int)optp->level, (int)optp->name, (int)optp->len));
10474 	qreply(q, mp3ctl);
10475 
10476 	/* ipRouteAttributeTable in mp4ctl */
10477 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10478 	optp->level = MIB2_IP;
10479 	optp->name = EXPER_IP_RTATTR;
10480 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10481 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10482 	    (int)optp->level, (int)optp->name, (int)optp->len));
10483 	if (optp->len == 0)
10484 		freemsg(mp4ctl);
10485 	else
10486 		qreply(q, mp4ctl);
10487 
10488 	return (mp2ctl);
10489 }
10490 
10491 /*
10492  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10493  * ipv6NetToMediaEntryTable in an NDP walk.
10494  */
10495 static mblk_t *
10496 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10497     ip_stack_t *ipst)
10498 {
10499 	struct opthdr	*optp;
10500 	mblk_t		*mp2ctl;	/* Returned */
10501 	mblk_t		*mp3ctl;	/* nettomedia */
10502 	mblk_t		*mp4ctl;	/* routeattrs */
10503 	iproutedata_t	ird;
10504 	zoneid_t	zoneid;
10505 
10506 	/*
10507 	 * make copies of the original message
10508 	 *	- mp2ctl is returned unchanged to the caller for his use
10509 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10510 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10511 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10512 	 */
10513 	mp2ctl = copymsg(mpctl);
10514 	mp3ctl = copymsg(mpctl);
10515 	mp4ctl = copymsg(mpctl);
10516 	if (mp3ctl == NULL || mp4ctl == NULL) {
10517 		freemsg(mp4ctl);
10518 		freemsg(mp3ctl);
10519 		freemsg(mp2ctl);
10520 		freemsg(mpctl);
10521 		return (NULL);
10522 	}
10523 
10524 	bzero(&ird, sizeof (ird));
10525 
10526 	ird.ird_route.lp_head = mpctl->b_cont;
10527 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10528 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10529 	/*
10530 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10531 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10532 	 * intended a temporary solution until a proper MIB API is provided
10533 	 * that provides complete filtering/caller-opt-in.
10534 	 */
10535 	if (level == EXPER_IP_AND_ALL_IRES)
10536 		ird.ird_flags |= IRD_REPORT_ALL;
10537 
10538 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10539 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10540 
10541 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10542 	optp->level = MIB2_IP6;
10543 	optp->name = MIB2_IP6_ROUTE;
10544 	optp->len = msgdsize(ird.ird_route.lp_head);
10545 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10546 	    (int)optp->level, (int)optp->name, (int)optp->len));
10547 	qreply(q, mpctl);
10548 
10549 	/* ipv6NetToMediaEntryTable in mp3ctl */
10550 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10551 
10552 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10553 	optp->level = MIB2_IP6;
10554 	optp->name = MIB2_IP6_MEDIA;
10555 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10556 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10557 	    (int)optp->level, (int)optp->name, (int)optp->len));
10558 	qreply(q, mp3ctl);
10559 
10560 	/* ipv6RouteAttributeTable in mp4ctl */
10561 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10562 	optp->level = MIB2_IP6;
10563 	optp->name = EXPER_IP_RTATTR;
10564 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10565 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10566 	    (int)optp->level, (int)optp->name, (int)optp->len));
10567 	if (optp->len == 0)
10568 		freemsg(mp4ctl);
10569 	else
10570 		qreply(q, mp4ctl);
10571 
10572 	return (mp2ctl);
10573 }
10574 
10575 /*
10576  * IPv6 mib: One per ill
10577  */
10578 static mblk_t *
10579 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10580 {
10581 	struct opthdr		*optp;
10582 	mblk_t			*mp2ctl;
10583 	ill_t			*ill;
10584 	ill_walk_context_t	ctx;
10585 	mblk_t			*mp_tail = NULL;
10586 
10587 	/*
10588 	 * Make a copy of the original message
10589 	 */
10590 	mp2ctl = copymsg(mpctl);
10591 
10592 	/* fixed length IPv6 structure ... */
10593 
10594 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10595 	optp->level = MIB2_IP6;
10596 	optp->name = 0;
10597 	/* Include "unknown interface" ip6_mib */
10598 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10599 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10600 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10601 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10602 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10603 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10604 	    ipst->ips_ipv6_def_hops);
10605 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10606 	    sizeof (mib2_ipIfStatsEntry_t));
10607 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10608 	    sizeof (mib2_ipv6AddrEntry_t));
10609 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10610 	    sizeof (mib2_ipv6RouteEntry_t));
10611 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10612 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10613 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10614 	    sizeof (ipv6_member_t));
10615 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10616 	    sizeof (ipv6_grpsrc_t));
10617 
10618 	/*
10619 	 * Synchronize 64- and 32-bit counters
10620 	 */
10621 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10622 	    ipIfStatsHCInReceives);
10623 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10624 	    ipIfStatsHCInDelivers);
10625 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10626 	    ipIfStatsHCOutRequests);
10627 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10628 	    ipIfStatsHCOutForwDatagrams);
10629 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10630 	    ipIfStatsHCOutMcastPkts);
10631 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10632 	    ipIfStatsHCInMcastPkts);
10633 
10634 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10635 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
10636 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10637 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
10638 	}
10639 
10640 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10641 	ill = ILL_START_WALK_V6(&ctx, ipst);
10642 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10643 		ill->ill_ip_mib->ipIfStatsIfIndex =
10644 		    ill->ill_phyint->phyint_ifindex;
10645 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10646 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10647 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10648 		    ill->ill_max_hops);
10649 
10650 		/*
10651 		 * Synchronize 64- and 32-bit counters
10652 		 */
10653 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10654 		    ipIfStatsHCInReceives);
10655 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10656 		    ipIfStatsHCInDelivers);
10657 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10658 		    ipIfStatsHCOutRequests);
10659 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10660 		    ipIfStatsHCOutForwDatagrams);
10661 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10662 		    ipIfStatsHCOutMcastPkts);
10663 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10664 		    ipIfStatsHCInMcastPkts);
10665 
10666 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10667 		    (char *)ill->ill_ip_mib,
10668 		    (int)sizeof (*ill->ill_ip_mib))) {
10669 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10670 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
10671 		}
10672 	}
10673 	rw_exit(&ipst->ips_ill_g_lock);
10674 
10675 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10676 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10677 	    (int)optp->level, (int)optp->name, (int)optp->len));
10678 	qreply(q, mpctl);
10679 	return (mp2ctl);
10680 }
10681 
10682 /*
10683  * ICMPv6 mib: One per ill
10684  */
10685 static mblk_t *
10686 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10687 {
10688 	struct opthdr		*optp;
10689 	mblk_t			*mp2ctl;
10690 	ill_t			*ill;
10691 	ill_walk_context_t	ctx;
10692 	mblk_t			*mp_tail = NULL;
10693 	/*
10694 	 * Make a copy of the original message
10695 	 */
10696 	mp2ctl = copymsg(mpctl);
10697 
10698 	/* fixed length ICMPv6 structure ... */
10699 
10700 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10701 	optp->level = MIB2_ICMP6;
10702 	optp->name = 0;
10703 	/* Include "unknown interface" icmp6_mib */
10704 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10705 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10706 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10707 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10708 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10709 	    (char *)&ipst->ips_icmp6_mib,
10710 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10711 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10712 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10713 	}
10714 
10715 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10716 	ill = ILL_START_WALK_V6(&ctx, ipst);
10717 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10718 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10719 		    ill->ill_phyint->phyint_ifindex;
10720 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10721 		    (char *)ill->ill_icmp6_mib,
10722 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10723 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10724 			    "%u bytes\n",
10725 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10726 		}
10727 	}
10728 	rw_exit(&ipst->ips_ill_g_lock);
10729 
10730 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10731 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10732 	    (int)optp->level, (int)optp->name, (int)optp->len));
10733 	qreply(q, mpctl);
10734 	return (mp2ctl);
10735 }
10736 
10737 /*
10738  * ire_walk routine to create both ipRouteEntryTable and
10739  * ipRouteAttributeTable in one IRE walk
10740  */
10741 static void
10742 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10743 {
10744 	ill_t				*ill;
10745 	mib2_ipRouteEntry_t		*re;
10746 	mib2_ipAttributeEntry_t		iaes;
10747 	tsol_ire_gw_secattr_t		*attrp;
10748 	tsol_gc_t			*gc = NULL;
10749 	tsol_gcgrp_t			*gcgrp = NULL;
10750 	ip_stack_t			*ipst = ire->ire_ipst;
10751 
10752 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10753 
10754 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10755 		if (ire->ire_testhidden)
10756 			return;
10757 		if (ire->ire_type & IRE_IF_CLONE)
10758 			return;
10759 	}
10760 
10761 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10762 		return;
10763 
10764 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10765 		mutex_enter(&attrp->igsa_lock);
10766 		if ((gc = attrp->igsa_gc) != NULL) {
10767 			gcgrp = gc->gc_grp;
10768 			ASSERT(gcgrp != NULL);
10769 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10770 		}
10771 		mutex_exit(&attrp->igsa_lock);
10772 	}
10773 	/*
10774 	 * Return all IRE types for route table... let caller pick and choose
10775 	 */
10776 	re->ipRouteDest = ire->ire_addr;
10777 	ill = ire->ire_ill;
10778 	re->ipRouteIfIndex.o_length = 0;
10779 	if (ill != NULL) {
10780 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10781 		re->ipRouteIfIndex.o_length =
10782 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10783 	}
10784 	re->ipRouteMetric1 = -1;
10785 	re->ipRouteMetric2 = -1;
10786 	re->ipRouteMetric3 = -1;
10787 	re->ipRouteMetric4 = -1;
10788 
10789 	re->ipRouteNextHop = ire->ire_gateway_addr;
10790 	/* indirect(4), direct(3), or invalid(2) */
10791 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10792 		re->ipRouteType = 2;
10793 	else if (ire->ire_type & IRE_ONLINK)
10794 		re->ipRouteType = 3;
10795 	else
10796 		re->ipRouteType = 4;
10797 
10798 	re->ipRouteProto = -1;
10799 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10800 	re->ipRouteMask = ire->ire_mask;
10801 	re->ipRouteMetric5 = -1;
10802 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10803 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10804 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10805 
10806 	re->ipRouteInfo.re_frag_flag	= 0;
10807 	re->ipRouteInfo.re_rtt		= 0;
10808 	re->ipRouteInfo.re_src_addr	= 0;
10809 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
10810 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10811 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10812 	re->ipRouteInfo.re_flags	= ire->ire_flags;
10813 
10814 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10815 	if (ire->ire_type & IRE_INTERFACE) {
10816 		ire_t *child;
10817 
10818 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10819 		child = ire->ire_dep_children;
10820 		while (child != NULL) {
10821 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10822 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10823 			child = child->ire_dep_sib_next;
10824 		}
10825 		rw_exit(&ipst->ips_ire_dep_lock);
10826 	}
10827 
10828 	if (ire->ire_flags & RTF_DYNAMIC) {
10829 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10830 	} else {
10831 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
10832 	}
10833 
10834 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10835 	    (char *)re, (int)sizeof (*re))) {
10836 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
10837 		    (uint_t)sizeof (*re)));
10838 	}
10839 
10840 	if (gc != NULL) {
10841 		iaes.iae_routeidx = ird->ird_idx;
10842 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10843 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10844 
10845 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10846 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10847 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
10848 			    "bytes\n", (uint_t)sizeof (iaes)));
10849 		}
10850 	}
10851 
10852 	/* bump route index for next pass */
10853 	ird->ird_idx++;
10854 
10855 	kmem_free(re, sizeof (*re));
10856 	if (gcgrp != NULL)
10857 		rw_exit(&gcgrp->gcgrp_rwlock);
10858 }
10859 
10860 /*
10861  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
10862  */
10863 static void
10864 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
10865 {
10866 	ill_t				*ill;
10867 	mib2_ipv6RouteEntry_t		*re;
10868 	mib2_ipAttributeEntry_t		iaes;
10869 	tsol_ire_gw_secattr_t		*attrp;
10870 	tsol_gc_t			*gc = NULL;
10871 	tsol_gcgrp_t			*gcgrp = NULL;
10872 	ip_stack_t			*ipst = ire->ire_ipst;
10873 
10874 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
10875 
10876 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10877 		if (ire->ire_testhidden)
10878 			return;
10879 		if (ire->ire_type & IRE_IF_CLONE)
10880 			return;
10881 	}
10882 
10883 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10884 		return;
10885 
10886 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10887 		mutex_enter(&attrp->igsa_lock);
10888 		if ((gc = attrp->igsa_gc) != NULL) {
10889 			gcgrp = gc->gc_grp;
10890 			ASSERT(gcgrp != NULL);
10891 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10892 		}
10893 		mutex_exit(&attrp->igsa_lock);
10894 	}
10895 	/*
10896 	 * Return all IRE types for route table... let caller pick and choose
10897 	 */
10898 	re->ipv6RouteDest = ire->ire_addr_v6;
10899 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
10900 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
10901 	re->ipv6RouteIfIndex.o_length = 0;
10902 	ill = ire->ire_ill;
10903 	if (ill != NULL) {
10904 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
10905 		re->ipv6RouteIfIndex.o_length =
10906 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
10907 	}
10908 
10909 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
10910 
10911 	mutex_enter(&ire->ire_lock);
10912 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
10913 	mutex_exit(&ire->ire_lock);
10914 
10915 	/* remote(4), local(3), or discard(2) */
10916 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10917 		re->ipv6RouteType = 2;
10918 	else if (ire->ire_type & IRE_ONLINK)
10919 		re->ipv6RouteType = 3;
10920 	else
10921 		re->ipv6RouteType = 4;
10922 
10923 	re->ipv6RouteProtocol	= -1;
10924 	re->ipv6RoutePolicy	= 0;
10925 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
10926 	re->ipv6RouteNextHopRDI	= 0;
10927 	re->ipv6RouteWeight	= 0;
10928 	re->ipv6RouteMetric	= 0;
10929 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10930 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
10931 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10932 
10933 	re->ipv6RouteInfo.re_frag_flag	= 0;
10934 	re->ipv6RouteInfo.re_rtt	= 0;
10935 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
10936 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10937 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10938 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
10939 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
10940 
10941 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10942 	if (ire->ire_type & IRE_INTERFACE) {
10943 		ire_t *child;
10944 
10945 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10946 		child = ire->ire_dep_children;
10947 		while (child != NULL) {
10948 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
10949 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10950 			child = child->ire_dep_sib_next;
10951 		}
10952 		rw_exit(&ipst->ips_ire_dep_lock);
10953 	}
10954 	if (ire->ire_flags & RTF_DYNAMIC) {
10955 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10956 	} else {
10957 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
10958 	}
10959 
10960 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10961 	    (char *)re, (int)sizeof (*re))) {
10962 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
10963 		    (uint_t)sizeof (*re)));
10964 	}
10965 
10966 	if (gc != NULL) {
10967 		iaes.iae_routeidx = ird->ird_idx;
10968 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10969 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10970 
10971 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10972 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10973 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
10974 			    "bytes\n", (uint_t)sizeof (iaes)));
10975 		}
10976 	}
10977 
10978 	/* bump route index for next pass */
10979 	ird->ird_idx++;
10980 
10981 	kmem_free(re, sizeof (*re));
10982 	if (gcgrp != NULL)
10983 		rw_exit(&gcgrp->gcgrp_rwlock);
10984 }
10985 
10986 /*
10987  * ncec_walk routine to create ipv6NetToMediaEntryTable
10988  */
10989 static int
10990 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
10991 {
10992 	ill_t				*ill;
10993 	mib2_ipv6NetToMediaEntry_t	ntme;
10994 
10995 	ill = ncec->ncec_ill;
10996 	/* skip arpce entries, and loopback ncec entries */
10997 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
10998 		return (0);
10999 	/*
11000 	 * Neighbor cache entry attached to IRE with on-link
11001 	 * destination.
11002 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11003 	 */
11004 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11005 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11006 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11007 	if (ncec->ncec_lladdr != NULL) {
11008 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11009 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11010 	}
11011 	/*
11012 	 * Note: Returns ND_* states. Should be:
11013 	 * reachable(1), stale(2), delay(3), probe(4),
11014 	 * invalid(5), unknown(6)
11015 	 */
11016 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11017 	ntme.ipv6NetToMediaLastUpdated = 0;
11018 
11019 	/* other(1), dynamic(2), static(3), local(4) */
11020 	if (NCE_MYADDR(ncec)) {
11021 		ntme.ipv6NetToMediaType = 4;
11022 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11023 		ntme.ipv6NetToMediaType = 1; /* proxy */
11024 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11025 		ntme.ipv6NetToMediaType = 3;
11026 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11027 		ntme.ipv6NetToMediaType = 1;
11028 	} else {
11029 		ntme.ipv6NetToMediaType = 2;
11030 	}
11031 
11032 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11033 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11034 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11035 		    (uint_t)sizeof (ntme)));
11036 	}
11037 	return (0);
11038 }
11039 
11040 int
11041 nce2ace(ncec_t *ncec)
11042 {
11043 	int flags = 0;
11044 
11045 	if (NCE_ISREACHABLE(ncec))
11046 		flags |= ACE_F_RESOLVED;
11047 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11048 		flags |= ACE_F_AUTHORITY;
11049 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11050 		flags |= ACE_F_PUBLISH;
11051 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11052 		flags |= ACE_F_PERMANENT;
11053 	if (NCE_MYADDR(ncec))
11054 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11055 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11056 		flags |= ACE_F_UNVERIFIED;
11057 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11058 		flags |= ACE_F_AUTHORITY;
11059 	if (ncec->ncec_flags & NCE_F_DELAYED)
11060 		flags |= ACE_F_DELAYED;
11061 	return (flags);
11062 }
11063 
11064 /*
11065  * ncec_walk routine to create ipNetToMediaEntryTable
11066  */
11067 static int
11068 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11069 {
11070 	ill_t				*ill;
11071 	mib2_ipNetToMediaEntry_t	ntme;
11072 	const char			*name = "unknown";
11073 	ipaddr_t			ncec_addr;
11074 
11075 	ill = ncec->ncec_ill;
11076 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11077 	    ill->ill_net_type == IRE_LOOPBACK)
11078 		return (0);
11079 
11080 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11081 	name = ill->ill_name;
11082 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11083 	if (NCE_MYADDR(ncec)) {
11084 		ntme.ipNetToMediaType = 4;
11085 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11086 		ntme.ipNetToMediaType = 1;
11087 	} else {
11088 		ntme.ipNetToMediaType = 3;
11089 	}
11090 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11091 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11092 	    ntme.ipNetToMediaIfIndex.o_length);
11093 
11094 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11095 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11096 
11097 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11098 	ncec_addr = INADDR_BROADCAST;
11099 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11100 	    sizeof (ncec_addr));
11101 	/*
11102 	 * map all the flags to the ACE counterpart.
11103 	 */
11104 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11105 
11106 	ntme.ipNetToMediaPhysAddress.o_length =
11107 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11108 
11109 	if (!NCE_ISREACHABLE(ncec))
11110 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11111 	else {
11112 		if (ncec->ncec_lladdr != NULL) {
11113 			bcopy(ncec->ncec_lladdr,
11114 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11115 			    ntme.ipNetToMediaPhysAddress.o_length);
11116 		}
11117 	}
11118 
11119 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11120 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11121 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11122 		    (uint_t)sizeof (ntme)));
11123 	}
11124 	return (0);
11125 }
11126 
11127 /*
11128  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11129  */
11130 /* ARGSUSED */
11131 int
11132 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11133 {
11134 	switch (level) {
11135 	case MIB2_IP:
11136 	case MIB2_ICMP:
11137 		switch (name) {
11138 		default:
11139 			break;
11140 		}
11141 		return (1);
11142 	default:
11143 		return (1);
11144 	}
11145 }
11146 
11147 /*
11148  * When there exists both a 64- and 32-bit counter of a particular type
11149  * (i.e., InReceives), only the 64-bit counters are added.
11150  */
11151 void
11152 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11153 {
11154 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11155 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11156 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11157 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11158 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11159 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11160 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11161 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11162 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11163 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11164 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11165 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11166 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11167 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11168 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11169 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11170 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11171 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11172 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11173 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11174 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11175 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11176 	    o2->ipIfStatsInWrongIPVersion);
11177 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11178 	    o2->ipIfStatsInWrongIPVersion);
11179 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11180 	    o2->ipIfStatsOutSwitchIPVersion);
11181 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11182 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11183 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11184 	    o2->ipIfStatsHCInForwDatagrams);
11185 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11186 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11187 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11188 	    o2->ipIfStatsHCOutForwDatagrams);
11189 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11190 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11191 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11192 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11193 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11194 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11195 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11196 	    o2->ipIfStatsHCOutMcastOctets);
11197 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11198 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11199 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11200 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11201 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11202 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11203 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11204 }
11205 
11206 void
11207 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11208 {
11209 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11210 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11211 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11212 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11213 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11214 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11215 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11216 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11217 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11218 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11219 	    o2->ipv6IfIcmpInRouterSolicits);
11220 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11221 	    o2->ipv6IfIcmpInRouterAdvertisements);
11222 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11223 	    o2->ipv6IfIcmpInNeighborSolicits);
11224 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11225 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11226 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11227 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11228 	    o2->ipv6IfIcmpInGroupMembQueries);
11229 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11230 	    o2->ipv6IfIcmpInGroupMembResponses);
11231 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11232 	    o2->ipv6IfIcmpInGroupMembReductions);
11233 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11234 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11235 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11236 	    o2->ipv6IfIcmpOutDestUnreachs);
11237 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11238 	    o2->ipv6IfIcmpOutAdminProhibs);
11239 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11240 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11241 	    o2->ipv6IfIcmpOutParmProblems);
11242 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11243 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11244 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11245 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11246 	    o2->ipv6IfIcmpOutRouterSolicits);
11247 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11248 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11249 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11250 	    o2->ipv6IfIcmpOutNeighborSolicits);
11251 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11252 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11253 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11254 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11255 	    o2->ipv6IfIcmpOutGroupMembQueries);
11256 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11257 	    o2->ipv6IfIcmpOutGroupMembResponses);
11258 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11259 	    o2->ipv6IfIcmpOutGroupMembReductions);
11260 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11261 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11262 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11263 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11264 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11265 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11266 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11267 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11268 	    o2->ipv6IfIcmpInGroupMembTotal);
11269 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11270 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11271 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11272 	    o2->ipv6IfIcmpInGroupMembBadReports);
11273 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11274 	    o2->ipv6IfIcmpInGroupMembOurReports);
11275 }
11276 
11277 /*
11278  * Called before the options are updated to check if this packet will
11279  * be source routed from here.
11280  * This routine assumes that the options are well formed i.e. that they
11281  * have already been checked.
11282  */
11283 boolean_t
11284 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11285 {
11286 	ipoptp_t	opts;
11287 	uchar_t		*opt;
11288 	uint8_t		optval;
11289 	uint8_t		optlen;
11290 	ipaddr_t	dst;
11291 
11292 	if (IS_SIMPLE_IPH(ipha)) {
11293 		ip2dbg(("not source routed\n"));
11294 		return (B_FALSE);
11295 	}
11296 	dst = ipha->ipha_dst;
11297 	for (optval = ipoptp_first(&opts, ipha);
11298 	    optval != IPOPT_EOL;
11299 	    optval = ipoptp_next(&opts)) {
11300 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11301 		opt = opts.ipoptp_cur;
11302 		optlen = opts.ipoptp_len;
11303 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11304 		    optval, optlen));
11305 		switch (optval) {
11306 			uint32_t off;
11307 		case IPOPT_SSRR:
11308 		case IPOPT_LSRR:
11309 			/*
11310 			 * If dst is one of our addresses and there are some
11311 			 * entries left in the source route return (true).
11312 			 */
11313 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11314 				ip2dbg(("ip_source_routed: not next"
11315 				    " source route 0x%x\n",
11316 				    ntohl(dst)));
11317 				return (B_FALSE);
11318 			}
11319 			off = opt[IPOPT_OFFSET];
11320 			off--;
11321 			if (optlen < IP_ADDR_LEN ||
11322 			    off > optlen - IP_ADDR_LEN) {
11323 				/* End of source route */
11324 				ip1dbg(("ip_source_routed: end of SR\n"));
11325 				return (B_FALSE);
11326 			}
11327 			return (B_TRUE);
11328 		}
11329 	}
11330 	ip2dbg(("not source routed\n"));
11331 	return (B_FALSE);
11332 }
11333 
11334 /*
11335  * ip_unbind is called by the transports to remove a conn from
11336  * the fanout table.
11337  */
11338 void
11339 ip_unbind(conn_t *connp)
11340 {
11341 
11342 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11343 
11344 	if (is_system_labeled() && connp->conn_anon_port) {
11345 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11346 		    connp->conn_mlp_type, connp->conn_proto,
11347 		    ntohs(connp->conn_lport), B_FALSE);
11348 		connp->conn_anon_port = 0;
11349 	}
11350 	connp->conn_mlp_type = mlptSingle;
11351 
11352 	ipcl_hash_remove(connp);
11353 }
11354 
11355 /*
11356  * Used for deciding the MSS size for the upper layer. Thus
11357  * we need to check the outbound policy values in the conn.
11358  */
11359 int
11360 conn_ipsec_length(conn_t *connp)
11361 {
11362 	ipsec_latch_t *ipl;
11363 
11364 	ipl = connp->conn_latch;
11365 	if (ipl == NULL)
11366 		return (0);
11367 
11368 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11369 		return (0);
11370 
11371 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11372 }
11373 
11374 /*
11375  * Returns an estimate of the IPsec headers size. This is used if
11376  * we don't want to call into IPsec to get the exact size.
11377  */
11378 int
11379 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11380 {
11381 	ipsec_action_t *a;
11382 
11383 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11384 		return (0);
11385 
11386 	a = ixa->ixa_ipsec_action;
11387 	if (a == NULL) {
11388 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11389 		a = ixa->ixa_ipsec_policy->ipsp_act;
11390 	}
11391 	ASSERT(a != NULL);
11392 
11393 	return (a->ipa_ovhd);
11394 }
11395 
11396 /*
11397  * If there are any source route options, return the true final
11398  * destination. Otherwise, return the destination.
11399  */
11400 ipaddr_t
11401 ip_get_dst(ipha_t *ipha)
11402 {
11403 	ipoptp_t	opts;
11404 	uchar_t		*opt;
11405 	uint8_t		optval;
11406 	uint8_t		optlen;
11407 	ipaddr_t	dst;
11408 	uint32_t off;
11409 
11410 	dst = ipha->ipha_dst;
11411 
11412 	if (IS_SIMPLE_IPH(ipha))
11413 		return (dst);
11414 
11415 	for (optval = ipoptp_first(&opts, ipha);
11416 	    optval != IPOPT_EOL;
11417 	    optval = ipoptp_next(&opts)) {
11418 		opt = opts.ipoptp_cur;
11419 		optlen = opts.ipoptp_len;
11420 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11421 		switch (optval) {
11422 		case IPOPT_SSRR:
11423 		case IPOPT_LSRR:
11424 			off = opt[IPOPT_OFFSET];
11425 			/*
11426 			 * If one of the conditions is true, it means
11427 			 * end of options and dst already has the right
11428 			 * value.
11429 			 */
11430 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11431 				off = optlen - IP_ADDR_LEN;
11432 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11433 			}
11434 			return (dst);
11435 		default:
11436 			break;
11437 		}
11438 	}
11439 
11440 	return (dst);
11441 }
11442 
11443 /*
11444  * Outbound IP fragmentation routine.
11445  * Assumes the caller has checked whether or not fragmentation should
11446  * be allowed. Here we copy the DF bit from the header to all the generated
11447  * fragments.
11448  */
11449 int
11450 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11451     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11452     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11453 {
11454 	int		i1;
11455 	int		hdr_len;
11456 	mblk_t		*hdr_mp;
11457 	ipha_t		*ipha;
11458 	int		ip_data_end;
11459 	int		len;
11460 	mblk_t		*mp = mp_orig;
11461 	int		offset;
11462 	ill_t		*ill = nce->nce_ill;
11463 	ip_stack_t	*ipst = ill->ill_ipst;
11464 	mblk_t		*carve_mp;
11465 	uint32_t	frag_flag;
11466 	uint_t		priority = mp->b_band;
11467 	int		error = 0;
11468 
11469 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11470 
11471 	if (pkt_len != msgdsize(mp)) {
11472 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11473 		    pkt_len, msgdsize(mp)));
11474 		freemsg(mp);
11475 		return (EINVAL);
11476 	}
11477 
11478 	if (max_frag == 0) {
11479 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11480 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11481 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11482 		freemsg(mp);
11483 		return (EINVAL);
11484 	}
11485 
11486 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11487 	ipha = (ipha_t *)mp->b_rptr;
11488 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11489 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11490 
11491 	/*
11492 	 * Establish the starting offset.  May not be zero if we are fragging
11493 	 * a fragment that is being forwarded.
11494 	 */
11495 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11496 
11497 	/* TODO why is this test needed? */
11498 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11499 		/* TODO: notify ulp somehow */
11500 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11501 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11502 		freemsg(mp);
11503 		return (EINVAL);
11504 	}
11505 
11506 	hdr_len = IPH_HDR_LENGTH(ipha);
11507 	ipha->ipha_hdr_checksum = 0;
11508 
11509 	/*
11510 	 * Establish the number of bytes maximum per frag, after putting
11511 	 * in the header.
11512 	 */
11513 	len = (max_frag - hdr_len) & ~7;
11514 
11515 	/* Get a copy of the header for the trailing frags */
11516 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11517 	    mp);
11518 	if (hdr_mp == NULL) {
11519 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11520 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11521 		freemsg(mp);
11522 		return (ENOBUFS);
11523 	}
11524 
11525 	/* Store the starting offset, with the MoreFrags flag. */
11526 	i1 = offset | IPH_MF | frag_flag;
11527 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11528 
11529 	/* Establish the ending byte offset, based on the starting offset. */
11530 	offset <<= 3;
11531 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11532 
11533 	/* Store the length of the first fragment in the IP header. */
11534 	i1 = len + hdr_len;
11535 	ASSERT(i1 <= IP_MAXPACKET);
11536 	ipha->ipha_length = htons((uint16_t)i1);
11537 
11538 	/*
11539 	 * Compute the IP header checksum for the first frag.  We have to
11540 	 * watch out that we stop at the end of the header.
11541 	 */
11542 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11543 
11544 	/*
11545 	 * Now carve off the first frag.  Note that this will include the
11546 	 * original IP header.
11547 	 */
11548 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11549 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11550 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11551 		freeb(hdr_mp);
11552 		freemsg(mp_orig);
11553 		return (ENOBUFS);
11554 	}
11555 
11556 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11557 
11558 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11559 	    ixa_cookie);
11560 	if (error != 0 && error != EWOULDBLOCK) {
11561 		/* No point in sending the other fragments */
11562 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11563 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11564 		freeb(hdr_mp);
11565 		freemsg(mp_orig);
11566 		return (error);
11567 	}
11568 
11569 	/* No need to redo state machine in loop */
11570 	ixaflags &= ~IXAF_REACH_CONF;
11571 
11572 	/* Advance the offset to the second frag starting point. */
11573 	offset += len;
11574 	/*
11575 	 * Update hdr_len from the copied header - there might be less options
11576 	 * in the later fragments.
11577 	 */
11578 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11579 	/* Loop until done. */
11580 	for (;;) {
11581 		uint16_t	offset_and_flags;
11582 		uint16_t	ip_len;
11583 
11584 		if (ip_data_end - offset > len) {
11585 			/*
11586 			 * Carve off the appropriate amount from the original
11587 			 * datagram.
11588 			 */
11589 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11590 				mp = NULL;
11591 				break;
11592 			}
11593 			/*
11594 			 * More frags after this one.  Get another copy
11595 			 * of the header.
11596 			 */
11597 			if (carve_mp->b_datap->db_ref == 1 &&
11598 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11599 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11600 				/* Inline IP header */
11601 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11602 				    hdr_mp->b_rptr;
11603 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11604 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11605 				mp = carve_mp;
11606 			} else {
11607 				if (!(mp = copyb(hdr_mp))) {
11608 					freemsg(carve_mp);
11609 					break;
11610 				}
11611 				/* Get priority marking, if any. */
11612 				mp->b_band = priority;
11613 				mp->b_cont = carve_mp;
11614 			}
11615 			ipha = (ipha_t *)mp->b_rptr;
11616 			offset_and_flags = IPH_MF;
11617 		} else {
11618 			/*
11619 			 * Last frag.  Consume the header. Set len to
11620 			 * the length of this last piece.
11621 			 */
11622 			len = ip_data_end - offset;
11623 
11624 			/*
11625 			 * Carve off the appropriate amount from the original
11626 			 * datagram.
11627 			 */
11628 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11629 				mp = NULL;
11630 				break;
11631 			}
11632 			if (carve_mp->b_datap->db_ref == 1 &&
11633 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11634 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11635 				/* Inline IP header */
11636 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11637 				    hdr_mp->b_rptr;
11638 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11639 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11640 				mp = carve_mp;
11641 				freeb(hdr_mp);
11642 				hdr_mp = mp;
11643 			} else {
11644 				mp = hdr_mp;
11645 				/* Get priority marking, if any. */
11646 				mp->b_band = priority;
11647 				mp->b_cont = carve_mp;
11648 			}
11649 			ipha = (ipha_t *)mp->b_rptr;
11650 			/* A frag of a frag might have IPH_MF non-zero */
11651 			offset_and_flags =
11652 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11653 			    IPH_MF;
11654 		}
11655 		offset_and_flags |= (uint16_t)(offset >> 3);
11656 		offset_and_flags |= (uint16_t)frag_flag;
11657 		/* Store the offset and flags in the IP header. */
11658 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11659 
11660 		/* Store the length in the IP header. */
11661 		ip_len = (uint16_t)(len + hdr_len);
11662 		ipha->ipha_length = htons(ip_len);
11663 
11664 		/*
11665 		 * Set the IP header checksum.	Note that mp is just
11666 		 * the header, so this is easy to pass to ip_csum.
11667 		 */
11668 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11669 
11670 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11671 
11672 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11673 		    nolzid, ixa_cookie);
11674 		/* All done if we just consumed the hdr_mp. */
11675 		if (mp == hdr_mp) {
11676 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11677 			return (error);
11678 		}
11679 		if (error != 0 && error != EWOULDBLOCK) {
11680 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11681 			    mblk_t *, hdr_mp);
11682 			/* No point in sending the other fragments */
11683 			break;
11684 		}
11685 
11686 		/* Otherwise, advance and loop. */
11687 		offset += len;
11688 	}
11689 	/* Clean up following allocation failure. */
11690 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11691 	ip_drop_output("FragFails: loop ended", NULL, ill);
11692 	if (mp != hdr_mp)
11693 		freeb(hdr_mp);
11694 	if (mp != mp_orig)
11695 		freemsg(mp_orig);
11696 	return (error);
11697 }
11698 
11699 /*
11700  * Copy the header plus those options which have the copy bit set
11701  */
11702 static mblk_t *
11703 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11704     mblk_t *src)
11705 {
11706 	mblk_t	*mp;
11707 	uchar_t	*up;
11708 
11709 	/*
11710 	 * Quick check if we need to look for options without the copy bit
11711 	 * set
11712 	 */
11713 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11714 	if (!mp)
11715 		return (mp);
11716 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11717 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11718 		bcopy(rptr, mp->b_rptr, hdr_len);
11719 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11720 		return (mp);
11721 	}
11722 	up  = mp->b_rptr;
11723 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11724 	up += IP_SIMPLE_HDR_LENGTH;
11725 	rptr += IP_SIMPLE_HDR_LENGTH;
11726 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11727 	while (hdr_len > 0) {
11728 		uint32_t optval;
11729 		uint32_t optlen;
11730 
11731 		optval = *rptr;
11732 		if (optval == IPOPT_EOL)
11733 			break;
11734 		if (optval == IPOPT_NOP)
11735 			optlen = 1;
11736 		else
11737 			optlen = rptr[1];
11738 		if (optval & IPOPT_COPY) {
11739 			bcopy(rptr, up, optlen);
11740 			up += optlen;
11741 		}
11742 		rptr += optlen;
11743 		hdr_len -= optlen;
11744 	}
11745 	/*
11746 	 * Make sure that we drop an even number of words by filling
11747 	 * with EOL to the next word boundary.
11748 	 */
11749 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11750 	    hdr_len & 0x3; hdr_len++)
11751 		*up++ = IPOPT_EOL;
11752 	mp->b_wptr = up;
11753 	/* Update header length */
11754 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11755 	return (mp);
11756 }
11757 
11758 /*
11759  * Update any source route, record route, or timestamp options when
11760  * sending a packet back to ourselves.
11761  * Check that we are at end of strict source route.
11762  * The options have been sanity checked by ip_output_options().
11763  */
11764 void
11765 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11766 {
11767 	ipoptp_t	opts;
11768 	uchar_t		*opt;
11769 	uint8_t		optval;
11770 	uint8_t		optlen;
11771 	ipaddr_t	dst;
11772 	uint32_t	ts;
11773 	timestruc_t	now;
11774 
11775 	for (optval = ipoptp_first(&opts, ipha);
11776 	    optval != IPOPT_EOL;
11777 	    optval = ipoptp_next(&opts)) {
11778 		opt = opts.ipoptp_cur;
11779 		optlen = opts.ipoptp_len;
11780 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11781 		switch (optval) {
11782 			uint32_t off;
11783 		case IPOPT_SSRR:
11784 		case IPOPT_LSRR:
11785 			off = opt[IPOPT_OFFSET];
11786 			off--;
11787 			if (optlen < IP_ADDR_LEN ||
11788 			    off > optlen - IP_ADDR_LEN) {
11789 				/* End of source route */
11790 				break;
11791 			}
11792 			/*
11793 			 * This will only happen if two consecutive entries
11794 			 * in the source route contains our address or if
11795 			 * it is a packet with a loose source route which
11796 			 * reaches us before consuming the whole source route
11797 			 */
11798 
11799 			if (optval == IPOPT_SSRR) {
11800 				return;
11801 			}
11802 			/*
11803 			 * Hack: instead of dropping the packet truncate the
11804 			 * source route to what has been used by filling the
11805 			 * rest with IPOPT_NOP.
11806 			 */
11807 			opt[IPOPT_OLEN] = (uint8_t)off;
11808 			while (off < optlen) {
11809 				opt[off++] = IPOPT_NOP;
11810 			}
11811 			break;
11812 		case IPOPT_RR:
11813 			off = opt[IPOPT_OFFSET];
11814 			off--;
11815 			if (optlen < IP_ADDR_LEN ||
11816 			    off > optlen - IP_ADDR_LEN) {
11817 				/* No more room - ignore */
11818 				ip1dbg((
11819 				    "ip_output_local_options: end of RR\n"));
11820 				break;
11821 			}
11822 			dst = htonl(INADDR_LOOPBACK);
11823 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11824 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11825 			break;
11826 		case IPOPT_TS:
11827 			/* Insert timestamp if there is romm */
11828 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11829 			case IPOPT_TS_TSONLY:
11830 				off = IPOPT_TS_TIMELEN;
11831 				break;
11832 			case IPOPT_TS_PRESPEC:
11833 			case IPOPT_TS_PRESPEC_RFC791:
11834 				/* Verify that the address matched */
11835 				off = opt[IPOPT_OFFSET] - 1;
11836 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
11837 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11838 					/* Not for us */
11839 					break;
11840 				}
11841 				/* FALLTHRU */
11842 			case IPOPT_TS_TSANDADDR:
11843 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
11844 				break;
11845 			default:
11846 				/*
11847 				 * ip_*put_options should have already
11848 				 * dropped this packet.
11849 				 */
11850 				cmn_err(CE_PANIC, "ip_output_local_options: "
11851 				    "unknown IT - bug in ip_output_options?\n");
11852 				return;	/* Keep "lint" happy */
11853 			}
11854 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
11855 				/* Increase overflow counter */
11856 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
11857 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
11858 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
11859 				    (off << 4);
11860 				break;
11861 			}
11862 			off = opt[IPOPT_OFFSET] - 1;
11863 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11864 			case IPOPT_TS_PRESPEC:
11865 			case IPOPT_TS_PRESPEC_RFC791:
11866 			case IPOPT_TS_TSANDADDR:
11867 				dst = htonl(INADDR_LOOPBACK);
11868 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11869 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11870 				/* FALLTHRU */
11871 			case IPOPT_TS_TSONLY:
11872 				off = opt[IPOPT_OFFSET] - 1;
11873 				/* Compute # of milliseconds since midnight */
11874 				gethrestime(&now);
11875 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
11876 				    now.tv_nsec / (NANOSEC / MILLISEC);
11877 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
11878 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
11879 				break;
11880 			}
11881 			break;
11882 		}
11883 	}
11884 }
11885 
11886 /*
11887  * Prepend an M_DATA fastpath header, and if none present prepend a
11888  * DL_UNITDATA_REQ. Frees the mblk on failure.
11889  *
11890  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
11891  * If there is a change to them, the nce will be deleted (condemned) and
11892  * a new nce_t will be created when packets are sent. Thus we need no locks
11893  * to access those fields.
11894  *
11895  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
11896  * we place b_band in dl_priority.dl_max.
11897  */
11898 static mblk_t *
11899 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
11900 {
11901 	uint_t	hlen;
11902 	mblk_t *mp1;
11903 	uint_t	priority;
11904 	uchar_t *rptr;
11905 
11906 	rptr = mp->b_rptr;
11907 
11908 	ASSERT(DB_TYPE(mp) == M_DATA);
11909 	priority = mp->b_band;
11910 
11911 	ASSERT(nce != NULL);
11912 	if ((mp1 = nce->nce_fp_mp) != NULL) {
11913 		hlen = MBLKL(mp1);
11914 		/*
11915 		 * Check if we have enough room to prepend fastpath
11916 		 * header
11917 		 */
11918 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
11919 			rptr -= hlen;
11920 			bcopy(mp1->b_rptr, rptr, hlen);
11921 			/*
11922 			 * Set the b_rptr to the start of the link layer
11923 			 * header
11924 			 */
11925 			mp->b_rptr = rptr;
11926 			return (mp);
11927 		}
11928 		mp1 = copyb(mp1);
11929 		if (mp1 == NULL) {
11930 			ill_t *ill = nce->nce_ill;
11931 
11932 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
11933 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
11934 			freemsg(mp);
11935 			return (NULL);
11936 		}
11937 		mp1->b_band = priority;
11938 		mp1->b_cont = mp;
11939 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
11940 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
11941 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
11942 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
11943 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
11944 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
11945 		/*
11946 		 * XXX disable ICK_VALID and compute checksum
11947 		 * here; can happen if nce_fp_mp changes and
11948 		 * it can't be copied now due to insufficient
11949 		 * space. (unlikely, fp mp can change, but it
11950 		 * does not increase in length)
11951 		 */
11952 		return (mp1);
11953 	}
11954 	mp1 = copyb(nce->nce_dlur_mp);
11955 
11956 	if (mp1 == NULL) {
11957 		ill_t *ill = nce->nce_ill;
11958 
11959 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
11960 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
11961 		freemsg(mp);
11962 		return (NULL);
11963 	}
11964 	mp1->b_cont = mp;
11965 	if (priority != 0) {
11966 		mp1->b_band = priority;
11967 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
11968 		    priority;
11969 	}
11970 	return (mp1);
11971 #undef rptr
11972 }
11973 
11974 /*
11975  * Finish the outbound IPsec processing. This function is called from
11976  * ipsec_out_process() if the IPsec packet was processed
11977  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
11978  * asynchronously.
11979  *
11980  * This is common to IPv4 and IPv6.
11981  */
11982 int
11983 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
11984 {
11985 	iaflags_t	ixaflags = ixa->ixa_flags;
11986 	uint_t		pktlen;
11987 
11988 
11989 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
11990 	if (ixaflags & IXAF_IS_IPV4) {
11991 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
11992 
11993 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11994 		pktlen = ntohs(ipha->ipha_length);
11995 	} else {
11996 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
11997 
11998 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
11999 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12000 	}
12001 
12002 	/*
12003 	 * We release any hard reference on the SAs here to make
12004 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12005 	 * on the SAs.
12006 	 * If in the future we want the hard latching of the SAs in the
12007 	 * ip_xmit_attr_t then we should remove this.
12008 	 */
12009 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12010 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12011 		ixa->ixa_ipsec_esp_sa = NULL;
12012 	}
12013 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12014 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12015 		ixa->ixa_ipsec_ah_sa = NULL;
12016 	}
12017 
12018 	/* Do we need to fragment? */
12019 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12020 	    pktlen > ixa->ixa_fragsize) {
12021 		if (ixaflags & IXAF_IS_IPV4) {
12022 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12023 			/*
12024 			 * We check for the DF case in ipsec_out_process
12025 			 * hence this only handles the non-DF case.
12026 			 */
12027 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12028 			    pktlen, ixa->ixa_fragsize,
12029 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12030 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12031 			    &ixa->ixa_cookie));
12032 		} else {
12033 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12034 			if (mp == NULL) {
12035 				/* MIB and ip_drop_output already done */
12036 				return (ENOMEM);
12037 			}
12038 			pktlen += sizeof (ip6_frag_t);
12039 			if (pktlen > ixa->ixa_fragsize) {
12040 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12041 				    ixa->ixa_flags, pktlen,
12042 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12043 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12044 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12045 			}
12046 		}
12047 	}
12048 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12049 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12050 	    ixa->ixa_no_loop_zoneid, NULL));
12051 }
12052 
12053 /*
12054  * Finish the inbound IPsec processing. This function is called from
12055  * ipsec_out_process() if the IPsec packet was processed
12056  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12057  * asynchronously.
12058  *
12059  * This is common to IPv4 and IPv6.
12060  */
12061 void
12062 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12063 {
12064 	iaflags_t	iraflags = ira->ira_flags;
12065 
12066 	/* Length might have changed */
12067 	if (iraflags & IRAF_IS_IPV4) {
12068 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12069 
12070 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12071 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12072 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12073 		ira->ira_protocol = ipha->ipha_protocol;
12074 
12075 		ip_fanout_v4(mp, ipha, ira);
12076 	} else {
12077 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12078 		uint8_t		*nexthdrp;
12079 
12080 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12081 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12082 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12083 		    &nexthdrp)) {
12084 			/* Malformed packet */
12085 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12086 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12087 			freemsg(mp);
12088 			return;
12089 		}
12090 		ira->ira_protocol = *nexthdrp;
12091 		ip_fanout_v6(mp, ip6h, ira);
12092 	}
12093 }
12094 
12095 /*
12096  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12097  *
12098  * If this function returns B_TRUE, the requested SA's have been filled
12099  * into the ixa_ipsec_*_sa pointers.
12100  *
12101  * If the function returns B_FALSE, the packet has been "consumed", most
12102  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12103  *
12104  * The SA references created by the protocol-specific "select"
12105  * function will be released in ip_output_post_ipsec.
12106  */
12107 static boolean_t
12108 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12109 {
12110 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12111 	ipsec_policy_t *pp;
12112 	ipsec_action_t *ap;
12113 
12114 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12115 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12116 	    (ixa->ixa_ipsec_action != NULL));
12117 
12118 	ap = ixa->ixa_ipsec_action;
12119 	if (ap == NULL) {
12120 		pp = ixa->ixa_ipsec_policy;
12121 		ASSERT(pp != NULL);
12122 		ap = pp->ipsp_act;
12123 		ASSERT(ap != NULL);
12124 	}
12125 
12126 	/*
12127 	 * We have an action.  now, let's select SA's.
12128 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12129 	 * be cached in the conn_t.
12130 	 */
12131 	if (ap->ipa_want_esp) {
12132 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12133 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12134 			    IPPROTO_ESP);
12135 		}
12136 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12137 	}
12138 
12139 	if (ap->ipa_want_ah) {
12140 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12141 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12142 			    IPPROTO_AH);
12143 		}
12144 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12145 		/*
12146 		 * The ESP and AH processing order needs to be preserved
12147 		 * when both protocols are required (ESP should be applied
12148 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12149 		 * when both ESP and AH are required, and an AH ACQUIRE
12150 		 * is needed.
12151 		 */
12152 		if (ap->ipa_want_esp && need_ah_acquire)
12153 			need_esp_acquire = B_TRUE;
12154 	}
12155 
12156 	/*
12157 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12158 	 * Release SAs that got referenced, but will not be used until we
12159 	 * acquire _all_ of the SAs we need.
12160 	 */
12161 	if (need_ah_acquire || need_esp_acquire) {
12162 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12163 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12164 			ixa->ixa_ipsec_ah_sa = NULL;
12165 		}
12166 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12167 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12168 			ixa->ixa_ipsec_esp_sa = NULL;
12169 		}
12170 
12171 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12172 		return (B_FALSE);
12173 	}
12174 
12175 	return (B_TRUE);
12176 }
12177 
12178 /*
12179  * Handle IPsec output processing.
12180  * This function is only entered once for a given packet.
12181  * We try to do things synchronously, but if we need to have user-level
12182  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12183  * will be completed
12184  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12185  *  - when asynchronous ESP is done it will do AH
12186  *
12187  * In all cases we come back in ip_output_post_ipsec() to fragment and
12188  * send out the packet.
12189  */
12190 int
12191 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12192 {
12193 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12194 	ip_stack_t	*ipst = ixa->ixa_ipst;
12195 	ipsec_stack_t	*ipss;
12196 	ipsec_policy_t	*pp;
12197 	ipsec_action_t	*ap;
12198 
12199 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12200 
12201 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12202 	    (ixa->ixa_ipsec_action != NULL));
12203 
12204 	ipss = ipst->ips_netstack->netstack_ipsec;
12205 	if (!ipsec_loaded(ipss)) {
12206 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12207 		ip_drop_packet(mp, B_TRUE, ill,
12208 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12209 		    &ipss->ipsec_dropper);
12210 		return (ENOTSUP);
12211 	}
12212 
12213 	ap = ixa->ixa_ipsec_action;
12214 	if (ap == NULL) {
12215 		pp = ixa->ixa_ipsec_policy;
12216 		ASSERT(pp != NULL);
12217 		ap = pp->ipsp_act;
12218 		ASSERT(ap != NULL);
12219 	}
12220 
12221 	/* Handle explicit drop action and bypass. */
12222 	switch (ap->ipa_act.ipa_type) {
12223 	case IPSEC_ACT_DISCARD:
12224 	case IPSEC_ACT_REJECT:
12225 		ip_drop_packet(mp, B_FALSE, ill,
12226 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12227 		return (EHOSTUNREACH);	/* IPsec policy failure */
12228 	case IPSEC_ACT_BYPASS:
12229 		return (ip_output_post_ipsec(mp, ixa));
12230 	}
12231 
12232 	/*
12233 	 * The order of processing is first insert a IP header if needed.
12234 	 * Then insert the ESP header and then the AH header.
12235 	 */
12236 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12237 		/*
12238 		 * First get the outer IP header before sending
12239 		 * it to ESP.
12240 		 */
12241 		ipha_t *oipha, *iipha;
12242 		mblk_t *outer_mp, *inner_mp;
12243 
12244 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12245 			(void) mi_strlog(ill->ill_rq, 0,
12246 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12247 			    "ipsec_out_process: "
12248 			    "Self-Encapsulation failed: Out of memory\n");
12249 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12250 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12251 			freemsg(mp);
12252 			return (ENOBUFS);
12253 		}
12254 		inner_mp = mp;
12255 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12256 		oipha = (ipha_t *)outer_mp->b_rptr;
12257 		iipha = (ipha_t *)inner_mp->b_rptr;
12258 		*oipha = *iipha;
12259 		outer_mp->b_wptr += sizeof (ipha_t);
12260 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12261 		    sizeof (ipha_t));
12262 		oipha->ipha_protocol = IPPROTO_ENCAP;
12263 		oipha->ipha_version_and_hdr_length =
12264 		    IP_SIMPLE_HDR_VERSION;
12265 		oipha->ipha_hdr_checksum = 0;
12266 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12267 		outer_mp->b_cont = inner_mp;
12268 		mp = outer_mp;
12269 
12270 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12271 	}
12272 
12273 	/* If we need to wait for a SA then we can't return any errno */
12274 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12275 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12276 	    !ipsec_out_select_sa(mp, ixa))
12277 		return (0);
12278 
12279 	/*
12280 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12281 	 * to do the heavy lifting.
12282 	 */
12283 	if (ap->ipa_want_esp) {
12284 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12285 
12286 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12287 		if (mp == NULL) {
12288 			/*
12289 			 * Either it failed or is pending. In the former case
12290 			 * ipIfStatsInDiscards was increased.
12291 			 */
12292 			return (0);
12293 		}
12294 	}
12295 
12296 	if (ap->ipa_want_ah) {
12297 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12298 
12299 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12300 		if (mp == NULL) {
12301 			/*
12302 			 * Either it failed or is pending. In the former case
12303 			 * ipIfStatsInDiscards was increased.
12304 			 */
12305 			return (0);
12306 		}
12307 	}
12308 	/*
12309 	 * We are done with IPsec processing. Send it over
12310 	 * the wire.
12311 	 */
12312 	return (ip_output_post_ipsec(mp, ixa));
12313 }
12314 
12315 /*
12316  * ioctls that go through a down/up sequence may need to wait for the down
12317  * to complete. This involves waiting for the ire and ipif refcnts to go down
12318  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12319  */
12320 /* ARGSUSED */
12321 void
12322 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12323 {
12324 	struct iocblk *iocp;
12325 	mblk_t *mp1;
12326 	ip_ioctl_cmd_t *ipip;
12327 	int err;
12328 	sin_t	*sin;
12329 	struct lifreq *lifr;
12330 	struct ifreq *ifr;
12331 
12332 	iocp = (struct iocblk *)mp->b_rptr;
12333 	ASSERT(ipsq != NULL);
12334 	/* Existence of mp1 verified in ip_wput_nondata */
12335 	mp1 = mp->b_cont->b_cont;
12336 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12337 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12338 		/*
12339 		 * Special case where ipx_current_ipif is not set:
12340 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12341 		 * We are here as were not able to complete the operation in
12342 		 * ipif_set_values because we could not become exclusive on
12343 		 * the new ipsq.
12344 		 */
12345 		ill_t *ill = q->q_ptr;
12346 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12347 	}
12348 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12349 
12350 	if (ipip->ipi_cmd_type == IF_CMD) {
12351 		/* This a old style SIOC[GS]IF* command */
12352 		ifr = (struct ifreq *)mp1->b_rptr;
12353 		sin = (sin_t *)&ifr->ifr_addr;
12354 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12355 		/* This a new style SIOC[GS]LIF* command */
12356 		lifr = (struct lifreq *)mp1->b_rptr;
12357 		sin = (sin_t *)&lifr->lifr_addr;
12358 	} else {
12359 		sin = NULL;
12360 	}
12361 
12362 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12363 	    q, mp, ipip, mp1->b_rptr);
12364 
12365 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12366 	    int, ipip->ipi_cmd,
12367 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12368 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12369 
12370 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12371 }
12372 
12373 /*
12374  * ioctl processing
12375  *
12376  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12377  * the ioctl command in the ioctl tables, determines the copyin data size
12378  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12379  *
12380  * ioctl processing then continues when the M_IOCDATA makes its way down to
12381  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12382  * associated 'conn' is refheld till the end of the ioctl and the general
12383  * ioctl processing function ip_process_ioctl() is called to extract the
12384  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12385  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12386  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12387  * is used to extract the ioctl's arguments.
12388  *
12389  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12390  * so goes thru the serialization primitive ipsq_try_enter. Then the
12391  * appropriate function to handle the ioctl is called based on the entry in
12392  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12393  * which also refreleases the 'conn' that was refheld at the start of the
12394  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12395  *
12396  * Many exclusive ioctls go thru an internal down up sequence as part of
12397  * the operation. For example an attempt to change the IP address of an
12398  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12399  * does all the cleanup such as deleting all ires that use this address.
12400  * Then we need to wait till all references to the interface go away.
12401  */
12402 void
12403 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12404 {
12405 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12406 	ip_ioctl_cmd_t *ipip = arg;
12407 	ip_extract_func_t *extract_funcp;
12408 	cmd_info_t ci;
12409 	int err;
12410 	boolean_t entered_ipsq = B_FALSE;
12411 
12412 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12413 
12414 	if (ipip == NULL)
12415 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12416 
12417 	/*
12418 	 * SIOCLIFADDIF needs to go thru a special path since the
12419 	 * ill may not exist yet. This happens in the case of lo0
12420 	 * which is created using this ioctl.
12421 	 */
12422 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12423 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12424 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12425 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12426 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12427 		return;
12428 	}
12429 
12430 	ci.ci_ipif = NULL;
12431 	switch (ipip->ipi_cmd_type) {
12432 	case MISC_CMD:
12433 	case MSFILT_CMD:
12434 		/*
12435 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12436 		 */
12437 		if (ipip->ipi_cmd == IF_UNITSEL) {
12438 			/* ioctl comes down the ill */
12439 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12440 			ipif_refhold(ci.ci_ipif);
12441 		}
12442 		err = 0;
12443 		ci.ci_sin = NULL;
12444 		ci.ci_sin6 = NULL;
12445 		ci.ci_lifr = NULL;
12446 		extract_funcp = NULL;
12447 		break;
12448 
12449 	case IF_CMD:
12450 	case LIF_CMD:
12451 		extract_funcp = ip_extract_lifreq;
12452 		break;
12453 
12454 	case ARP_CMD:
12455 	case XARP_CMD:
12456 		extract_funcp = ip_extract_arpreq;
12457 		break;
12458 
12459 	default:
12460 		ASSERT(0);
12461 	}
12462 
12463 	if (extract_funcp != NULL) {
12464 		err = (*extract_funcp)(q, mp, ipip, &ci);
12465 		if (err != 0) {
12466 			DTRACE_PROBE4(ipif__ioctl,
12467 			    char *, "ip_process_ioctl finish err",
12468 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12469 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12470 			return;
12471 		}
12472 
12473 		/*
12474 		 * All of the extraction functions return a refheld ipif.
12475 		 */
12476 		ASSERT(ci.ci_ipif != NULL);
12477 	}
12478 
12479 	if (!(ipip->ipi_flags & IPI_WR)) {
12480 		/*
12481 		 * A return value of EINPROGRESS means the ioctl is
12482 		 * either queued and waiting for some reason or has
12483 		 * already completed.
12484 		 */
12485 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12486 		    ci.ci_lifr);
12487 		if (ci.ci_ipif != NULL) {
12488 			DTRACE_PROBE4(ipif__ioctl,
12489 			    char *, "ip_process_ioctl finish RD",
12490 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12491 			    ipif_t *, ci.ci_ipif);
12492 			ipif_refrele(ci.ci_ipif);
12493 		} else {
12494 			DTRACE_PROBE4(ipif__ioctl,
12495 			    char *, "ip_process_ioctl finish RD",
12496 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12497 		}
12498 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12499 		return;
12500 	}
12501 
12502 	ASSERT(ci.ci_ipif != NULL);
12503 
12504 	/*
12505 	 * If ipsq is non-NULL, we are already being called exclusively
12506 	 */
12507 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12508 	if (ipsq == NULL) {
12509 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12510 		    NEW_OP, B_TRUE);
12511 		if (ipsq == NULL) {
12512 			ipif_refrele(ci.ci_ipif);
12513 			return;
12514 		}
12515 		entered_ipsq = B_TRUE;
12516 	}
12517 	/*
12518 	 * Release the ipif so that ipif_down and friends that wait for
12519 	 * references to go away are not misled about the current ipif_refcnt
12520 	 * values. We are writer so we can access the ipif even after releasing
12521 	 * the ipif.
12522 	 */
12523 	ipif_refrele(ci.ci_ipif);
12524 
12525 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12526 
12527 	/*
12528 	 * A return value of EINPROGRESS means the ioctl is
12529 	 * either queued and waiting for some reason or has
12530 	 * already completed.
12531 	 */
12532 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12533 
12534 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12535 	    int, ipip->ipi_cmd,
12536 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12537 	    ipif_t *, ci.ci_ipif);
12538 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12539 
12540 	if (entered_ipsq)
12541 		ipsq_exit(ipsq);
12542 }
12543 
12544 /*
12545  * Complete the ioctl. Typically ioctls use the mi package and need to
12546  * do mi_copyout/mi_copy_done.
12547  */
12548 void
12549 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12550 {
12551 	conn_t	*connp = NULL;
12552 
12553 	if (err == EINPROGRESS)
12554 		return;
12555 
12556 	if (CONN_Q(q)) {
12557 		connp = Q_TO_CONN(q);
12558 		ASSERT(connp->conn_ref >= 2);
12559 	}
12560 
12561 	switch (mode) {
12562 	case COPYOUT:
12563 		if (err == 0)
12564 			mi_copyout(q, mp);
12565 		else
12566 			mi_copy_done(q, mp, err);
12567 		break;
12568 
12569 	case NO_COPYOUT:
12570 		mi_copy_done(q, mp, err);
12571 		break;
12572 
12573 	default:
12574 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12575 		break;
12576 	}
12577 
12578 	/*
12579 	 * The conn refhold and ioctlref placed on the conn at the start of the
12580 	 * ioctl are released here.
12581 	 */
12582 	if (connp != NULL) {
12583 		CONN_DEC_IOCTLREF(connp);
12584 		CONN_OPER_PENDING_DONE(connp);
12585 	}
12586 
12587 	if (ipsq != NULL)
12588 		ipsq_current_finish(ipsq);
12589 }
12590 
12591 /* Handles all non data messages */
12592 void
12593 ip_wput_nondata(queue_t *q, mblk_t *mp)
12594 {
12595 	mblk_t		*mp1;
12596 	struct iocblk	*iocp;
12597 	ip_ioctl_cmd_t	*ipip;
12598 	conn_t		*connp;
12599 	cred_t		*cr;
12600 	char		*proto_str;
12601 
12602 	if (CONN_Q(q))
12603 		connp = Q_TO_CONN(q);
12604 	else
12605 		connp = NULL;
12606 
12607 	switch (DB_TYPE(mp)) {
12608 	case M_IOCTL:
12609 		/*
12610 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12611 		 * will arrange to copy in associated control structures.
12612 		 */
12613 		ip_sioctl_copyin_setup(q, mp);
12614 		return;
12615 	case M_IOCDATA:
12616 		/*
12617 		 * Ensure that this is associated with one of our trans-
12618 		 * parent ioctls.  If it's not ours, discard it if we're
12619 		 * running as a driver, or pass it on if we're a module.
12620 		 */
12621 		iocp = (struct iocblk *)mp->b_rptr;
12622 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12623 		if (ipip == NULL) {
12624 			if (q->q_next == NULL) {
12625 				goto nak;
12626 			} else {
12627 				putnext(q, mp);
12628 			}
12629 			return;
12630 		}
12631 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12632 			/*
12633 			 * The ioctl is one we recognise, but is not consumed
12634 			 * by IP as a module and we are a module, so we drop
12635 			 */
12636 			goto nak;
12637 		}
12638 
12639 		/* IOCTL continuation following copyin or copyout. */
12640 		if (mi_copy_state(q, mp, NULL) == -1) {
12641 			/*
12642 			 * The copy operation failed.  mi_copy_state already
12643 			 * cleaned up, so we're out of here.
12644 			 */
12645 			return;
12646 		}
12647 		/*
12648 		 * If we just completed a copy in, we become writer and
12649 		 * continue processing in ip_sioctl_copyin_done.  If it
12650 		 * was a copy out, we call mi_copyout again.  If there is
12651 		 * nothing more to copy out, it will complete the IOCTL.
12652 		 */
12653 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12654 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12655 				mi_copy_done(q, mp, EPROTO);
12656 				return;
12657 			}
12658 			/*
12659 			 * Check for cases that need more copying.  A return
12660 			 * value of 0 means a second copyin has been started,
12661 			 * so we return; a return value of 1 means no more
12662 			 * copying is needed, so we continue.
12663 			 */
12664 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12665 			    MI_COPY_COUNT(mp) == 1) {
12666 				if (ip_copyin_msfilter(q, mp) == 0)
12667 					return;
12668 			}
12669 			/*
12670 			 * Refhold the conn, till the ioctl completes. This is
12671 			 * needed in case the ioctl ends up in the pending mp
12672 			 * list. Every mp in the ipx_pending_mp list must have
12673 			 * a refhold on the conn to resume processing. The
12674 			 * refhold is released when the ioctl completes
12675 			 * (whether normally or abnormally). An ioctlref is also
12676 			 * placed on the conn to prevent TCP from removing the
12677 			 * queue needed to send the ioctl reply back.
12678 			 * In all cases ip_ioctl_finish is called to finish
12679 			 * the ioctl and release the refholds.
12680 			 */
12681 			if (connp != NULL) {
12682 				/* This is not a reentry */
12683 				CONN_INC_REF(connp);
12684 				CONN_INC_IOCTLREF(connp);
12685 			} else {
12686 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12687 					mi_copy_done(q, mp, EINVAL);
12688 					return;
12689 				}
12690 			}
12691 
12692 			ip_process_ioctl(NULL, q, mp, ipip);
12693 
12694 		} else {
12695 			mi_copyout(q, mp);
12696 		}
12697 		return;
12698 
12699 	case M_IOCNAK:
12700 		/*
12701 		 * The only way we could get here is if a resolver didn't like
12702 		 * an IOCTL we sent it.	 This shouldn't happen.
12703 		 */
12704 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12705 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12706 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12707 		freemsg(mp);
12708 		return;
12709 	case M_IOCACK:
12710 		/* /dev/ip shouldn't see this */
12711 		goto nak;
12712 	case M_FLUSH:
12713 		if (*mp->b_rptr & FLUSHW)
12714 			flushq(q, FLUSHALL);
12715 		if (q->q_next) {
12716 			putnext(q, mp);
12717 			return;
12718 		}
12719 		if (*mp->b_rptr & FLUSHR) {
12720 			*mp->b_rptr &= ~FLUSHW;
12721 			qreply(q, mp);
12722 			return;
12723 		}
12724 		freemsg(mp);
12725 		return;
12726 	case M_CTL:
12727 		break;
12728 	case M_PROTO:
12729 	case M_PCPROTO:
12730 		/*
12731 		 * The only PROTO messages we expect are SNMP-related.
12732 		 */
12733 		switch (((union T_primitives *)mp->b_rptr)->type) {
12734 		case T_SVR4_OPTMGMT_REQ:
12735 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12736 			    "flags %x\n",
12737 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12738 
12739 			if (connp == NULL) {
12740 				proto_str = "T_SVR4_OPTMGMT_REQ";
12741 				goto protonak;
12742 			}
12743 
12744 			/*
12745 			 * All Solaris components should pass a db_credp
12746 			 * for this TPI message, hence we ASSERT.
12747 			 * But in case there is some other M_PROTO that looks
12748 			 * like a TPI message sent by some other kernel
12749 			 * component, we check and return an error.
12750 			 */
12751 			cr = msg_getcred(mp, NULL);
12752 			ASSERT(cr != NULL);
12753 			if (cr == NULL) {
12754 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12755 				if (mp != NULL)
12756 					qreply(q, mp);
12757 				return;
12758 			}
12759 
12760 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12761 				proto_str = "Bad SNMPCOM request?";
12762 				goto protonak;
12763 			}
12764 			return;
12765 		default:
12766 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12767 			    (int)*(uint_t *)mp->b_rptr));
12768 			freemsg(mp);
12769 			return;
12770 		}
12771 	default:
12772 		break;
12773 	}
12774 	if (q->q_next) {
12775 		putnext(q, mp);
12776 	} else
12777 		freemsg(mp);
12778 	return;
12779 
12780 nak:
12781 	iocp->ioc_error = EINVAL;
12782 	mp->b_datap->db_type = M_IOCNAK;
12783 	iocp->ioc_count = 0;
12784 	qreply(q, mp);
12785 	return;
12786 
12787 protonak:
12788 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12789 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12790 		qreply(q, mp);
12791 }
12792 
12793 /*
12794  * Process IP options in an outbound packet.  Verify that the nexthop in a
12795  * strict source route is onlink.
12796  * Returns non-zero if something fails in which case an ICMP error has been
12797  * sent and mp freed.
12798  *
12799  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12800  */
12801 int
12802 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12803 {
12804 	ipoptp_t	opts;
12805 	uchar_t		*opt;
12806 	uint8_t		optval;
12807 	uint8_t		optlen;
12808 	ipaddr_t	dst;
12809 	intptr_t	code = 0;
12810 	ire_t		*ire;
12811 	ip_stack_t	*ipst = ixa->ixa_ipst;
12812 	ip_recv_attr_t	iras;
12813 
12814 	ip2dbg(("ip_output_options\n"));
12815 
12816 	dst = ipha->ipha_dst;
12817 	for (optval = ipoptp_first(&opts, ipha);
12818 	    optval != IPOPT_EOL;
12819 	    optval = ipoptp_next(&opts)) {
12820 		opt = opts.ipoptp_cur;
12821 		optlen = opts.ipoptp_len;
12822 		ip2dbg(("ip_output_options: opt %d, len %d\n",
12823 		    optval, optlen));
12824 		switch (optval) {
12825 			uint32_t off;
12826 		case IPOPT_SSRR:
12827 		case IPOPT_LSRR:
12828 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12829 				ip1dbg((
12830 				    "ip_output_options: bad option offset\n"));
12831 				code = (char *)&opt[IPOPT_OLEN] -
12832 				    (char *)ipha;
12833 				goto param_prob;
12834 			}
12835 			off = opt[IPOPT_OFFSET];
12836 			ip1dbg(("ip_output_options: next hop 0x%x\n",
12837 			    ntohl(dst)));
12838 			/*
12839 			 * For strict: verify that dst is directly
12840 			 * reachable.
12841 			 */
12842 			if (optval == IPOPT_SSRR) {
12843 				ire = ire_ftable_lookup_v4(dst, 0, 0,
12844 				    IRE_IF_ALL, NULL, ALL_ZONES, ixa->ixa_tsl,
12845 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
12846 				    NULL);
12847 				if (ire == NULL) {
12848 					ip1dbg(("ip_output_options: SSRR not"
12849 					    " directly reachable: 0x%x\n",
12850 					    ntohl(dst)));
12851 					goto bad_src_route;
12852 				}
12853 				ire_refrele(ire);
12854 			}
12855 			break;
12856 		case IPOPT_RR:
12857 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12858 				ip1dbg((
12859 				    "ip_output_options: bad option offset\n"));
12860 				code = (char *)&opt[IPOPT_OLEN] -
12861 				    (char *)ipha;
12862 				goto param_prob;
12863 			}
12864 			break;
12865 		case IPOPT_TS:
12866 			/*
12867 			 * Verify that length >=5 and that there is either
12868 			 * room for another timestamp or that the overflow
12869 			 * counter is not maxed out.
12870 			 */
12871 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
12872 			if (optlen < IPOPT_MINLEN_IT) {
12873 				goto param_prob;
12874 			}
12875 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12876 				ip1dbg((
12877 				    "ip_output_options: bad option offset\n"));
12878 				code = (char *)&opt[IPOPT_OFFSET] -
12879 				    (char *)ipha;
12880 				goto param_prob;
12881 			}
12882 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12883 			case IPOPT_TS_TSONLY:
12884 				off = IPOPT_TS_TIMELEN;
12885 				break;
12886 			case IPOPT_TS_TSANDADDR:
12887 			case IPOPT_TS_PRESPEC:
12888 			case IPOPT_TS_PRESPEC_RFC791:
12889 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12890 				break;
12891 			default:
12892 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
12893 				    (char *)ipha;
12894 				goto param_prob;
12895 			}
12896 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
12897 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
12898 				/*
12899 				 * No room and the overflow counter is 15
12900 				 * already.
12901 				 */
12902 				goto param_prob;
12903 			}
12904 			break;
12905 		}
12906 	}
12907 
12908 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
12909 		return (0);
12910 
12911 	ip1dbg(("ip_output_options: error processing IP options."));
12912 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
12913 
12914 param_prob:
12915 	bzero(&iras, sizeof (iras));
12916 	iras.ira_ill = iras.ira_rill = ill;
12917 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12918 	iras.ira_rifindex = iras.ira_ruifindex;
12919 	iras.ira_flags = IRAF_IS_IPV4;
12920 
12921 	ip_drop_output("ip_output_options", mp, ill);
12922 	icmp_param_problem(mp, (uint8_t)code, &iras);
12923 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12924 	return (-1);
12925 
12926 bad_src_route:
12927 	bzero(&iras, sizeof (iras));
12928 	iras.ira_ill = iras.ira_rill = ill;
12929 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12930 	iras.ira_rifindex = iras.ira_ruifindex;
12931 	iras.ira_flags = IRAF_IS_IPV4;
12932 
12933 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
12934 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
12935 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12936 	return (-1);
12937 }
12938 
12939 /*
12940  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
12941  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
12942  * thru /etc/system.
12943  */
12944 #define	CONN_MAXDRAINCNT	64
12945 
12946 static void
12947 conn_drain_init(ip_stack_t *ipst)
12948 {
12949 	int i, j;
12950 	idl_tx_list_t *itl_tx;
12951 
12952 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
12953 
12954 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
12955 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
12956 		/*
12957 		 * Default value of the number of drainers is the
12958 		 * number of cpus, subject to maximum of 8 drainers.
12959 		 */
12960 		if (boot_max_ncpus != -1)
12961 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
12962 		else
12963 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
12964 	}
12965 
12966 	ipst->ips_idl_tx_list =
12967 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
12968 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
12969 		itl_tx =  &ipst->ips_idl_tx_list[i];
12970 		itl_tx->txl_drain_list =
12971 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
12972 		    sizeof (idl_t), KM_SLEEP);
12973 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
12974 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
12975 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
12976 			    MUTEX_DEFAULT, NULL);
12977 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
12978 		}
12979 	}
12980 }
12981 
12982 static void
12983 conn_drain_fini(ip_stack_t *ipst)
12984 {
12985 	int i;
12986 	idl_tx_list_t *itl_tx;
12987 
12988 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
12989 		itl_tx =  &ipst->ips_idl_tx_list[i];
12990 		kmem_free(itl_tx->txl_drain_list,
12991 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
12992 	}
12993 	kmem_free(ipst->ips_idl_tx_list,
12994 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
12995 	ipst->ips_idl_tx_list = NULL;
12996 }
12997 
12998 /*
12999  * Flow control has blocked us from proceeding.  Insert the given conn in one
13000  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13001  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13002  * will call conn_walk_drain().  See the flow control notes at the top of this
13003  * file for more details.
13004  */
13005 void
13006 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13007 {
13008 	idl_t	*idl = tx_list->txl_drain_list;
13009 	uint_t	index;
13010 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13011 
13012 	mutex_enter(&connp->conn_lock);
13013 	if (connp->conn_state_flags & CONN_CLOSING) {
13014 		/*
13015 		 * The conn is closing as a result of which CONN_CLOSING
13016 		 * is set. Return.
13017 		 */
13018 		mutex_exit(&connp->conn_lock);
13019 		return;
13020 	} else if (connp->conn_idl == NULL) {
13021 		/*
13022 		 * Assign the next drain list round robin. We dont' use
13023 		 * a lock, and thus it may not be strictly round robin.
13024 		 * Atomicity of load/stores is enough to make sure that
13025 		 * conn_drain_list_index is always within bounds.
13026 		 */
13027 		index = tx_list->txl_drain_index;
13028 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13029 		connp->conn_idl = &tx_list->txl_drain_list[index];
13030 		index++;
13031 		if (index == ipst->ips_conn_drain_list_cnt)
13032 			index = 0;
13033 		tx_list->txl_drain_index = index;
13034 	} else {
13035 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13036 	}
13037 	mutex_exit(&connp->conn_lock);
13038 
13039 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
13040 	if ((connp->conn_drain_prev != NULL) ||
13041 	    (connp->conn_state_flags & CONN_CLOSING)) {
13042 		/*
13043 		 * The conn is already in the drain list, OR
13044 		 * the conn is closing. We need to check again for
13045 		 * the closing case again since close can happen
13046 		 * after we drop the conn_lock, and before we
13047 		 * acquire the CONN_DRAIN_LIST_LOCK.
13048 		 */
13049 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
13050 		return;
13051 	} else {
13052 		idl = connp->conn_idl;
13053 	}
13054 
13055 	/*
13056 	 * The conn is not in the drain list. Insert it at the
13057 	 * tail of the drain list. The drain list is circular
13058 	 * and doubly linked. idl_conn points to the 1st element
13059 	 * in the list.
13060 	 */
13061 	if (idl->idl_conn == NULL) {
13062 		idl->idl_conn = connp;
13063 		connp->conn_drain_next = connp;
13064 		connp->conn_drain_prev = connp;
13065 	} else {
13066 		conn_t *head = idl->idl_conn;
13067 
13068 		connp->conn_drain_next = head;
13069 		connp->conn_drain_prev = head->conn_drain_prev;
13070 		head->conn_drain_prev->conn_drain_next = connp;
13071 		head->conn_drain_prev = connp;
13072 	}
13073 	/*
13074 	 * For non streams based sockets assert flow control.
13075 	 */
13076 	conn_setqfull(connp, NULL);
13077 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
13078 }
13079 
13080 static void
13081 conn_drain_remove(conn_t *connp)
13082 {
13083 	idl_t *idl = connp->conn_idl;
13084 
13085 	if (idl != NULL) {
13086 		/*
13087 		 * Remove ourself from the drain list.
13088 		 */
13089 		if (connp->conn_drain_next == connp) {
13090 			/* Singleton in the list */
13091 			ASSERT(connp->conn_drain_prev == connp);
13092 			idl->idl_conn = NULL;
13093 		} else {
13094 			connp->conn_drain_prev->conn_drain_next =
13095 			    connp->conn_drain_next;
13096 			connp->conn_drain_next->conn_drain_prev =
13097 			    connp->conn_drain_prev;
13098 			if (idl->idl_conn == connp)
13099 				idl->idl_conn = connp->conn_drain_next;
13100 		}
13101 
13102 		/*
13103 		 * NOTE: because conn_idl is associated with a specific drain
13104 		 * list which in turn is tied to the index the TX ring
13105 		 * (txl_cookie) hashes to, and because the TX ring can change
13106 		 * over the lifetime of the conn_t, we must clear conn_idl so
13107 		 * a subsequent conn_drain_insert() will set conn_idl again
13108 		 * based on the latest txl_cookie.
13109 		 */
13110 		connp->conn_idl = NULL;
13111 	}
13112 	connp->conn_drain_next = NULL;
13113 	connp->conn_drain_prev = NULL;
13114 
13115 	conn_clrqfull(connp, NULL);
13116 	/*
13117 	 * For streams based sockets open up flow control.
13118 	 */
13119 	if (!IPCL_IS_NONSTR(connp))
13120 		enableok(connp->conn_wq);
13121 }
13122 
13123 /*
13124  * This conn is closing, and we are called from ip_close. OR
13125  * this conn is draining because flow-control on the ill has been relieved.
13126  *
13127  * We must also need to remove conn's on this idl from the list, and also
13128  * inform the sockfs upcalls about the change in flow-control.
13129  */
13130 static void
13131 conn_drain(conn_t *connp, boolean_t closing)
13132 {
13133 	idl_t *idl;
13134 	conn_t *next_connp;
13135 
13136 	/*
13137 	 * connp->conn_idl is stable at this point, and no lock is needed
13138 	 * to check it. If we are called from ip_close, close has already
13139 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13140 	 * called us only because conn_idl is non-null. If we are called thru
13141 	 * service, conn_idl could be null, but it cannot change because
13142 	 * service is single-threaded per queue, and there cannot be another
13143 	 * instance of service trying to call conn_drain_insert on this conn
13144 	 * now.
13145 	 */
13146 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13147 
13148 	/*
13149 	 * If the conn doesn't exist or is not on a drain list, bail.
13150 	 */
13151 	if (connp == NULL || connp->conn_idl == NULL ||
13152 	    connp->conn_drain_prev == NULL) {
13153 		return;
13154 	}
13155 
13156 	idl = connp->conn_idl;
13157 	if (!closing) {
13158 		next_connp = connp->conn_drain_next;
13159 		while (next_connp != connp) {
13160 			conn_t *delconnp = next_connp;
13161 
13162 			next_connp = next_connp->conn_drain_next;
13163 			conn_drain_remove(delconnp);
13164 		}
13165 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13166 	}
13167 	conn_drain_remove(connp);
13168 }
13169 
13170 /*
13171  * Write service routine. Shared perimeter entry point.
13172  * The device queue's messages has fallen below the low water mark and STREAMS
13173  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13174  * each waiting conn.
13175  */
13176 void
13177 ip_wsrv(queue_t *q)
13178 {
13179 	ill_t	*ill;
13180 
13181 	ill = (ill_t *)q->q_ptr;
13182 	if (ill->ill_state_flags == 0) {
13183 		ip_stack_t *ipst = ill->ill_ipst;
13184 
13185 		/*
13186 		 * The device flow control has opened up.
13187 		 * Walk through conn drain lists and qenable the
13188 		 * first conn in each list. This makes sense only
13189 		 * if the stream is fully plumbed and setup.
13190 		 * Hence the ill_state_flags check above.
13191 		 */
13192 		ip1dbg(("ip_wsrv: walking\n"));
13193 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13194 		enableok(ill->ill_wq);
13195 	}
13196 }
13197 
13198 /*
13199  * Callback to disable flow control in IP.
13200  *
13201  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13202  * is enabled.
13203  *
13204  * When MAC_TX() is not able to send any more packets, dld sets its queue
13205  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13206  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13207  * function and wakes up corresponding mac worker threads, which in turn
13208  * calls this callback function, and disables flow control.
13209  */
13210 void
13211 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13212 {
13213 	ill_t *ill = (ill_t *)arg;
13214 	ip_stack_t *ipst = ill->ill_ipst;
13215 	idl_tx_list_t *idl_txl;
13216 
13217 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13218 	mutex_enter(&idl_txl->txl_lock);
13219 	/* add code to to set a flag to indicate idl_txl is enabled */
13220 	conn_walk_drain(ipst, idl_txl);
13221 	mutex_exit(&idl_txl->txl_lock);
13222 }
13223 
13224 /*
13225  * Flow control has been relieved and STREAMS has backenabled us; drain
13226  * all the conn lists on `tx_list'.
13227  */
13228 static void
13229 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13230 {
13231 	int i;
13232 	idl_t *idl;
13233 
13234 	IP_STAT(ipst, ip_conn_walk_drain);
13235 
13236 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13237 		idl = &tx_list->txl_drain_list[i];
13238 		mutex_enter(&idl->idl_lock);
13239 		conn_drain(idl->idl_conn, B_FALSE);
13240 		mutex_exit(&idl->idl_lock);
13241 	}
13242 }
13243 
13244 /*
13245  * Determine if the ill and multicast aspects of that packets
13246  * "matches" the conn.
13247  */
13248 boolean_t
13249 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13250 {
13251 	ill_t		*ill = ira->ira_rill;
13252 	zoneid_t	zoneid = ira->ira_zoneid;
13253 	uint_t		in_ifindex;
13254 	ipaddr_t	dst, src;
13255 
13256 	dst = ipha->ipha_dst;
13257 	src = ipha->ipha_src;
13258 
13259 	/*
13260 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13261 	 * unicast, broadcast and multicast reception to
13262 	 * conn_incoming_ifindex.
13263 	 * conn_wantpacket is called for unicast, broadcast and
13264 	 * multicast packets.
13265 	 */
13266 	in_ifindex = connp->conn_incoming_ifindex;
13267 
13268 	/* mpathd can bind to the under IPMP interface, which we allow */
13269 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13270 		if (!IS_UNDER_IPMP(ill))
13271 			return (B_FALSE);
13272 
13273 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13274 			return (B_FALSE);
13275 	}
13276 
13277 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13278 		return (B_FALSE);
13279 
13280 	if (!(ira->ira_flags & IRAF_MULTICAST))
13281 		return (B_TRUE);
13282 
13283 	if (connp->conn_multi_router) {
13284 		/* multicast packet and multicast router socket: send up */
13285 		return (B_TRUE);
13286 	}
13287 
13288 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13289 	    ipha->ipha_protocol == IPPROTO_RSVP)
13290 		return (B_TRUE);
13291 
13292 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13293 }
13294 
13295 void
13296 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13297 {
13298 	if (IPCL_IS_NONSTR(connp)) {
13299 		(*connp->conn_upcalls->su_txq_full)
13300 		    (connp->conn_upper_handle, B_TRUE);
13301 		if (flow_stopped != NULL)
13302 			*flow_stopped = B_TRUE;
13303 	} else {
13304 		queue_t *q = connp->conn_wq;
13305 
13306 		ASSERT(q != NULL);
13307 		if (!(q->q_flag & QFULL)) {
13308 			mutex_enter(QLOCK(q));
13309 			if (!(q->q_flag & QFULL)) {
13310 				/* still need to set QFULL */
13311 				q->q_flag |= QFULL;
13312 				/* set flow_stopped to true under QLOCK */
13313 				if (flow_stopped != NULL)
13314 					*flow_stopped = B_TRUE;
13315 				mutex_exit(QLOCK(q));
13316 			} else {
13317 				/* flow_stopped is left unchanged */
13318 				mutex_exit(QLOCK(q));
13319 			}
13320 		}
13321 	}
13322 }
13323 
13324 void
13325 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13326 {
13327 	if (IPCL_IS_NONSTR(connp)) {
13328 		(*connp->conn_upcalls->su_txq_full)
13329 		    (connp->conn_upper_handle, B_FALSE);
13330 		if (flow_stopped != NULL)
13331 			*flow_stopped = B_FALSE;
13332 	} else {
13333 		queue_t *q = connp->conn_wq;
13334 
13335 		ASSERT(q != NULL);
13336 		if (q->q_flag & QFULL) {
13337 			mutex_enter(QLOCK(q));
13338 			if (q->q_flag & QFULL) {
13339 				q->q_flag &= ~QFULL;
13340 				/* set flow_stopped to false under QLOCK */
13341 				if (flow_stopped != NULL)
13342 					*flow_stopped = B_FALSE;
13343 				mutex_exit(QLOCK(q));
13344 				if (q->q_flag & QWANTW)
13345 					qbackenable(q, 0);
13346 			} else {
13347 				/* flow_stopped is left unchanged */
13348 				mutex_exit(QLOCK(q));
13349 			}
13350 		}
13351 	}
13352 
13353 	mutex_enter(&connp->conn_lock);
13354 	connp->conn_blocked = B_FALSE;
13355 	mutex_exit(&connp->conn_lock);
13356 }
13357 
13358 /*
13359  * Return the length in bytes of the IPv4 headers (base header, label, and
13360  * other IP options) that will be needed based on the
13361  * ip_pkt_t structure passed by the caller.
13362  *
13363  * The returned length does not include the length of the upper level
13364  * protocol (ULP) header.
13365  * The caller needs to check that the length doesn't exceed the max for IPv4.
13366  */
13367 int
13368 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13369 {
13370 	int len;
13371 
13372 	len = IP_SIMPLE_HDR_LENGTH;
13373 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13374 		ASSERT(ipp->ipp_label_len_v4 != 0);
13375 		/* We need to round up here */
13376 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13377 	}
13378 
13379 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13380 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13381 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13382 		len += ipp->ipp_ipv4_options_len;
13383 	}
13384 	return (len);
13385 }
13386 
13387 /*
13388  * All-purpose routine to build an IPv4 header with options based
13389  * on the abstract ip_pkt_t.
13390  *
13391  * The caller has to set the source and destination address as well as
13392  * ipha_length. The caller has to massage any source route and compensate
13393  * for the ULP pseudo-header checksum due to the source route.
13394  */
13395 void
13396 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13397     uint8_t protocol)
13398 {
13399 	ipha_t	*ipha = (ipha_t *)buf;
13400 	uint8_t *cp;
13401 
13402 	/* Initialize IPv4 header */
13403 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13404 	ipha->ipha_length = 0;	/* Caller will set later */
13405 	ipha->ipha_ident = 0;
13406 	ipha->ipha_fragment_offset_and_flags = 0;
13407 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13408 	ipha->ipha_protocol = protocol;
13409 	ipha->ipha_hdr_checksum = 0;
13410 
13411 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13412 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13413 		ipha->ipha_src = ipp->ipp_addr_v4;
13414 
13415 	cp = (uint8_t *)&ipha[1];
13416 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13417 		ASSERT(ipp->ipp_label_len_v4 != 0);
13418 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13419 		cp += ipp->ipp_label_len_v4;
13420 		/* We need to round up here */
13421 		while ((uintptr_t)cp & 0x3) {
13422 			*cp++ = IPOPT_NOP;
13423 		}
13424 	}
13425 
13426 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13427 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13428 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13429 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13430 		cp += ipp->ipp_ipv4_options_len;
13431 	}
13432 	ipha->ipha_version_and_hdr_length =
13433 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13434 
13435 	ASSERT((int)(cp - buf) == buf_len);
13436 }
13437 
13438 /* Allocate the private structure */
13439 static int
13440 ip_priv_alloc(void **bufp)
13441 {
13442 	void	*buf;
13443 
13444 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13445 		return (ENOMEM);
13446 
13447 	*bufp = buf;
13448 	return (0);
13449 }
13450 
13451 /* Function to delete the private structure */
13452 void
13453 ip_priv_free(void *buf)
13454 {
13455 	ASSERT(buf != NULL);
13456 	kmem_free(buf, sizeof (ip_priv_t));
13457 }
13458 
13459 /*
13460  * The entry point for IPPF processing.
13461  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13462  * routine just returns.
13463  *
13464  * When called, ip_process generates an ipp_packet_t structure
13465  * which holds the state information for this packet and invokes the
13466  * the classifier (via ipp_packet_process). The classification, depending on
13467  * configured filters, results in a list of actions for this packet. Invoking
13468  * an action may cause the packet to be dropped, in which case we return NULL.
13469  * proc indicates the callout position for
13470  * this packet and ill is the interface this packet arrived on or will leave
13471  * on (inbound and outbound resp.).
13472  *
13473  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13474  * on the ill corrsponding to the destination IP address.
13475  */
13476 mblk_t *
13477 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13478 {
13479 	ip_priv_t	*priv;
13480 	ipp_action_id_t	aid;
13481 	int		rc = 0;
13482 	ipp_packet_t	*pp;
13483 
13484 	/* If the classifier is not loaded, return  */
13485 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13486 		return (mp);
13487 	}
13488 
13489 	ASSERT(mp != NULL);
13490 
13491 	/* Allocate the packet structure */
13492 	rc = ipp_packet_alloc(&pp, "ip", aid);
13493 	if (rc != 0)
13494 		goto drop;
13495 
13496 	/* Allocate the private structure */
13497 	rc = ip_priv_alloc((void **)&priv);
13498 	if (rc != 0) {
13499 		ipp_packet_free(pp);
13500 		goto drop;
13501 	}
13502 	priv->proc = proc;
13503 	priv->ill_index = ill_get_upper_ifindex(rill);
13504 
13505 	ipp_packet_set_private(pp, priv, ip_priv_free);
13506 	ipp_packet_set_data(pp, mp);
13507 
13508 	/* Invoke the classifier */
13509 	rc = ipp_packet_process(&pp);
13510 	if (pp != NULL) {
13511 		mp = ipp_packet_get_data(pp);
13512 		ipp_packet_free(pp);
13513 		if (rc != 0)
13514 			goto drop;
13515 		return (mp);
13516 	} else {
13517 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13518 		mp = NULL;
13519 	}
13520 drop:
13521 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13522 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13523 		ip_drop_input("ip_process", mp, ill);
13524 	} else {
13525 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13526 		ip_drop_output("ip_process", mp, ill);
13527 	}
13528 	freemsg(mp);
13529 	return (NULL);
13530 }
13531 
13532 /*
13533  * Propagate a multicast group membership operation (add/drop) on
13534  * all the interfaces crossed by the related multirt routes.
13535  * The call is considered successful if the operation succeeds
13536  * on at least one interface.
13537  *
13538  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13539  * multicast addresses with the ire argument being the first one.
13540  * We walk the bucket to find all the of those.
13541  *
13542  * Common to IPv4 and IPv6.
13543  */
13544 static int
13545 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13546     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13547     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13548     mcast_record_t fmode, const in6_addr_t *v6src)
13549 {
13550 	ire_t		*ire_gw;
13551 	irb_t		*irb;
13552 	int		ifindex;
13553 	int		error = 0;
13554 	int		result;
13555 	ip_stack_t	*ipst = ire->ire_ipst;
13556 	ipaddr_t	group;
13557 	boolean_t	isv6;
13558 	int		match_flags;
13559 
13560 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13561 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13562 		isv6 = B_FALSE;
13563 	} else {
13564 		isv6 = B_TRUE;
13565 	}
13566 
13567 	irb = ire->ire_bucket;
13568 	ASSERT(irb != NULL);
13569 
13570 	result = 0;
13571 	irb_refhold(irb);
13572 	for (; ire != NULL; ire = ire->ire_next) {
13573 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13574 			continue;
13575 
13576 		/* We handle -ifp routes by matching on the ill if set */
13577 		match_flags = MATCH_IRE_TYPE;
13578 		if (ire->ire_ill != NULL)
13579 			match_flags |= MATCH_IRE_ILL;
13580 
13581 		if (isv6) {
13582 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13583 				continue;
13584 
13585 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13586 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13587 			    match_flags, 0, ipst, NULL);
13588 		} else {
13589 			if (ire->ire_addr != group)
13590 				continue;
13591 
13592 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13593 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13594 			    match_flags, 0, ipst, NULL);
13595 		}
13596 		/* No interface route exists for the gateway; skip this ire. */
13597 		if (ire_gw == NULL)
13598 			continue;
13599 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13600 			ire_refrele(ire_gw);
13601 			continue;
13602 		}
13603 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13604 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13605 
13606 		/*
13607 		 * The operation is considered a success if
13608 		 * it succeeds at least once on any one interface.
13609 		 */
13610 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13611 		    fmode, v6src);
13612 		if (error == 0)
13613 			result = CGTP_MCAST_SUCCESS;
13614 
13615 		ire_refrele(ire_gw);
13616 	}
13617 	irb_refrele(irb);
13618 	/*
13619 	 * Consider the call as successful if we succeeded on at least
13620 	 * one interface. Otherwise, return the last encountered error.
13621 	 */
13622 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13623 }
13624 
13625 /*
13626  * Return the expected CGTP hooks version number.
13627  */
13628 int
13629 ip_cgtp_filter_supported(void)
13630 {
13631 	return (ip_cgtp_filter_rev);
13632 }
13633 
13634 /*
13635  * CGTP hooks can be registered by invoking this function.
13636  * Checks that the version number matches.
13637  */
13638 int
13639 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13640 {
13641 	netstack_t *ns;
13642 	ip_stack_t *ipst;
13643 
13644 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13645 		return (ENOTSUP);
13646 
13647 	ns = netstack_find_by_stackid(stackid);
13648 	if (ns == NULL)
13649 		return (EINVAL);
13650 	ipst = ns->netstack_ip;
13651 	ASSERT(ipst != NULL);
13652 
13653 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13654 		netstack_rele(ns);
13655 		return (EALREADY);
13656 	}
13657 
13658 	ipst->ips_ip_cgtp_filter_ops = ops;
13659 
13660 	ill_set_inputfn_all(ipst);
13661 
13662 	netstack_rele(ns);
13663 	return (0);
13664 }
13665 
13666 /*
13667  * CGTP hooks can be unregistered by invoking this function.
13668  * Returns ENXIO if there was no registration.
13669  * Returns EBUSY if the ndd variable has not been turned off.
13670  */
13671 int
13672 ip_cgtp_filter_unregister(netstackid_t stackid)
13673 {
13674 	netstack_t *ns;
13675 	ip_stack_t *ipst;
13676 
13677 	ns = netstack_find_by_stackid(stackid);
13678 	if (ns == NULL)
13679 		return (EINVAL);
13680 	ipst = ns->netstack_ip;
13681 	ASSERT(ipst != NULL);
13682 
13683 	if (ipst->ips_ip_cgtp_filter) {
13684 		netstack_rele(ns);
13685 		return (EBUSY);
13686 	}
13687 
13688 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13689 		netstack_rele(ns);
13690 		return (ENXIO);
13691 	}
13692 	ipst->ips_ip_cgtp_filter_ops = NULL;
13693 
13694 	ill_set_inputfn_all(ipst);
13695 
13696 	netstack_rele(ns);
13697 	return (0);
13698 }
13699 
13700 /*
13701  * Check whether there is a CGTP filter registration.
13702  * Returns non-zero if there is a registration, otherwise returns zero.
13703  * Note: returns zero if bad stackid.
13704  */
13705 int
13706 ip_cgtp_filter_is_registered(netstackid_t stackid)
13707 {
13708 	netstack_t *ns;
13709 	ip_stack_t *ipst;
13710 	int ret;
13711 
13712 	ns = netstack_find_by_stackid(stackid);
13713 	if (ns == NULL)
13714 		return (0);
13715 	ipst = ns->netstack_ip;
13716 	ASSERT(ipst != NULL);
13717 
13718 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13719 		ret = 1;
13720 	else
13721 		ret = 0;
13722 
13723 	netstack_rele(ns);
13724 	return (ret);
13725 }
13726 
13727 static int
13728 ip_squeue_switch(int val)
13729 {
13730 	int rval;
13731 
13732 	switch (val) {
13733 	case IP_SQUEUE_ENTER_NODRAIN:
13734 		rval = SQ_NODRAIN;
13735 		break;
13736 	case IP_SQUEUE_ENTER:
13737 		rval = SQ_PROCESS;
13738 		break;
13739 	case IP_SQUEUE_FILL:
13740 	default:
13741 		rval = SQ_FILL;
13742 		break;
13743 	}
13744 	return (rval);
13745 }
13746 
13747 static void *
13748 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13749 {
13750 	kstat_t *ksp;
13751 
13752 	ip_stat_t template = {
13753 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
13754 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
13755 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
13756 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13757 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13758 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13759 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13760 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13761 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13762 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13763 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13764 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13765 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13766 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13767 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13768 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13769 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13770 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13771 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13772 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13773 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13774 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13775 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13776 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13777 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13778 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13779 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13780 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13781 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13782 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13783 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
13784 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
13785 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
13786 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
13787 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
13788 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
13789 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
13790 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
13791 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
13792 	};
13793 
13794 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13795 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13796 	    KSTAT_FLAG_VIRTUAL, stackid);
13797 
13798 	if (ksp == NULL)
13799 		return (NULL);
13800 
13801 	bcopy(&template, ip_statisticsp, sizeof (template));
13802 	ksp->ks_data = (void *)ip_statisticsp;
13803 	ksp->ks_private = (void *)(uintptr_t)stackid;
13804 
13805 	kstat_install(ksp);
13806 	return (ksp);
13807 }
13808 
13809 static void
13810 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13811 {
13812 	if (ksp != NULL) {
13813 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13814 		kstat_delete_netstack(ksp, stackid);
13815 	}
13816 }
13817 
13818 static void *
13819 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13820 {
13821 	kstat_t	*ksp;
13822 
13823 	ip_named_kstat_t template = {
13824 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
13825 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
13826 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
13827 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
13828 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
13829 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
13830 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
13831 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
13832 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
13833 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
13834 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
13835 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
13836 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
13837 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
13838 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
13839 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
13840 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
13841 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
13842 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
13843 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
13844 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
13845 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
13846 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
13847 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
13848 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
13849 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
13850 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
13851 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
13852 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
13853 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
13854 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
13855 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
13856 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
13857 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
13858 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
13859 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
13860 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
13861 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
13862 	};
13863 
13864 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
13865 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
13866 	if (ksp == NULL || ksp->ks_data == NULL)
13867 		return (NULL);
13868 
13869 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
13870 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
13871 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
13872 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
13873 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
13874 
13875 	template.netToMediaEntrySize.value.i32 =
13876 	    sizeof (mib2_ipNetToMediaEntry_t);
13877 
13878 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
13879 
13880 	bcopy(&template, ksp->ks_data, sizeof (template));
13881 	ksp->ks_update = ip_kstat_update;
13882 	ksp->ks_private = (void *)(uintptr_t)stackid;
13883 
13884 	kstat_install(ksp);
13885 	return (ksp);
13886 }
13887 
13888 static void
13889 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
13890 {
13891 	if (ksp != NULL) {
13892 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13893 		kstat_delete_netstack(ksp, stackid);
13894 	}
13895 }
13896 
13897 static int
13898 ip_kstat_update(kstat_t *kp, int rw)
13899 {
13900 	ip_named_kstat_t *ipkp;
13901 	mib2_ipIfStatsEntry_t ipmib;
13902 	ill_walk_context_t ctx;
13903 	ill_t *ill;
13904 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
13905 	netstack_t	*ns;
13906 	ip_stack_t	*ipst;
13907 
13908 	if (kp == NULL || kp->ks_data == NULL)
13909 		return (EIO);
13910 
13911 	if (rw == KSTAT_WRITE)
13912 		return (EACCES);
13913 
13914 	ns = netstack_find_by_stackid(stackid);
13915 	if (ns == NULL)
13916 		return (-1);
13917 	ipst = ns->netstack_ip;
13918 	if (ipst == NULL) {
13919 		netstack_rele(ns);
13920 		return (-1);
13921 	}
13922 	ipkp = (ip_named_kstat_t *)kp->ks_data;
13923 
13924 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
13925 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
13926 	ill = ILL_START_WALK_V4(&ctx, ipst);
13927 	for (; ill != NULL; ill = ill_next(&ctx, ill))
13928 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
13929 	rw_exit(&ipst->ips_ill_g_lock);
13930 
13931 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
13932 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
13933 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
13934 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
13935 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
13936 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
13937 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
13938 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
13939 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
13940 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
13941 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
13942 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
13943 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
13944 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
13945 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
13946 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
13947 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
13948 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
13949 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
13950 
13951 	ipkp->routingDiscards.value.ui32 =	0;
13952 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
13953 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
13954 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
13955 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
13956 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
13957 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
13958 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
13959 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
13960 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
13961 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
13962 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
13963 
13964 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
13965 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
13966 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
13967 
13968 	netstack_rele(ns);
13969 
13970 	return (0);
13971 }
13972 
13973 static void *
13974 icmp_kstat_init(netstackid_t stackid)
13975 {
13976 	kstat_t	*ksp;
13977 
13978 	icmp_named_kstat_t template = {
13979 		{ "inMsgs",		KSTAT_DATA_UINT32 },
13980 		{ "inErrors",		KSTAT_DATA_UINT32 },
13981 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
13982 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
13983 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
13984 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
13985 		{ "inRedirects",	KSTAT_DATA_UINT32 },
13986 		{ "inEchos",		KSTAT_DATA_UINT32 },
13987 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
13988 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
13989 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
13990 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
13991 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
13992 		{ "outMsgs",		KSTAT_DATA_UINT32 },
13993 		{ "outErrors",		KSTAT_DATA_UINT32 },
13994 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
13995 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
13996 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
13997 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
13998 		{ "outRedirects",	KSTAT_DATA_UINT32 },
13999 		{ "outEchos",		KSTAT_DATA_UINT32 },
14000 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14001 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14002 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14003 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14004 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14005 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14006 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14007 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14008 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14009 		{ "outDrops",		KSTAT_DATA_UINT32 },
14010 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14011 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14012 	};
14013 
14014 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14015 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14016 	if (ksp == NULL || ksp->ks_data == NULL)
14017 		return (NULL);
14018 
14019 	bcopy(&template, ksp->ks_data, sizeof (template));
14020 
14021 	ksp->ks_update = icmp_kstat_update;
14022 	ksp->ks_private = (void *)(uintptr_t)stackid;
14023 
14024 	kstat_install(ksp);
14025 	return (ksp);
14026 }
14027 
14028 static void
14029 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14030 {
14031 	if (ksp != NULL) {
14032 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14033 		kstat_delete_netstack(ksp, stackid);
14034 	}
14035 }
14036 
14037 static int
14038 icmp_kstat_update(kstat_t *kp, int rw)
14039 {
14040 	icmp_named_kstat_t *icmpkp;
14041 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14042 	netstack_t	*ns;
14043 	ip_stack_t	*ipst;
14044 
14045 	if ((kp == NULL) || (kp->ks_data == NULL))
14046 		return (EIO);
14047 
14048 	if (rw == KSTAT_WRITE)
14049 		return (EACCES);
14050 
14051 	ns = netstack_find_by_stackid(stackid);
14052 	if (ns == NULL)
14053 		return (-1);
14054 	ipst = ns->netstack_ip;
14055 	if (ipst == NULL) {
14056 		netstack_rele(ns);
14057 		return (-1);
14058 	}
14059 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14060 
14061 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14062 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14063 	icmpkp->inDestUnreachs.value.ui32 =
14064 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14065 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14066 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14067 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14068 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14069 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14070 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14071 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14072 	icmpkp->inTimestampReps.value.ui32 =
14073 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14074 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14075 	icmpkp->inAddrMaskReps.value.ui32 =
14076 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14077 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14078 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14079 	icmpkp->outDestUnreachs.value.ui32 =
14080 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14081 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14082 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14083 	icmpkp->outSrcQuenchs.value.ui32 =
14084 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14085 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14086 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14087 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14088 	icmpkp->outTimestamps.value.ui32 =
14089 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14090 	icmpkp->outTimestampReps.value.ui32 =
14091 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14092 	icmpkp->outAddrMasks.value.ui32 =
14093 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14094 	icmpkp->outAddrMaskReps.value.ui32 =
14095 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14096 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14097 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14098 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14099 	icmpkp->outFragNeeded.value.ui32 =
14100 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14101 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14102 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14103 	icmpkp->inBadRedirects.value.ui32 =
14104 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14105 
14106 	netstack_rele(ns);
14107 	return (0);
14108 }
14109 
14110 /*
14111  * This is the fanout function for raw socket opened for SCTP.  Note
14112  * that it is called after SCTP checks that there is no socket which
14113  * wants a packet.  Then before SCTP handles this out of the blue packet,
14114  * this function is called to see if there is any raw socket for SCTP.
14115  * If there is and it is bound to the correct address, the packet will
14116  * be sent to that socket.  Note that only one raw socket can be bound to
14117  * a port.  This is assured in ipcl_sctp_hash_insert();
14118  */
14119 void
14120 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14121     ip_recv_attr_t *ira)
14122 {
14123 	conn_t		*connp;
14124 	queue_t		*rq;
14125 	boolean_t	secure;
14126 	ill_t		*ill = ira->ira_ill;
14127 	ip_stack_t	*ipst = ill->ill_ipst;
14128 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14129 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14130 	iaflags_t	iraflags = ira->ira_flags;
14131 	ill_t		*rill = ira->ira_rill;
14132 
14133 	secure = iraflags & IRAF_IPSEC_SECURE;
14134 
14135 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14136 	    ira, ipst);
14137 	if (connp == NULL) {
14138 		/*
14139 		 * Although raw sctp is not summed, OOB chunks must be.
14140 		 * Drop the packet here if the sctp checksum failed.
14141 		 */
14142 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14143 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
14144 			freemsg(mp);
14145 			return;
14146 		}
14147 		ira->ira_ill = ira->ira_rill = NULL;
14148 		sctp_ootb_input(mp, ira, ipst);
14149 		ira->ira_ill = ill;
14150 		ira->ira_rill = rill;
14151 		return;
14152 	}
14153 	rq = connp->conn_rq;
14154 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14155 		CONN_DEC_REF(connp);
14156 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14157 		freemsg(mp);
14158 		return;
14159 	}
14160 	if (((iraflags & IRAF_IS_IPV4) ?
14161 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14162 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14163 	    secure) {
14164 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14165 		    ip6h, ira);
14166 		if (mp == NULL) {
14167 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14168 			/* Note that mp is NULL */
14169 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14170 			CONN_DEC_REF(connp);
14171 			return;
14172 		}
14173 	}
14174 
14175 	if (iraflags & IRAF_ICMP_ERROR) {
14176 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14177 	} else {
14178 		ill_t *rill = ira->ira_rill;
14179 
14180 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14181 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14182 		ira->ira_ill = ira->ira_rill = NULL;
14183 		(connp->conn_recv)(connp, mp, NULL, ira);
14184 		ira->ira_ill = ill;
14185 		ira->ira_rill = rill;
14186 	}
14187 	CONN_DEC_REF(connp);
14188 }
14189 
14190 /*
14191  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14192  * header before the ip payload.
14193  */
14194 static void
14195 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14196 {
14197 	int len = (mp->b_wptr - mp->b_rptr);
14198 	mblk_t *ip_mp;
14199 
14200 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14201 	if (is_fp_mp || len != fp_mp_len) {
14202 		if (len > fp_mp_len) {
14203 			/*
14204 			 * fastpath header and ip header in the first mblk
14205 			 */
14206 			mp->b_rptr += fp_mp_len;
14207 		} else {
14208 			/*
14209 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14210 			 * attach the fastpath header before ip header.
14211 			 */
14212 			ip_mp = mp->b_cont;
14213 			freeb(mp);
14214 			mp = ip_mp;
14215 			mp->b_rptr += (fp_mp_len - len);
14216 		}
14217 	} else {
14218 		ip_mp = mp->b_cont;
14219 		freeb(mp);
14220 		mp = ip_mp;
14221 	}
14222 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14223 	freemsg(mp);
14224 }
14225 
14226 /*
14227  * Normal post fragmentation function.
14228  *
14229  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14230  * using the same state machine.
14231  *
14232  * We return an error on failure. In particular we return EWOULDBLOCK
14233  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14234  * (currently by canputnext failure resulting in backenabling from GLD.)
14235  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14236  * indication that they can flow control until ip_wsrv() tells then to restart.
14237  *
14238  * If the nce passed by caller is incomplete, this function
14239  * queues the packet and if necessary, sends ARP request and bails.
14240  * If the Neighbor Cache passed is fully resolved, we simply prepend
14241  * the link-layer header to the packet, do ipsec hw acceleration
14242  * work if necessary, and send the packet out on the wire.
14243  */
14244 /* ARGSUSED6 */
14245 int
14246 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14247     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14248 {
14249 	queue_t		*wq;
14250 	ill_t		*ill = nce->nce_ill;
14251 	ip_stack_t	*ipst = ill->ill_ipst;
14252 	uint64_t	delta;
14253 	boolean_t	isv6 = ill->ill_isv6;
14254 	boolean_t	fp_mp;
14255 	ncec_t		*ncec = nce->nce_common;
14256 	int64_t		now = LBOLT_FASTPATH64;
14257 	boolean_t	is_probe;
14258 
14259 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14260 
14261 	ASSERT(mp != NULL);
14262 	ASSERT(mp->b_datap->db_type == M_DATA);
14263 	ASSERT(pkt_len == msgdsize(mp));
14264 
14265 	/*
14266 	 * If we have already been here and are coming back after ARP/ND.
14267 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14268 	 * in that case since they have seen the packet when it came here
14269 	 * the first time.
14270 	 */
14271 	if (ixaflags & IXAF_NO_TRACE)
14272 		goto sendit;
14273 
14274 	if (ixaflags & IXAF_IS_IPV4) {
14275 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14276 
14277 		ASSERT(!isv6);
14278 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14279 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14280 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14281 			int	error;
14282 
14283 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14284 			    ipst->ips_ipv4firewall_physical_out,
14285 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14286 			DTRACE_PROBE1(ip4__physical__out__end,
14287 			    mblk_t *, mp);
14288 			if (mp == NULL)
14289 				return (error);
14290 
14291 			/* The length could have changed */
14292 			pkt_len = msgdsize(mp);
14293 		}
14294 		if (ipst->ips_ip4_observe.he_interested) {
14295 			/*
14296 			 * Note that for TX the zoneid is the sending
14297 			 * zone, whether or not MLP is in play.
14298 			 * Since the szone argument is the IP zoneid (i.e.,
14299 			 * zero for exclusive-IP zones) and ipobs wants
14300 			 * the system zoneid, we map it here.
14301 			 */
14302 			szone = IP_REAL_ZONEID(szone, ipst);
14303 
14304 			/*
14305 			 * On the outbound path the destination zone will be
14306 			 * unknown as we're sending this packet out on the
14307 			 * wire.
14308 			 */
14309 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14310 			    ill, ipst);
14311 		}
14312 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14313 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14314 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14315 	} else {
14316 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14317 
14318 		ASSERT(isv6);
14319 		ASSERT(pkt_len ==
14320 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14321 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14322 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14323 			int	error;
14324 
14325 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14326 			    ipst->ips_ipv6firewall_physical_out,
14327 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14328 			DTRACE_PROBE1(ip6__physical__out__end,
14329 			    mblk_t *, mp);
14330 			if (mp == NULL)
14331 				return (error);
14332 
14333 			/* The length could have changed */
14334 			pkt_len = msgdsize(mp);
14335 		}
14336 		if (ipst->ips_ip6_observe.he_interested) {
14337 			/* See above */
14338 			szone = IP_REAL_ZONEID(szone, ipst);
14339 
14340 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14341 			    ill, ipst);
14342 		}
14343 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14344 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14345 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14346 	}
14347 
14348 sendit:
14349 	/*
14350 	 * We check the state without a lock because the state can never
14351 	 * move "backwards" to initial or incomplete.
14352 	 */
14353 	switch (ncec->ncec_state) {
14354 	case ND_REACHABLE:
14355 	case ND_STALE:
14356 	case ND_DELAY:
14357 	case ND_PROBE:
14358 		mp = ip_xmit_attach_llhdr(mp, nce);
14359 		if (mp == NULL) {
14360 			/*
14361 			 * ip_xmit_attach_llhdr has increased
14362 			 * ipIfStatsOutDiscards and called ip_drop_output()
14363 			 */
14364 			return (ENOBUFS);
14365 		}
14366 		/*
14367 		 * check if nce_fastpath completed and we tagged on a
14368 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14369 		 */
14370 		fp_mp = (mp->b_datap->db_type == M_DATA);
14371 
14372 		if (fp_mp &&
14373 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14374 			ill_dld_direct_t *idd;
14375 
14376 			idd = &ill->ill_dld_capab->idc_direct;
14377 			/*
14378 			 * Send the packet directly to DLD, where it
14379 			 * may be queued depending on the availability
14380 			 * of transmit resources at the media layer.
14381 			 * Return value should be taken into
14382 			 * account and flow control the TCP.
14383 			 */
14384 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14385 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14386 			    pkt_len);
14387 
14388 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14389 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14390 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14391 			} else {
14392 				uintptr_t cookie;
14393 
14394 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14395 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14396 					if (ixacookie != NULL)
14397 						*ixacookie = cookie;
14398 					return (EWOULDBLOCK);
14399 				}
14400 			}
14401 		} else {
14402 			wq = ill->ill_wq;
14403 
14404 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14405 			    !canputnext(wq)) {
14406 				if (ixacookie != NULL)
14407 					*ixacookie = 0;
14408 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14409 				    nce->nce_fp_mp != NULL ?
14410 				    MBLKL(nce->nce_fp_mp) : 0);
14411 				return (EWOULDBLOCK);
14412 			}
14413 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14414 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14415 			    pkt_len);
14416 			putnext(wq, mp);
14417 		}
14418 
14419 		/*
14420 		 * The rest of this function implements Neighbor Unreachability
14421 		 * detection. Determine if the ncec is eligible for NUD.
14422 		 */
14423 		if (ncec->ncec_flags & NCE_F_NONUD)
14424 			return (0);
14425 
14426 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14427 
14428 		/*
14429 		 * Check for upper layer advice
14430 		 */
14431 		if (ixaflags & IXAF_REACH_CONF) {
14432 			timeout_id_t tid;
14433 
14434 			/*
14435 			 * It should be o.k. to check the state without
14436 			 * a lock here, at most we lose an advice.
14437 			 */
14438 			ncec->ncec_last = TICK_TO_MSEC(now);
14439 			if (ncec->ncec_state != ND_REACHABLE) {
14440 				mutex_enter(&ncec->ncec_lock);
14441 				ncec->ncec_state = ND_REACHABLE;
14442 				tid = ncec->ncec_timeout_id;
14443 				ncec->ncec_timeout_id = 0;
14444 				mutex_exit(&ncec->ncec_lock);
14445 				(void) untimeout(tid);
14446 				if (ip_debug > 2) {
14447 					/* ip1dbg */
14448 					pr_addr_dbg("ip_xmit: state"
14449 					    " for %s changed to"
14450 					    " REACHABLE\n", AF_INET6,
14451 					    &ncec->ncec_addr);
14452 				}
14453 			}
14454 			return (0);
14455 		}
14456 
14457 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14458 		ip1dbg(("ip_xmit: delta = %" PRId64
14459 		    " ill_reachable_time = %d \n", delta,
14460 		    ill->ill_reachable_time));
14461 		if (delta > (uint64_t)ill->ill_reachable_time) {
14462 			mutex_enter(&ncec->ncec_lock);
14463 			switch (ncec->ncec_state) {
14464 			case ND_REACHABLE:
14465 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14466 				/* FALLTHROUGH */
14467 			case ND_STALE:
14468 				/*
14469 				 * ND_REACHABLE is identical to
14470 				 * ND_STALE in this specific case. If
14471 				 * reachable time has expired for this
14472 				 * neighbor (delta is greater than
14473 				 * reachable time), conceptually, the
14474 				 * neighbor cache is no longer in
14475 				 * REACHABLE state, but already in
14476 				 * STALE state.  So the correct
14477 				 * transition here is to ND_DELAY.
14478 				 */
14479 				ncec->ncec_state = ND_DELAY;
14480 				mutex_exit(&ncec->ncec_lock);
14481 				nce_restart_timer(ncec,
14482 				    ipst->ips_delay_first_probe_time);
14483 				if (ip_debug > 3) {
14484 					/* ip2dbg */
14485 					pr_addr_dbg("ip_xmit: state"
14486 					    " for %s changed to"
14487 					    " DELAY\n", AF_INET6,
14488 					    &ncec->ncec_addr);
14489 				}
14490 				break;
14491 			case ND_DELAY:
14492 			case ND_PROBE:
14493 				mutex_exit(&ncec->ncec_lock);
14494 				/* Timers have already started */
14495 				break;
14496 			case ND_UNREACHABLE:
14497 				/*
14498 				 * nce_timer has detected that this ncec
14499 				 * is unreachable and initiated deleting
14500 				 * this ncec.
14501 				 * This is a harmless race where we found the
14502 				 * ncec before it was deleted and have
14503 				 * just sent out a packet using this
14504 				 * unreachable ncec.
14505 				 */
14506 				mutex_exit(&ncec->ncec_lock);
14507 				break;
14508 			default:
14509 				ASSERT(0);
14510 				mutex_exit(&ncec->ncec_lock);
14511 			}
14512 		}
14513 		return (0);
14514 
14515 	case ND_INCOMPLETE:
14516 		/*
14517 		 * the state could have changed since we didn't hold the lock.
14518 		 * Re-verify state under lock.
14519 		 */
14520 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14521 		mutex_enter(&ncec->ncec_lock);
14522 		if (NCE_ISREACHABLE(ncec)) {
14523 			mutex_exit(&ncec->ncec_lock);
14524 			goto sendit;
14525 		}
14526 		/* queue the packet */
14527 		nce_queue_mp(ncec, mp, is_probe);
14528 		mutex_exit(&ncec->ncec_lock);
14529 		DTRACE_PROBE2(ip__xmit__incomplete,
14530 		    (ncec_t *), ncec, (mblk_t *), mp);
14531 		return (0);
14532 
14533 	case ND_INITIAL:
14534 		/*
14535 		 * State could have changed since we didn't hold the lock, so
14536 		 * re-verify state.
14537 		 */
14538 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14539 		mutex_enter(&ncec->ncec_lock);
14540 		if (NCE_ISREACHABLE(ncec))  {
14541 			mutex_exit(&ncec->ncec_lock);
14542 			goto sendit;
14543 		}
14544 		nce_queue_mp(ncec, mp, is_probe);
14545 		if (ncec->ncec_state == ND_INITIAL) {
14546 			ncec->ncec_state = ND_INCOMPLETE;
14547 			mutex_exit(&ncec->ncec_lock);
14548 			/*
14549 			 * figure out the source we want to use
14550 			 * and resolve it.
14551 			 */
14552 			ip_ndp_resolve(ncec);
14553 		} else  {
14554 			mutex_exit(&ncec->ncec_lock);
14555 		}
14556 		return (0);
14557 
14558 	case ND_UNREACHABLE:
14559 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14560 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14561 		    mp, ill);
14562 		freemsg(mp);
14563 		return (0);
14564 
14565 	default:
14566 		ASSERT(0);
14567 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14568 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14569 		    mp, ill);
14570 		freemsg(mp);
14571 		return (ENETUNREACH);
14572 	}
14573 }
14574 
14575 /*
14576  * Return B_TRUE if the buffers differ in length or content.
14577  * This is used for comparing extension header buffers.
14578  * Note that an extension header would be declared different
14579  * even if all that changed was the next header value in that header i.e.
14580  * what really changed is the next extension header.
14581  */
14582 boolean_t
14583 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14584     uint_t blen)
14585 {
14586 	if (!b_valid)
14587 		blen = 0;
14588 
14589 	if (alen != blen)
14590 		return (B_TRUE);
14591 	if (alen == 0)
14592 		return (B_FALSE);	/* Both zero length */
14593 	return (bcmp(abuf, bbuf, alen));
14594 }
14595 
14596 /*
14597  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14598  * Return B_FALSE if memory allocation fails - don't change any state!
14599  */
14600 boolean_t
14601 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14602     const void *src, uint_t srclen)
14603 {
14604 	void *dst;
14605 
14606 	if (!src_valid)
14607 		srclen = 0;
14608 
14609 	ASSERT(*dstlenp == 0);
14610 	if (src != NULL && srclen != 0) {
14611 		dst = mi_alloc(srclen, BPRI_MED);
14612 		if (dst == NULL)
14613 			return (B_FALSE);
14614 	} else {
14615 		dst = NULL;
14616 	}
14617 	if (*dstp != NULL)
14618 		mi_free(*dstp);
14619 	*dstp = dst;
14620 	*dstlenp = dst == NULL ? 0 : srclen;
14621 	return (B_TRUE);
14622 }
14623 
14624 /*
14625  * Replace what is in *dst, *dstlen with the source.
14626  * Assumes ip_allocbuf has already been called.
14627  */
14628 void
14629 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14630     const void *src, uint_t srclen)
14631 {
14632 	if (!src_valid)
14633 		srclen = 0;
14634 
14635 	ASSERT(*dstlenp == srclen);
14636 	if (src != NULL && srclen != 0)
14637 		bcopy(src, *dstp, srclen);
14638 }
14639 
14640 /*
14641  * Free the storage pointed to by the members of an ip_pkt_t.
14642  */
14643 void
14644 ip_pkt_free(ip_pkt_t *ipp)
14645 {
14646 	uint_t	fields = ipp->ipp_fields;
14647 
14648 	if (fields & IPPF_HOPOPTS) {
14649 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14650 		ipp->ipp_hopopts = NULL;
14651 		ipp->ipp_hopoptslen = 0;
14652 	}
14653 	if (fields & IPPF_RTHDRDSTOPTS) {
14654 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14655 		ipp->ipp_rthdrdstopts = NULL;
14656 		ipp->ipp_rthdrdstoptslen = 0;
14657 	}
14658 	if (fields & IPPF_DSTOPTS) {
14659 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14660 		ipp->ipp_dstopts = NULL;
14661 		ipp->ipp_dstoptslen = 0;
14662 	}
14663 	if (fields & IPPF_RTHDR) {
14664 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14665 		ipp->ipp_rthdr = NULL;
14666 		ipp->ipp_rthdrlen = 0;
14667 	}
14668 	if (fields & IPPF_IPV4_OPTIONS) {
14669 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14670 		ipp->ipp_ipv4_options = NULL;
14671 		ipp->ipp_ipv4_options_len = 0;
14672 	}
14673 	if (fields & IPPF_LABEL_V4) {
14674 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14675 		ipp->ipp_label_v4 = NULL;
14676 		ipp->ipp_label_len_v4 = 0;
14677 	}
14678 	if (fields & IPPF_LABEL_V6) {
14679 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14680 		ipp->ipp_label_v6 = NULL;
14681 		ipp->ipp_label_len_v6 = 0;
14682 	}
14683 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14684 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14685 }
14686 
14687 /*
14688  * Copy from src to dst and allocate as needed.
14689  * Returns zero or ENOMEM.
14690  *
14691  * The caller must initialize dst to zero.
14692  */
14693 int
14694 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14695 {
14696 	uint_t	fields = src->ipp_fields;
14697 
14698 	/* Start with fields that don't require memory allocation */
14699 	dst->ipp_fields = fields &
14700 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14701 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14702 
14703 	dst->ipp_addr = src->ipp_addr;
14704 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14705 	dst->ipp_hoplimit = src->ipp_hoplimit;
14706 	dst->ipp_tclass = src->ipp_tclass;
14707 	dst->ipp_type_of_service = src->ipp_type_of_service;
14708 
14709 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14710 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14711 		return (0);
14712 
14713 	if (fields & IPPF_HOPOPTS) {
14714 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14715 		if (dst->ipp_hopopts == NULL) {
14716 			ip_pkt_free(dst);
14717 			return (ENOMEM);
14718 		}
14719 		dst->ipp_fields |= IPPF_HOPOPTS;
14720 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14721 		    src->ipp_hopoptslen);
14722 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14723 	}
14724 	if (fields & IPPF_RTHDRDSTOPTS) {
14725 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14726 		    kmflag);
14727 		if (dst->ipp_rthdrdstopts == NULL) {
14728 			ip_pkt_free(dst);
14729 			return (ENOMEM);
14730 		}
14731 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14732 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14733 		    src->ipp_rthdrdstoptslen);
14734 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14735 	}
14736 	if (fields & IPPF_DSTOPTS) {
14737 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14738 		if (dst->ipp_dstopts == NULL) {
14739 			ip_pkt_free(dst);
14740 			return (ENOMEM);
14741 		}
14742 		dst->ipp_fields |= IPPF_DSTOPTS;
14743 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14744 		    src->ipp_dstoptslen);
14745 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14746 	}
14747 	if (fields & IPPF_RTHDR) {
14748 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14749 		if (dst->ipp_rthdr == NULL) {
14750 			ip_pkt_free(dst);
14751 			return (ENOMEM);
14752 		}
14753 		dst->ipp_fields |= IPPF_RTHDR;
14754 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14755 		    src->ipp_rthdrlen);
14756 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14757 	}
14758 	if (fields & IPPF_IPV4_OPTIONS) {
14759 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14760 		    kmflag);
14761 		if (dst->ipp_ipv4_options == NULL) {
14762 			ip_pkt_free(dst);
14763 			return (ENOMEM);
14764 		}
14765 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14766 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14767 		    src->ipp_ipv4_options_len);
14768 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14769 	}
14770 	if (fields & IPPF_LABEL_V4) {
14771 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14772 		if (dst->ipp_label_v4 == NULL) {
14773 			ip_pkt_free(dst);
14774 			return (ENOMEM);
14775 		}
14776 		dst->ipp_fields |= IPPF_LABEL_V4;
14777 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14778 		    src->ipp_label_len_v4);
14779 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14780 	}
14781 	if (fields & IPPF_LABEL_V6) {
14782 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14783 		if (dst->ipp_label_v6 == NULL) {
14784 			ip_pkt_free(dst);
14785 			return (ENOMEM);
14786 		}
14787 		dst->ipp_fields |= IPPF_LABEL_V6;
14788 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14789 		    src->ipp_label_len_v6);
14790 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14791 	}
14792 	if (fields & IPPF_FRAGHDR) {
14793 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14794 		if (dst->ipp_fraghdr == NULL) {
14795 			ip_pkt_free(dst);
14796 			return (ENOMEM);
14797 		}
14798 		dst->ipp_fields |= IPPF_FRAGHDR;
14799 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14800 		    src->ipp_fraghdrlen);
14801 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14802 	}
14803 	return (0);
14804 }
14805 
14806 /*
14807  * Returns INADDR_ANY if no source route
14808  */
14809 ipaddr_t
14810 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14811 {
14812 	ipaddr_t	nexthop = INADDR_ANY;
14813 	ipoptp_t	opts;
14814 	uchar_t		*opt;
14815 	uint8_t		optval;
14816 	uint8_t		optlen;
14817 	uint32_t	totallen;
14818 
14819 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14820 		return (INADDR_ANY);
14821 
14822 	totallen = ipp->ipp_ipv4_options_len;
14823 	if (totallen & 0x3)
14824 		return (INADDR_ANY);
14825 
14826 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14827 	    optval != IPOPT_EOL;
14828 	    optval = ipoptp_next(&opts)) {
14829 		opt = opts.ipoptp_cur;
14830 		switch (optval) {
14831 			uint8_t off;
14832 		case IPOPT_SSRR:
14833 		case IPOPT_LSRR:
14834 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14835 				break;
14836 			}
14837 			optlen = opts.ipoptp_len;
14838 			off = opt[IPOPT_OFFSET];
14839 			off--;
14840 			if (optlen < IP_ADDR_LEN ||
14841 			    off > optlen - IP_ADDR_LEN) {
14842 				/* End of source route */
14843 				break;
14844 			}
14845 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
14846 			if (nexthop == htonl(INADDR_LOOPBACK)) {
14847 				/* Ignore */
14848 				nexthop = INADDR_ANY;
14849 				break;
14850 			}
14851 			break;
14852 		}
14853 	}
14854 	return (nexthop);
14855 }
14856 
14857 /*
14858  * Reverse a source route.
14859  */
14860 void
14861 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
14862 {
14863 	ipaddr_t	tmp;
14864 	ipoptp_t	opts;
14865 	uchar_t		*opt;
14866 	uint8_t		optval;
14867 	uint32_t	totallen;
14868 
14869 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14870 		return;
14871 
14872 	totallen = ipp->ipp_ipv4_options_len;
14873 	if (totallen & 0x3)
14874 		return;
14875 
14876 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14877 	    optval != IPOPT_EOL;
14878 	    optval = ipoptp_next(&opts)) {
14879 		uint8_t off1, off2;
14880 
14881 		opt = opts.ipoptp_cur;
14882 		switch (optval) {
14883 		case IPOPT_SSRR:
14884 		case IPOPT_LSRR:
14885 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14886 				break;
14887 			}
14888 			off1 = IPOPT_MINOFF_SR - 1;
14889 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
14890 			while (off2 > off1) {
14891 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
14892 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
14893 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
14894 				off2 -= IP_ADDR_LEN;
14895 				off1 += IP_ADDR_LEN;
14896 			}
14897 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
14898 			break;
14899 		}
14900 	}
14901 }
14902 
14903 /*
14904  * Returns NULL if no routing header
14905  */
14906 in6_addr_t *
14907 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
14908 {
14909 	in6_addr_t	*nexthop = NULL;
14910 	ip6_rthdr0_t	*rthdr;
14911 
14912 	if (!(ipp->ipp_fields & IPPF_RTHDR))
14913 		return (NULL);
14914 
14915 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
14916 	if (rthdr->ip6r0_segleft == 0)
14917 		return (NULL);
14918 
14919 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
14920 	return (nexthop);
14921 }
14922 
14923 zoneid_t
14924 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
14925     zoneid_t lookup_zoneid)
14926 {
14927 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
14928 	ire_t		*ire;
14929 	int		ire_flags = MATCH_IRE_TYPE;
14930 	zoneid_t	zoneid = ALL_ZONES;
14931 
14932 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
14933 		return (ALL_ZONES);
14934 
14935 	if (lookup_zoneid != ALL_ZONES)
14936 		ire_flags |= MATCH_IRE_ZONEONLY;
14937 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
14938 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
14939 	if (ire != NULL) {
14940 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
14941 		ire_refrele(ire);
14942 	}
14943 	return (zoneid);
14944 }
14945 
14946 zoneid_t
14947 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
14948     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
14949 {
14950 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
14951 	ire_t		*ire;
14952 	int		ire_flags = MATCH_IRE_TYPE;
14953 	zoneid_t	zoneid = ALL_ZONES;
14954 
14955 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
14956 		return (ALL_ZONES);
14957 
14958 	if (IN6_IS_ADDR_LINKLOCAL(addr))
14959 		ire_flags |= MATCH_IRE_ILL;
14960 
14961 	if (lookup_zoneid != ALL_ZONES)
14962 		ire_flags |= MATCH_IRE_ZONEONLY;
14963 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
14964 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
14965 	if (ire != NULL) {
14966 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
14967 		ire_refrele(ire);
14968 	}
14969 	return (zoneid);
14970 }
14971 
14972 /*
14973  * IP obserability hook support functions.
14974  */
14975 static void
14976 ipobs_init(ip_stack_t *ipst)
14977 {
14978 	netid_t id;
14979 
14980 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
14981 
14982 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
14983 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
14984 
14985 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
14986 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
14987 }
14988 
14989 static void
14990 ipobs_fini(ip_stack_t *ipst)
14991 {
14992 
14993 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
14994 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
14995 }
14996 
14997 /*
14998  * hook_pkt_observe_t is composed in network byte order so that the
14999  * entire mblk_t chain handed into hook_run can be used as-is.
15000  * The caveat is that use of the fields, such as the zone fields,
15001  * requires conversion into host byte order first.
15002  */
15003 void
15004 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15005     const ill_t *ill, ip_stack_t *ipst)
15006 {
15007 	hook_pkt_observe_t *hdr;
15008 	uint64_t grifindex;
15009 	mblk_t *imp;
15010 
15011 	imp = allocb(sizeof (*hdr), BPRI_HI);
15012 	if (imp == NULL)
15013 		return;
15014 
15015 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15016 	/*
15017 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15018 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15019 	 */
15020 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15021 	imp->b_cont = mp;
15022 
15023 	ASSERT(DB_TYPE(mp) == M_DATA);
15024 
15025 	if (IS_UNDER_IPMP(ill))
15026 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15027 	else
15028 		grifindex = 0;
15029 
15030 	hdr->hpo_version = 1;
15031 	hdr->hpo_htype = htons(htype);
15032 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15033 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15034 	hdr->hpo_grifindex = htonl(grifindex);
15035 	hdr->hpo_zsrc = htonl(zsrc);
15036 	hdr->hpo_zdst = htonl(zdst);
15037 	hdr->hpo_pkt = imp;
15038 	hdr->hpo_ctx = ipst->ips_netstack;
15039 
15040 	if (ill->ill_isv6) {
15041 		hdr->hpo_family = AF_INET6;
15042 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15043 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15044 	} else {
15045 		hdr->hpo_family = AF_INET;
15046 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15047 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15048 	}
15049 
15050 	imp->b_cont = NULL;
15051 	freemsg(imp);
15052 }
15053 
15054 /*
15055  * Utility routine that checks if `v4srcp' is a valid address on underlying
15056  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15057  * associated with `v4srcp' on success.  NOTE: if this is not called from
15058  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15059  * group during or after this lookup.
15060  */
15061 boolean_t
15062 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15063 {
15064 	ipif_t *ipif;
15065 
15066 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15067 	if (ipif != NULL) {
15068 		if (ipifp != NULL)
15069 			*ipifp = ipif;
15070 		else
15071 			ipif_refrele(ipif);
15072 		return (B_TRUE);
15073 	}
15074 
15075 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15076 	    *v4srcp));
15077 	return (B_FALSE);
15078 }
15079