xref: /titanic_44/usr/src/uts/common/inet/ip/ip.c (revision 1cfa752f4e24c34133009b0f6c139127a5c461de)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 1990 Mentat Inc.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/stream.h>
29 #include <sys/dlpi.h>
30 #include <sys/stropts.h>
31 #include <sys/sysmacros.h>
32 #include <sys/strsubr.h>
33 #include <sys/strlog.h>
34 #include <sys/strsun.h>
35 #include <sys/zone.h>
36 #define	_SUN_TPI_VERSION 2
37 #include <sys/tihdr.h>
38 #include <sys/xti_inet.h>
39 #include <sys/ddi.h>
40 #include <sys/suntpi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/sadb.h>
98 #include <inet/ipsec_impl.h>
99 #include <inet/iptun/iptun_impl.h>
100 #include <inet/ipdrop.h>
101 #include <inet/ip_netinfo.h>
102 #include <inet/ilb_ip.h>
103 
104 #include <sys/ethernet.h>
105 #include <net/if_types.h>
106 #include <sys/cpuvar.h>
107 
108 #include <ipp/ipp.h>
109 #include <ipp/ipp_impl.h>
110 #include <ipp/ipgpc/ipgpc.h>
111 
112 #include <sys/pattr.h>
113 #include <inet/ipclassifier.h>
114 #include <inet/sctp_ip.h>
115 #include <inet/sctp/sctp_impl.h>
116 #include <inet/udp_impl.h>
117 #include <inet/rawip_impl.h>
118 #include <inet/rts_impl.h>
119 
120 #include <sys/tsol/label.h>
121 #include <sys/tsol/tnet.h>
122 
123 #include <sys/squeue_impl.h>
124 #include <inet/ip_arp.h>
125 
126 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
131  * IP_SQUEUE_ENTER: SQ_PROCESS
132  * IP_SQUEUE_FILL: SQ_FILL
133  */
134 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
135 
136 int ip_squeue_flag;
137 
138 /*
139  * Setable in /etc/system
140  */
141 int ip_poll_normal_ms = 100;
142 int ip_poll_normal_ticks = 0;
143 int ip_modclose_ackwait_ms = 3000;
144 
145 /*
146  * It would be nice to have these present only in DEBUG systems, but the
147  * current design of the global symbol checking logic requires them to be
148  * unconditionally present.
149  */
150 uint_t ip_thread_data;			/* TSD key for debug support */
151 krwlock_t ip_thread_rwlock;
152 list_t	ip_thread_list;
153 
154 /*
155  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
156  */
157 
158 struct listptr_s {
159 	mblk_t	*lp_head;	/* pointer to the head of the list */
160 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
161 };
162 
163 typedef struct listptr_s listptr_t;
164 
165 /*
166  * This is used by ip_snmp_get_mib2_ip_route_media and
167  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
168  */
169 typedef struct iproutedata_s {
170 	uint_t		ird_idx;
171 	uint_t		ird_flags;	/* see below */
172 	listptr_t	ird_route;	/* ipRouteEntryTable */
173 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
174 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
175 } iproutedata_t;
176 
177 /* Include ire_testhidden and IRE_IF_CLONE routes */
178 #define	IRD_REPORT_ALL	0x01
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
199     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
200     void *args) = NULL;
201 
202 /*
203  * Hook function to generate cluster wide SPI.
204  */
205 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
206     void *) = NULL;
207 
208 /*
209  * Hook function to verify if the SPI is already utlized.
210  */
211 
212 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
213 
214 /*
215  * Hook function to delete the SPI from the cluster wide repository.
216  */
217 
218 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
219 
220 /*
221  * Hook function to inform the cluster when packet received on an IDLE SA
222  */
223 
224 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
225     in6_addr_t, in6_addr_t, void *) = NULL;
226 
227 /*
228  * Synchronization notes:
229  *
230  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
231  * MT level protection given by STREAMS. IP uses a combination of its own
232  * internal serialization mechanism and standard Solaris locking techniques.
233  * The internal serialization is per phyint.  This is used to serialize
234  * plumbing operations, IPMP operations, most set ioctls, etc.
235  *
236  * Plumbing is a long sequence of operations involving message
237  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
238  * involved in plumbing operations. A natural model is to serialize these
239  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
240  * parallel without any interference. But various set ioctls on hme0 are best
241  * serialized, along with IPMP operations and processing of DLPI control
242  * messages received from drivers on a per phyint basis. This serialization is
243  * provided by the ipsq_t and primitives operating on this. Details can
244  * be found in ip_if.c above the core primitives operating on ipsq_t.
245  *
246  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
247  * Simiarly lookup of an ire by a thread also returns a refheld ire.
248  * In addition ipif's and ill's referenced by the ire are also indirectly
249  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
250  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
251  * address of an ipif has to go through the ipsq_t. This ensures that only
252  * one such exclusive operation proceeds at any time on the ipif. It then
253  * waits for all refcnts
254  * associated with this ipif to come down to zero. The address is changed
255  * only after the ipif has been quiesced. Then the ipif is brought up again.
256  * More details are described above the comment in ip_sioctl_flags.
257  *
258  * Packet processing is based mostly on IREs and are fully multi-threaded
259  * using standard Solaris MT techniques.
260  *
261  * There are explicit locks in IP to handle:
262  * - The ip_g_head list maintained by mi_open_link() and friends.
263  *
264  * - The reassembly data structures (one lock per hash bucket)
265  *
266  * - conn_lock is meant to protect conn_t fields. The fields actually
267  *   protected by conn_lock are documented in the conn_t definition.
268  *
269  * - ire_lock to protect some of the fields of the ire, IRE tables
270  *   (one lock per hash bucket). Refer to ip_ire.c for details.
271  *
272  * - ndp_g_lock and ncec_lock for protecting NCEs.
273  *
274  * - ill_lock protects fields of the ill and ipif. Details in ip.h
275  *
276  * - ill_g_lock: This is a global reader/writer lock. Protects the following
277  *	* The AVL tree based global multi list of all ills.
278  *	* The linked list of all ipifs of an ill
279  *	* The <ipsq-xop> mapping
280  *	* <ill-phyint> association
281  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
282  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
283  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
284  *   writer for the actual duration of the insertion/deletion/change.
285  *
286  * - ill_lock:  This is a per ill mutex.
287  *   It protects some members of the ill_t struct; see ip.h for details.
288  *   It also protects the <ill-phyint> assoc.
289  *   It also protects the list of ipifs hanging off the ill.
290  *
291  * - ipsq_lock: This is a per ipsq_t mutex lock.
292  *   This protects some members of the ipsq_t struct; see ip.h for details.
293  *   It also protects the <ipsq-ipxop> mapping
294  *
295  * - ipx_lock: This is a per ipxop_t mutex lock.
296  *   This protects some members of the ipxop_t struct; see ip.h for details.
297  *
298  * - phyint_lock: This is a per phyint mutex lock. Protects just the
299  *   phyint_flags
300  *
301  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
302  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
303  *   uniqueness check also done atomically.
304  *
305  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
306  *   group list linked by ill_usesrc_grp_next. It also protects the
307  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
308  *   group is being added or deleted.  This lock is taken as a reader when
309  *   walking the list/group(eg: to get the number of members in a usesrc group).
310  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
311  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
312  *   example, it is not necessary to take this lock in the initial portion
313  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
314  *   operations are executed exclusively and that ensures that the "usesrc
315  *   group state" cannot change. The "usesrc group state" change can happen
316  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ipsq-xop> assocications:
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ipsq-xop> association, the ill_g_lock must be held as
325  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
326  * This is only done when ills are added or removed from IPMP groups.
327  *
328  * To add or delete an ipif from the list of ipifs hanging off the ill,
329  * ill_g_lock (writer) and ill_lock must be held and the thread must be
330  * a writer on the associated ipsq.
331  *
332  * To add or delete an ill to the system, the ill_g_lock must be held as
333  * writer and the thread must be a writer on the associated ipsq.
334  *
335  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
336  * must be a writer on the associated ipsq.
337  *
338  * Lock hierarchy
339  *
340  * Some lock hierarchy scenarios are listed below.
341  *
342  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
343  * ill_g_lock -> ill_lock(s) -> phyint_lock
344  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
345  * ill_g_lock -> ip_addr_avail_lock
346  * conn_lock -> irb_lock -> ill_lock -> ire_lock
347  * ill_g_lock -> ip_g_nd_lock
348  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
350  * arl_lock -> ill_lock
351  * ips_ire_dep_lock -> irb_lock
352  *
353  * When more than 1 ill lock is needed to be held, all ill lock addresses
354  * are sorted on address and locked starting from highest addressed lock
355  * downward.
356  *
357  * Multicast scenarios
358  * ips_ill_g_lock -> ill_mcast_lock
359  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
360  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
361  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
362  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
363  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
364  *
365  * IPsec scenarios
366  *
367  * ipsa_lock -> ill_g_lock -> ill_lock
368  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
369  *
370  * Trusted Solaris scenarios
371  *
372  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
373  * igsa_lock -> gcdb_lock
374  * gcgrp_rwlock -> ire_lock
375  * gcgrp_rwlock -> gcdb_lock
376  *
377  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
378  *
379  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
380  * sq_lock -> conn_lock -> QLOCK(q)
381  * ill_lock -> ft_lock -> fe_lock
382  *
383  * Routing/forwarding table locking notes:
384  *
385  * Lock acquisition order: Radix tree lock, irb_lock.
386  * Requirements:
387  * i.  Walker must not hold any locks during the walker callback.
388  * ii  Walker must not see a truncated tree during the walk because of any node
389  *     deletion.
390  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
391  *     in many places in the code to walk the irb list. Thus even if all the
392  *     ires in a bucket have been deleted, we still can't free the radix node
393  *     until the ires have actually been inactive'd (freed).
394  *
395  * Tree traversal - Need to hold the global tree lock in read mode.
396  * Before dropping the global tree lock, need to either increment the ire_refcnt
397  * to ensure that the radix node can't be deleted.
398  *
399  * Tree add - Need to hold the global tree lock in write mode to add a
400  * radix node. To prevent the node from being deleted, increment the
401  * irb_refcnt, after the node is added to the tree. The ire itself is
402  * added later while holding the irb_lock, but not the tree lock.
403  *
404  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
405  * All associated ires must be inactive (i.e. freed), and irb_refcnt
406  * must be zero.
407  *
408  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
409  * global tree lock (read mode) for traversal.
410  *
411  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
412  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
413  *
414  * IPsec notes :
415  *
416  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
417  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
418  * ip_xmit_attr_t has the
419  * information used by the IPsec code for applying the right level of
420  * protection. The information initialized by IP in the ip_xmit_attr_t
421  * is determined by the per-socket policy or global policy in the system.
422  * For inbound datagrams, the ip_recv_attr_t
423  * starts out with nothing in it. It gets filled
424  * with the right information if it goes through the AH/ESP code, which
425  * happens if the incoming packet is secure. The information initialized
426  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
427  * the policy requirements needed by per-socket policy or global policy
428  * is met or not.
429  *
430  * For fully connected sockets i.e dst, src [addr, port] is known,
431  * conn_policy_cached is set indicating that policy has been cached.
432  * conn_in_enforce_policy may or may not be set depending on whether
433  * there is a global policy match or per-socket policy match.
434  * Policy inheriting happpens in ip_policy_set once the destination is known.
435  * Once the right policy is set on the conn_t, policy cannot change for
436  * this socket. This makes life simpler for TCP (UDP ?) where
437  * re-transmissions go out with the same policy. For symmetry, policy
438  * is cached for fully connected UDP sockets also. Thus if policy is cached,
439  * it also implies that policy is latched i.e policy cannot change
440  * on these sockets. As we have the right policy on the conn, we don't
441  * have to lookup global policy for every outbound and inbound datagram
442  * and thus serving as an optimization. Note that a global policy change
443  * does not affect fully connected sockets if they have policy. If fully
444  * connected sockets did not have any policy associated with it, global
445  * policy change may affect them.
446  *
447  * IP Flow control notes:
448  * ---------------------
449  * Non-TCP streams are flow controlled by IP. The way this is accomplished
450  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
451  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
452  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
453  * functions.
454  *
455  * Per Tx ring udp flow control:
456  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
457  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
458  *
459  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
460  * To achieve best performance, outgoing traffic need to be fanned out among
461  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
462  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
463  * the address of connp as fanout hint to mac_tx(). Under flow controlled
464  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
465  * cookie points to a specific Tx ring that is blocked. The cookie is used to
466  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
467  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
468  * connp's. The drain list is not a single list but a configurable number of
469  * lists.
470  *
471  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
472  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
473  * which is equal to 128. This array in turn contains a pointer to idl_t[],
474  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
475  * list will point to the list of connp's that are flow controlled.
476  *
477  *                      ---------------   -------   -------   -------
478  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
479  *                   |  ---------------   -------   -------   -------
480  *                   |  ---------------   -------   -------   -------
481  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
482  * ----------------  |  ---------------   -------   -------   -------
483  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
484  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   .        .              .         .         .
487  *                   |  ---------------   -------   -------   -------
488  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
489  *                      ---------------   -------   -------   -------
490  *                      ---------------   -------   -------   -------
491  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
492  *                   |  ---------------   -------   -------   -------
493  *                   |  ---------------   -------   -------   -------
494  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
495  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
496  * ----------------  |        .              .         .         .
497  *                   |  ---------------   -------   -------   -------
498  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
499  *                      ---------------   -------   -------   -------
500  *     .....
501  * ----------------
502  * |idl_tx_list[n]|-> ...
503  * ----------------
504  *
505  * When mac_tx() returns a cookie, the cookie is hashed into an index into
506  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
507  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
508  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
509  * Further, conn_blocked is set to indicate that the conn is blocked.
510  *
511  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
512  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
513  * is again hashed to locate the appropriate idl_tx_list, which is then
514  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
515  * the drain list and calls conn_drain_remove() to clear flow control (via
516  * calling su_txq_full() or clearing QFULL), and remove the conn from the
517  * drain list.
518  *
519  * Note that the drain list is not a single list but a (configurable) array of
520  * lists (8 elements by default).  Synchronization between drain insertion and
521  * flow control wakeup is handled by using idl_txl->txl_lock, and only
522  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
523  *
524  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
525  * On the send side, if the packet cannot be sent down to the driver by IP
526  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
527  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
528  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
529  * control has been relieved, the blocked conns in the 0'th drain list are
530  * drained as in the non-STREAMS case.
531  *
532  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
533  * is done when the conn is inserted into the drain list (conn_drain_insert())
534  * and cleared when the conn is removed from the it (conn_drain_remove()).
535  *
536  * IPQOS notes:
537  *
538  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
539  * and IPQoS modules. IPPF includes hooks in IP at different control points
540  * (callout positions) which direct packets to IPQoS modules for policy
541  * processing. Policies, if present, are global.
542  *
543  * The callout positions are located in the following paths:
544  *		o local_in (packets destined for this host)
545  *		o local_out (packets orginating from this host )
546  *		o fwd_in  (packets forwarded by this m/c - inbound)
547  *		o fwd_out (packets forwarded by this m/c - outbound)
548  * Hooks at these callout points can be enabled/disabled using the ndd variable
549  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
550  * By default all the callout positions are enabled.
551  *
552  * Outbound (local_out)
553  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
554  *
555  * Inbound (local_in)
556  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
557  *
558  * Forwarding (in and out)
559  * Hooks are placed in ire_recv_forward_v4/v6.
560  *
561  * IP Policy Framework processing (IPPF processing)
562  * Policy processing for a packet is initiated by ip_process, which ascertains
563  * that the classifier (ipgpc) is loaded and configured, failing which the
564  * packet resumes normal processing in IP. If the clasifier is present, the
565  * packet is acted upon by one or more IPQoS modules (action instances), per
566  * filters configured in ipgpc and resumes normal IP processing thereafter.
567  * An action instance can drop a packet in course of its processing.
568  *
569  * Zones notes:
570  *
571  * The partitioning rules for networking are as follows:
572  * 1) Packets coming from a zone must have a source address belonging to that
573  * zone.
574  * 2) Packets coming from a zone can only be sent on a physical interface on
575  * which the zone has an IP address.
576  * 3) Between two zones on the same machine, packet delivery is only allowed if
577  * there's a matching route for the destination and zone in the forwarding
578  * table.
579  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
580  * different zones can bind to the same port with the wildcard address
581  * (INADDR_ANY).
582  *
583  * The granularity of interface partitioning is at the logical interface level.
584  * Therefore, every zone has its own IP addresses, and incoming packets can be
585  * attributed to a zone unambiguously. A logical interface is placed into a zone
586  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
587  * structure. Rule (1) is implemented by modifying the source address selection
588  * algorithm so that the list of eligible addresses is filtered based on the
589  * sending process zone.
590  *
591  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
592  * across all zones, depending on their type. Here is the break-up:
593  *
594  * IRE type				Shared/exclusive
595  * --------				----------------
596  * IRE_BROADCAST			Exclusive
597  * IRE_DEFAULT (default routes)		Shared (*)
598  * IRE_LOCAL				Exclusive (x)
599  * IRE_LOOPBACK				Exclusive
600  * IRE_PREFIX (net routes)		Shared (*)
601  * IRE_IF_NORESOLVER (interface routes)	Exclusive
602  * IRE_IF_RESOLVER (interface routes)	Exclusive
603  * IRE_IF_CLONE (interface routes)	Exclusive
604  * IRE_HOST (host routes)		Shared (*)
605  *
606  * (*) A zone can only use a default or off-subnet route if the gateway is
607  * directly reachable from the zone, that is, if the gateway's address matches
608  * one of the zone's logical interfaces.
609  *
610  * (x) IRE_LOCAL are handled a bit differently.
611  * When ip_restrict_interzone_loopback is set (the default),
612  * ire_route_recursive restricts loopback using an IRE_LOCAL
613  * between zone to the case when L2 would have conceptually looped the packet
614  * back, i.e. the loopback which is required since neither Ethernet drivers
615  * nor Ethernet hardware loops them back. This is the case when the normal
616  * routes (ignoring IREs with different zoneids) would send out the packet on
617  * the same ill as the ill with which is IRE_LOCAL is associated.
618  *
619  * Multiple zones can share a common broadcast address; typically all zones
620  * share the 255.255.255.255 address. Incoming as well as locally originated
621  * broadcast packets must be dispatched to all the zones on the broadcast
622  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
623  * since some zones may not be on the 10.16.72/24 network. To handle this, each
624  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
625  * sent to every zone that has an IRE_BROADCAST entry for the destination
626  * address on the input ill, see ip_input_broadcast().
627  *
628  * Applications in different zones can join the same multicast group address.
629  * The same logic applies for multicast as for broadcast. ip_input_multicast
630  * dispatches packets to all zones that have members on the physical interface.
631  */
632 
633 /*
634  * Squeue Fanout flags:
635  *	0: No fanout.
636  *	1: Fanout across all squeues
637  */
638 boolean_t	ip_squeue_fanout = 0;
639 
640 /*
641  * Maximum dups allowed per packet.
642  */
643 uint_t ip_max_frag_dups = 10;
644 
645 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
646 		    cred_t *credp, boolean_t isv6);
647 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
648 
649 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
650 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
651 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
652     ip_recv_attr_t *);
653 static void	icmp_options_update(ipha_t *);
654 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
655 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
656 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
657 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
658     ip_recv_attr_t *);
659 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
660 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
661     ip_recv_attr_t *);
662 
663 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
664 char		*ip_dot_addr(ipaddr_t, char *);
665 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
666 int		ip_close(queue_t *, int);
667 static char	*ip_dot_saddr(uchar_t *, char *);
668 static void	ip_lrput(queue_t *, mblk_t *);
669 ipaddr_t	ip_net_mask(ipaddr_t);
670 char		*ip_nv_lookup(nv_t *, int);
671 void	ip_rput(queue_t *, mblk_t *);
672 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
673 		    void *dummy_arg);
674 int		ip_snmp_get(queue_t *, mblk_t *, int);
675 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
676 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
678 		    ip_stack_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
680 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
703 		    ip_stack_t *ipst);
704 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
705 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
706 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
707 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
708 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
709 
710 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
711 		    mblk_t *);
712 
713 static void	conn_drain_init(ip_stack_t *);
714 static void	conn_drain_fini(ip_stack_t *);
715 static void	conn_drain(conn_t *connp, boolean_t closing);
716 
717 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
718 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
719 
720 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
721 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
722 static void	ip_stack_fini(netstackid_t stackid, void *arg);
723 
724 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
725     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
726     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
727     const in6_addr_t *);
728 
729 static int	ip_squeue_switch(int);
730 
731 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
732 static void	ip_kstat_fini(netstackid_t, kstat_t *);
733 static int	ip_kstat_update(kstat_t *kp, int rw);
734 static void	*icmp_kstat_init(netstackid_t);
735 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
736 static int	icmp_kstat_update(kstat_t *kp, int rw);
737 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
738 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
739 
740 static void	ipobs_init(ip_stack_t *);
741 static void	ipobs_fini(ip_stack_t *);
742 
743 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
744 
745 static long ip_rput_pullups;
746 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
747 
748 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
749 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
750 
751 int	ip_debug;
752 
753 /*
754  * Multirouting/CGTP stuff
755  */
756 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
757 
758 /*
759  * IP tunables related declarations. Definitions are in ip_tunables.c
760  */
761 extern mod_prop_info_t ip_propinfo_tbl[];
762 extern int ip_propinfo_count;
763 
764 /*
765  * Table of IP ioctls encoding the various properties of the ioctl and
766  * indexed based on the last byte of the ioctl command. Occasionally there
767  * is a clash, and there is more than 1 ioctl with the same last byte.
768  * In such a case 1 ioctl is encoded in the ndx table and the remaining
769  * ioctls are encoded in the misc table. An entry in the ndx table is
770  * retrieved by indexing on the last byte of the ioctl command and comparing
771  * the ioctl command with the value in the ndx table. In the event of a
772  * mismatch the misc table is then searched sequentially for the desired
773  * ioctl command.
774  *
775  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
776  */
777 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
778 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
779 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
780 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
781 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
782 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
783 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
784 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
785 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
786 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
787 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
788 
789 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
790 			MISC_CMD, ip_siocaddrt, NULL },
791 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
792 			MISC_CMD, ip_siocdelrt, NULL },
793 
794 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
795 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
796 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
797 			IF_CMD, ip_sioctl_get_addr, NULL },
798 
799 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
800 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
801 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
802 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
803 
804 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
805 			IPI_PRIV | IPI_WR,
806 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
807 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
808 			IPI_MODOK | IPI_GET_CMD,
809 			IF_CMD, ip_sioctl_get_flags, NULL },
810 
811 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
812 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
813 
814 	/* copyin size cannot be coded for SIOCGIFCONF */
815 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
816 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
817 
818 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
819 			IF_CMD, ip_sioctl_mtu, NULL },
820 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
821 			IF_CMD, ip_sioctl_get_mtu, NULL },
822 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
823 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
824 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
825 			IF_CMD, ip_sioctl_brdaddr, NULL },
826 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
827 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
828 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
829 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
830 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
831 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
832 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
833 			IF_CMD, ip_sioctl_metric, NULL },
834 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
835 
836 	/* See 166-168 below for extended SIOC*XARP ioctls */
837 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
838 			ARP_CMD, ip_sioctl_arp, NULL },
839 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
840 			ARP_CMD, ip_sioctl_arp, NULL },
841 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
842 			ARP_CMD, ip_sioctl_arp, NULL },
843 
844 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
845 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
846 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
847 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
848 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
849 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
850 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
851 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
852 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
853 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
854 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
855 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
856 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
857 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
858 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
859 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
860 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
861 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
862 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
863 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
864 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
865 
866 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
867 			MISC_CMD, if_unitsel, if_unitsel_restart },
868 
869 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
870 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
871 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
872 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
873 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
874 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
875 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
876 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
877 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
878 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
879 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
880 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
881 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
882 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
883 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
884 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
885 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
886 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
887 
888 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
889 			IPI_PRIV | IPI_WR | IPI_MODOK,
890 			IF_CMD, ip_sioctl_sifname, NULL },
891 
892 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
893 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
894 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
895 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
896 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
897 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
898 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
899 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
900 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
901 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
902 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
903 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
904 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
905 
906 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
907 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
908 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
909 			IF_CMD, ip_sioctl_get_muxid, NULL },
910 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
911 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
912 
913 	/* Both if and lif variants share same func */
914 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
915 			IF_CMD, ip_sioctl_get_lifindex, NULL },
916 	/* Both if and lif variants share same func */
917 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
918 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
919 
920 	/* copyin size cannot be coded for SIOCGIFCONF */
921 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
922 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
923 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
924 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
925 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
926 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
927 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
928 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
929 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
930 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
931 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
932 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
933 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
934 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
935 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
936 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
937 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
938 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
939 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
940 
941 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
942 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
943 			ip_sioctl_removeif_restart },
944 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
945 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
946 			LIF_CMD, ip_sioctl_addif, NULL },
947 #define	SIOCLIFADDR_NDX 112
948 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
949 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
950 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
951 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
952 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
953 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
954 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
955 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
956 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
957 			IPI_PRIV | IPI_WR,
958 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
959 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
960 			IPI_GET_CMD | IPI_MODOK,
961 			LIF_CMD, ip_sioctl_get_flags, NULL },
962 
963 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
964 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
965 
966 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
967 			ip_sioctl_get_lifconf, NULL },
968 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
969 			LIF_CMD, ip_sioctl_mtu, NULL },
970 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
971 			LIF_CMD, ip_sioctl_get_mtu, NULL },
972 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
973 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
974 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
975 			LIF_CMD, ip_sioctl_brdaddr, NULL },
976 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
977 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
978 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
979 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
980 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
981 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
982 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
983 			LIF_CMD, ip_sioctl_metric, NULL },
984 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
985 			IPI_PRIV | IPI_WR | IPI_MODOK,
986 			LIF_CMD, ip_sioctl_slifname,
987 			ip_sioctl_slifname_restart },
988 
989 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
990 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
991 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
992 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
993 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
994 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
995 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
996 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
997 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
998 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
999 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1000 			LIF_CMD, ip_sioctl_token, NULL },
1001 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1002 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1003 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1004 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1005 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1006 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1007 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1008 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1009 
1010 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1011 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1012 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1013 			LIF_CMD, ip_siocdelndp_v6, NULL },
1014 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1015 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1016 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1017 			LIF_CMD, ip_siocsetndp_v6, NULL },
1018 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1019 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1020 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1021 			MISC_CMD, ip_sioctl_tonlink, NULL },
1022 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1023 			MISC_CMD, ip_sioctl_tmysite, NULL },
1024 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1027 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1028 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1029 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1030 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1031 
1032 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 
1034 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1035 			LIF_CMD, ip_sioctl_get_binding, NULL },
1036 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1037 			IPI_PRIV | IPI_WR,
1038 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1039 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1040 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1041 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1042 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1043 
1044 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1045 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 
1049 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 
1051 	/* These are handled in ip_sioctl_copyin_setup itself */
1052 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1053 			MISC_CMD, NULL, NULL },
1054 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1055 			MISC_CMD, NULL, NULL },
1056 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1057 
1058 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1059 			ip_sioctl_get_lifconf, NULL },
1060 
1061 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1062 			XARP_CMD, ip_sioctl_arp, NULL },
1063 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1064 			XARP_CMD, ip_sioctl_arp, NULL },
1065 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1066 			XARP_CMD, ip_sioctl_arp, NULL },
1067 
1068 	/* SIOCPOPSOCKFS is not handled by IP */
1069 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1070 
1071 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1072 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1073 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1074 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1075 			ip_sioctl_slifzone_restart },
1076 	/* 172-174 are SCTP ioctls and not handled by IP */
1077 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1081 			IPI_GET_CMD, LIF_CMD,
1082 			ip_sioctl_get_lifusesrc, 0 },
1083 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1084 			IPI_PRIV | IPI_WR,
1085 			LIF_CMD, ip_sioctl_slifusesrc,
1086 			NULL },
1087 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1088 			ip_sioctl_get_lifsrcof, NULL },
1089 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1090 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1091 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1092 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1093 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1094 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1095 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1096 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1097 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* SIOCSENABLESDP is handled by SDP */
1099 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1100 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1101 	/* 185 */ { IPI_DONTCARE /* SIOCGIFHWADDR */, 0, 0, 0, NULL, NULL },
1102 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1103 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1104 			ip_sioctl_ilb_cmd, NULL },
1105 	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1106 	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1107 	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1108 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1109 	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1110 			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart }
1111 };
1112 
1113 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1114 
1115 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1116 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1117 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1118 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1119 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1120 	{ ND_GET,	0, 0, 0, NULL, NULL },
1121 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1122 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1123 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1124 		MISC_CMD, mrt_ioctl},
1125 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1126 		MISC_CMD, mrt_ioctl},
1127 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1128 		MISC_CMD, mrt_ioctl}
1129 };
1130 
1131 int ip_misc_ioctl_count =
1132     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1133 
1134 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1135 					/* Settable in /etc/system */
1136 /* Defined in ip_ire.c */
1137 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1138 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1139 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1140 
1141 static nv_t	ire_nv_arr[] = {
1142 	{ IRE_BROADCAST, "BROADCAST" },
1143 	{ IRE_LOCAL, "LOCAL" },
1144 	{ IRE_LOOPBACK, "LOOPBACK" },
1145 	{ IRE_DEFAULT, "DEFAULT" },
1146 	{ IRE_PREFIX, "PREFIX" },
1147 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1148 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1149 	{ IRE_IF_CLONE, "IF_CLONE" },
1150 	{ IRE_HOST, "HOST" },
1151 	{ IRE_MULTICAST, "MULTICAST" },
1152 	{ IRE_NOROUTE, "NOROUTE" },
1153 	{ 0 }
1154 };
1155 
1156 nv_t	*ire_nv_tbl = ire_nv_arr;
1157 
1158 /* Simple ICMP IP Header Template */
1159 static ipha_t icmp_ipha = {
1160 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1161 };
1162 
1163 struct module_info ip_mod_info = {
1164 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1165 	IP_MOD_LOWAT
1166 };
1167 
1168 /*
1169  * Duplicate static symbols within a module confuses mdb; so we avoid the
1170  * problem by making the symbols here distinct from those in udp.c.
1171  */
1172 
1173 /*
1174  * Entry points for IP as a device and as a module.
1175  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1176  */
1177 static struct qinit iprinitv4 = {
1178 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1179 	&ip_mod_info
1180 };
1181 
1182 struct qinit iprinitv6 = {
1183 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1184 	&ip_mod_info
1185 };
1186 
1187 static struct qinit ipwinit = {
1188 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1189 	&ip_mod_info
1190 };
1191 
1192 static struct qinit iplrinit = {
1193 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1194 	&ip_mod_info
1195 };
1196 
1197 static struct qinit iplwinit = {
1198 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1199 	&ip_mod_info
1200 };
1201 
1202 /* For AF_INET aka /dev/ip */
1203 struct streamtab ipinfov4 = {
1204 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1205 };
1206 
1207 /* For AF_INET6 aka /dev/ip6 */
1208 struct streamtab ipinfov6 = {
1209 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1210 };
1211 
1212 #ifdef	DEBUG
1213 boolean_t skip_sctp_cksum = B_FALSE;
1214 #endif
1215 
1216 /*
1217  * Generate an ICMP fragmentation needed message.
1218  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1219  * constructed by the caller.
1220  */
1221 void
1222 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1223 {
1224 	icmph_t	icmph;
1225 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1226 
1227 	mp = icmp_pkt_err_ok(mp, ira);
1228 	if (mp == NULL)
1229 		return;
1230 
1231 	bzero(&icmph, sizeof (icmph_t));
1232 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1233 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1234 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1235 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1236 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1237 
1238 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1239 }
1240 
1241 /*
1242  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1243  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1244  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1245  * Likewise, if the ICMP error is misformed (too short, etc), then it
1246  * returns NULL. The caller uses this to determine whether or not to send
1247  * to raw sockets.
1248  *
1249  * All error messages are passed to the matching transport stream.
1250  *
1251  * The following cases are handled by icmp_inbound:
1252  * 1) It needs to send a reply back and possibly delivering it
1253  *    to the "interested" upper clients.
1254  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1255  * 3) It needs to change some values in IP only.
1256  * 4) It needs to change some values in IP and upper layers e.g TCP
1257  *    by delivering an error to the upper layers.
1258  *
1259  * We handle the above three cases in the context of IPsec in the
1260  * following way :
1261  *
1262  * 1) Send the reply back in the same way as the request came in.
1263  *    If it came in encrypted, it goes out encrypted. If it came in
1264  *    clear, it goes out in clear. Thus, this will prevent chosen
1265  *    plain text attack.
1266  * 2) The client may or may not expect things to come in secure.
1267  *    If it comes in secure, the policy constraints are checked
1268  *    before delivering it to the upper layers. If it comes in
1269  *    clear, ipsec_inbound_accept_clear will decide whether to
1270  *    accept this in clear or not. In both the cases, if the returned
1271  *    message (IP header + 8 bytes) that caused the icmp message has
1272  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1273  *    sending up. If there are only 8 bytes of returned message, then
1274  *    upper client will not be notified.
1275  * 3) Check with global policy to see whether it matches the constaints.
1276  *    But this will be done only if icmp_accept_messages_in_clear is
1277  *    zero.
1278  * 4) If we need to change both in IP and ULP, then the decision taken
1279  *    while affecting the values in IP and while delivering up to TCP
1280  *    should be the same.
1281  *
1282  * 	There are two cases.
1283  *
1284  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1285  *	   failed), we will not deliver it to the ULP, even though they
1286  *	   are *willing* to accept in *clear*. This is fine as our global
1287  *	   disposition to icmp messages asks us reject the datagram.
1288  *
1289  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1290  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1291  *	   to deliver it to ULP (policy failed), it can lead to
1292  *	   consistency problems. The cases known at this time are
1293  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1294  *	   values :
1295  *
1296  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1297  *	     and Upper layer rejects. Then the communication will
1298  *	     come to a stop. This is solved by making similar decisions
1299  *	     at both levels. Currently, when we are unable to deliver
1300  *	     to the Upper Layer (due to policy failures) while IP has
1301  *	     adjusted dce_pmtu, the next outbound datagram would
1302  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1303  *	     will be with the right level of protection. Thus the right
1304  *	     value will be communicated even if we are not able to
1305  *	     communicate when we get from the wire initially. But this
1306  *	     assumes there would be at least one outbound datagram after
1307  *	     IP has adjusted its dce_pmtu value. To make things
1308  *	     simpler, we accept in clear after the validation of
1309  *	     AH/ESP headers.
1310  *
1311  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1312  *	     upper layer depending on the level of protection the upper
1313  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1314  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1315  *	     should be accepted in clear when the Upper layer expects secure.
1316  *	     Thus the communication may get aborted by some bad ICMP
1317  *	     packets.
1318  */
1319 mblk_t *
1320 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1321 {
1322 	icmph_t		*icmph;
1323 	ipha_t		*ipha;		/* Outer header */
1324 	int		ip_hdr_length;	/* Outer header length */
1325 	boolean_t	interested;
1326 	ipif_t		*ipif;
1327 	uint32_t	ts;
1328 	uint32_t	*tsp;
1329 	timestruc_t	now;
1330 	ill_t		*ill = ira->ira_ill;
1331 	ip_stack_t	*ipst = ill->ill_ipst;
1332 	zoneid_t	zoneid = ira->ira_zoneid;
1333 	int		len_needed;
1334 	mblk_t		*mp_ret = NULL;
1335 
1336 	ipha = (ipha_t *)mp->b_rptr;
1337 
1338 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1339 
1340 	ip_hdr_length = ira->ira_ip_hdr_length;
1341 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1342 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1343 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1344 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1345 			freemsg(mp);
1346 			return (NULL);
1347 		}
1348 		/* Last chance to get real. */
1349 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1350 		if (ipha == NULL) {
1351 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1352 			freemsg(mp);
1353 			return (NULL);
1354 		}
1355 	}
1356 
1357 	/* The IP header will always be a multiple of four bytes */
1358 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1359 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1360 	    icmph->icmph_code));
1361 
1362 	/*
1363 	 * We will set "interested" to "true" if we should pass a copy to
1364 	 * the transport or if we handle the packet locally.
1365 	 */
1366 	interested = B_FALSE;
1367 	switch (icmph->icmph_type) {
1368 	case ICMP_ECHO_REPLY:
1369 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1370 		break;
1371 	case ICMP_DEST_UNREACHABLE:
1372 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1373 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1374 		interested = B_TRUE;	/* Pass up to transport */
1375 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1376 		break;
1377 	case ICMP_SOURCE_QUENCH:
1378 		interested = B_TRUE;	/* Pass up to transport */
1379 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1380 		break;
1381 	case ICMP_REDIRECT:
1382 		if (!ipst->ips_ip_ignore_redirect)
1383 			interested = B_TRUE;
1384 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1385 		break;
1386 	case ICMP_ECHO_REQUEST:
1387 		/*
1388 		 * Whether to respond to echo requests that come in as IP
1389 		 * broadcasts or as IP multicast is subject to debate
1390 		 * (what isn't?).  We aim to please, you pick it.
1391 		 * Default is do it.
1392 		 */
1393 		if (ira->ira_flags & IRAF_MULTICAST) {
1394 			/* multicast: respond based on tunable */
1395 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1396 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1397 			/* broadcast: respond based on tunable */
1398 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1399 		} else {
1400 			/* unicast: always respond */
1401 			interested = B_TRUE;
1402 		}
1403 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1404 		if (!interested) {
1405 			/* We never pass these to RAW sockets */
1406 			freemsg(mp);
1407 			return (NULL);
1408 		}
1409 
1410 		/* Check db_ref to make sure we can modify the packet. */
1411 		if (mp->b_datap->db_ref > 1) {
1412 			mblk_t	*mp1;
1413 
1414 			mp1 = copymsg(mp);
1415 			freemsg(mp);
1416 			if (!mp1) {
1417 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1418 				return (NULL);
1419 			}
1420 			mp = mp1;
1421 			ipha = (ipha_t *)mp->b_rptr;
1422 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1423 		}
1424 		icmph->icmph_type = ICMP_ECHO_REPLY;
1425 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1426 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1427 		return (NULL);
1428 
1429 	case ICMP_ROUTER_ADVERTISEMENT:
1430 	case ICMP_ROUTER_SOLICITATION:
1431 		break;
1432 	case ICMP_TIME_EXCEEDED:
1433 		interested = B_TRUE;	/* Pass up to transport */
1434 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1435 		break;
1436 	case ICMP_PARAM_PROBLEM:
1437 		interested = B_TRUE;	/* Pass up to transport */
1438 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1439 		break;
1440 	case ICMP_TIME_STAMP_REQUEST:
1441 		/* Response to Time Stamp Requests is local policy. */
1442 		if (ipst->ips_ip_g_resp_to_timestamp) {
1443 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1444 				interested =
1445 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1446 			else
1447 				interested = B_TRUE;
1448 		}
1449 		if (!interested) {
1450 			/* We never pass these to RAW sockets */
1451 			freemsg(mp);
1452 			return (NULL);
1453 		}
1454 
1455 		/* Make sure we have enough of the packet */
1456 		len_needed = ip_hdr_length + ICMPH_SIZE +
1457 		    3 * sizeof (uint32_t);
1458 
1459 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1460 			ipha = ip_pullup(mp, len_needed, ira);
1461 			if (ipha == NULL) {
1462 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1463 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1464 				    mp, ill);
1465 				freemsg(mp);
1466 				return (NULL);
1467 			}
1468 			/* Refresh following the pullup. */
1469 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1470 		}
1471 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1472 		/* Check db_ref to make sure we can modify the packet. */
1473 		if (mp->b_datap->db_ref > 1) {
1474 			mblk_t	*mp1;
1475 
1476 			mp1 = copymsg(mp);
1477 			freemsg(mp);
1478 			if (!mp1) {
1479 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1480 				return (NULL);
1481 			}
1482 			mp = mp1;
1483 			ipha = (ipha_t *)mp->b_rptr;
1484 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1485 		}
1486 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1487 		tsp = (uint32_t *)&icmph[1];
1488 		tsp++;		/* Skip past 'originate time' */
1489 		/* Compute # of milliseconds since midnight */
1490 		gethrestime(&now);
1491 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1492 		    now.tv_nsec / (NANOSEC / MILLISEC);
1493 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1494 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1495 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1496 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1497 		return (NULL);
1498 
1499 	case ICMP_TIME_STAMP_REPLY:
1500 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1501 		break;
1502 	case ICMP_INFO_REQUEST:
1503 		/* Per RFC 1122 3.2.2.7, ignore this. */
1504 	case ICMP_INFO_REPLY:
1505 		break;
1506 	case ICMP_ADDRESS_MASK_REQUEST:
1507 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1508 			interested =
1509 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1510 		} else {
1511 			interested = B_TRUE;
1512 		}
1513 		if (!interested) {
1514 			/* We never pass these to RAW sockets */
1515 			freemsg(mp);
1516 			return (NULL);
1517 		}
1518 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1519 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1520 			ipha = ip_pullup(mp, len_needed, ira);
1521 			if (ipha == NULL) {
1522 				BUMP_MIB(ill->ill_ip_mib,
1523 				    ipIfStatsInTruncatedPkts);
1524 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1525 				    ill);
1526 				freemsg(mp);
1527 				return (NULL);
1528 			}
1529 			/* Refresh following the pullup. */
1530 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1531 		}
1532 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1533 		/* Check db_ref to make sure we can modify the packet. */
1534 		if (mp->b_datap->db_ref > 1) {
1535 			mblk_t	*mp1;
1536 
1537 			mp1 = copymsg(mp);
1538 			freemsg(mp);
1539 			if (!mp1) {
1540 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1541 				return (NULL);
1542 			}
1543 			mp = mp1;
1544 			ipha = (ipha_t *)mp->b_rptr;
1545 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1546 		}
1547 		/*
1548 		 * Need the ipif with the mask be the same as the source
1549 		 * address of the mask reply. For unicast we have a specific
1550 		 * ipif. For multicast/broadcast we only handle onlink
1551 		 * senders, and use the source address to pick an ipif.
1552 		 */
1553 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1554 		if (ipif == NULL) {
1555 			/* Broadcast or multicast */
1556 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1557 			if (ipif == NULL) {
1558 				freemsg(mp);
1559 				return (NULL);
1560 			}
1561 		}
1562 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1563 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1564 		ipif_refrele(ipif);
1565 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1566 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1567 		return (NULL);
1568 
1569 	case ICMP_ADDRESS_MASK_REPLY:
1570 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1571 		break;
1572 	default:
1573 		interested = B_TRUE;	/* Pass up to transport */
1574 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1575 		break;
1576 	}
1577 	/*
1578 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1579 	 * if there isn't one.
1580 	 */
1581 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1582 		/* If there is an ICMP client and we want one too, copy it. */
1583 
1584 		if (!interested) {
1585 			/* Caller will deliver to RAW sockets */
1586 			return (mp);
1587 		}
1588 		mp_ret = copymsg(mp);
1589 		if (mp_ret == NULL) {
1590 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1591 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1592 		}
1593 	} else if (!interested) {
1594 		/* Neither we nor raw sockets are interested. Drop packet now */
1595 		freemsg(mp);
1596 		return (NULL);
1597 	}
1598 
1599 	/*
1600 	 * ICMP error or redirect packet. Make sure we have enough of
1601 	 * the header and that db_ref == 1 since we might end up modifying
1602 	 * the packet.
1603 	 */
1604 	if (mp->b_cont != NULL) {
1605 		if (ip_pullup(mp, -1, ira) == NULL) {
1606 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1607 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1608 			    mp, ill);
1609 			freemsg(mp);
1610 			return (mp_ret);
1611 		}
1612 	}
1613 
1614 	if (mp->b_datap->db_ref > 1) {
1615 		mblk_t	*mp1;
1616 
1617 		mp1 = copymsg(mp);
1618 		if (mp1 == NULL) {
1619 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1620 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1621 			freemsg(mp);
1622 			return (mp_ret);
1623 		}
1624 		freemsg(mp);
1625 		mp = mp1;
1626 	}
1627 
1628 	/*
1629 	 * In case mp has changed, verify the message before any further
1630 	 * processes.
1631 	 */
1632 	ipha = (ipha_t *)mp->b_rptr;
1633 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1634 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1635 		freemsg(mp);
1636 		return (mp_ret);
1637 	}
1638 
1639 	switch (icmph->icmph_type) {
1640 	case ICMP_REDIRECT:
1641 		icmp_redirect_v4(mp, ipha, icmph, ira);
1642 		break;
1643 	case ICMP_DEST_UNREACHABLE:
1644 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1645 			/* Update DCE and adjust MTU is icmp header if needed */
1646 			icmp_inbound_too_big_v4(icmph, ira);
1647 		}
1648 		/* FALLTHRU */
1649 	default:
1650 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1651 		break;
1652 	}
1653 	return (mp_ret);
1654 }
1655 
1656 /*
1657  * Send an ICMP echo, timestamp or address mask reply.
1658  * The caller has already updated the payload part of the packet.
1659  * We handle the ICMP checksum, IP source address selection and feed
1660  * the packet into ip_output_simple.
1661  */
1662 static void
1663 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1664     ip_recv_attr_t *ira)
1665 {
1666 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1667 	ill_t		*ill = ira->ira_ill;
1668 	ip_stack_t	*ipst = ill->ill_ipst;
1669 	ip_xmit_attr_t	ixas;
1670 
1671 	/* Send out an ICMP packet */
1672 	icmph->icmph_checksum = 0;
1673 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1674 	/* Reset time to live. */
1675 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1676 	{
1677 		/* Swap source and destination addresses */
1678 		ipaddr_t tmp;
1679 
1680 		tmp = ipha->ipha_src;
1681 		ipha->ipha_src = ipha->ipha_dst;
1682 		ipha->ipha_dst = tmp;
1683 	}
1684 	ipha->ipha_ident = 0;
1685 	if (!IS_SIMPLE_IPH(ipha))
1686 		icmp_options_update(ipha);
1687 
1688 	bzero(&ixas, sizeof (ixas));
1689 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1690 	ixas.ixa_zoneid = ira->ira_zoneid;
1691 	ixas.ixa_cred = kcred;
1692 	ixas.ixa_cpid = NOPID;
1693 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1694 	ixas.ixa_ifindex = 0;
1695 	ixas.ixa_ipst = ipst;
1696 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1697 
1698 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1699 		/*
1700 		 * This packet should go out the same way as it
1701 		 * came in i.e in clear, independent of the IPsec policy
1702 		 * for transmitting packets.
1703 		 */
1704 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1705 	} else {
1706 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1707 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1708 			/* Note: mp already consumed and ip_drop_packet done */
1709 			return;
1710 		}
1711 	}
1712 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1713 		/*
1714 		 * Not one or our addresses (IRE_LOCALs), thus we let
1715 		 * ip_output_simple pick the source.
1716 		 */
1717 		ipha->ipha_src = INADDR_ANY;
1718 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1719 	}
1720 	/* Should we send with DF and use dce_pmtu? */
1721 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1722 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1723 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1724 	}
1725 
1726 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1727 
1728 	(void) ip_output_simple(mp, &ixas);
1729 	ixa_cleanup(&ixas);
1730 }
1731 
1732 /*
1733  * Verify the ICMP messages for either for ICMP error or redirect packet.
1734  * The caller should have fully pulled up the message. If it's a redirect
1735  * packet, only basic checks on IP header will be done; otherwise, verify
1736  * the packet by looking at the included ULP header.
1737  *
1738  * Called before icmp_inbound_error_fanout_v4 is called.
1739  */
1740 static boolean_t
1741 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1742 {
1743 	ill_t		*ill = ira->ira_ill;
1744 	int		hdr_length;
1745 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1746 	conn_t		*connp;
1747 	ipha_t		*ipha;	/* Inner IP header */
1748 
1749 	ipha = (ipha_t *)&icmph[1];
1750 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1751 		goto truncated;
1752 
1753 	hdr_length = IPH_HDR_LENGTH(ipha);
1754 
1755 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1756 		goto discard_pkt;
1757 
1758 	if (hdr_length < sizeof (ipha_t))
1759 		goto truncated;
1760 
1761 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1762 		goto truncated;
1763 
1764 	/*
1765 	 * Stop here for ICMP_REDIRECT.
1766 	 */
1767 	if (icmph->icmph_type == ICMP_REDIRECT)
1768 		return (B_TRUE);
1769 
1770 	/*
1771 	 * ICMP errors only.
1772 	 */
1773 	switch (ipha->ipha_protocol) {
1774 	case IPPROTO_UDP:
1775 		/*
1776 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1777 		 * transport header.
1778 		 */
1779 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1780 		    mp->b_wptr)
1781 			goto truncated;
1782 		break;
1783 	case IPPROTO_TCP: {
1784 		tcpha_t		*tcpha;
1785 
1786 		/*
1787 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1788 		 * transport header.
1789 		 */
1790 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1791 		    mp->b_wptr)
1792 			goto truncated;
1793 
1794 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1795 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1796 		    ipst);
1797 		if (connp == NULL)
1798 			goto discard_pkt;
1799 
1800 		if ((connp->conn_verifyicmp != NULL) &&
1801 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1802 			CONN_DEC_REF(connp);
1803 			goto discard_pkt;
1804 		}
1805 		CONN_DEC_REF(connp);
1806 		break;
1807 	}
1808 	case IPPROTO_SCTP:
1809 		/*
1810 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1811 		 * transport header.
1812 		 */
1813 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1814 		    mp->b_wptr)
1815 			goto truncated;
1816 		break;
1817 	case IPPROTO_ESP:
1818 	case IPPROTO_AH:
1819 		break;
1820 	case IPPROTO_ENCAP:
1821 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1822 		    mp->b_wptr)
1823 			goto truncated;
1824 		break;
1825 	default:
1826 		break;
1827 	}
1828 
1829 	return (B_TRUE);
1830 
1831 discard_pkt:
1832 	/* Bogus ICMP error. */
1833 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1834 	return (B_FALSE);
1835 
1836 truncated:
1837 	/* We pulled up everthing already. Must be truncated */
1838 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1839 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1840 	return (B_FALSE);
1841 }
1842 
1843 /* Table from RFC 1191 */
1844 static int icmp_frag_size_table[] =
1845 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1846 
1847 /*
1848  * Process received ICMP Packet too big.
1849  * Just handles the DCE create/update, including using the above table of
1850  * PMTU guesses. The caller is responsible for validating the packet before
1851  * passing it in and also to fanout the ICMP error to any matching transport
1852  * conns. Assumes the message has been fully pulled up and verified.
1853  *
1854  * Before getting here, the caller has called icmp_inbound_verify_v4()
1855  * that should have verified with ULP to prevent undoing the changes we're
1856  * going to make to DCE. For example, TCP might have verified that the packet
1857  * which generated error is in the send window.
1858  *
1859  * In some cases modified this MTU in the ICMP header packet; the caller
1860  * should pass to the matching ULP after this returns.
1861  */
1862 static void
1863 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1864 {
1865 	dce_t		*dce;
1866 	int		old_mtu;
1867 	int		mtu, orig_mtu;
1868 	ipaddr_t	dst;
1869 	boolean_t	disable_pmtud;
1870 	ill_t		*ill = ira->ira_ill;
1871 	ip_stack_t	*ipst = ill->ill_ipst;
1872 	uint_t		hdr_length;
1873 	ipha_t		*ipha;
1874 
1875 	/* Caller already pulled up everything. */
1876 	ipha = (ipha_t *)&icmph[1];
1877 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1878 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1879 	ASSERT(ill != NULL);
1880 
1881 	hdr_length = IPH_HDR_LENGTH(ipha);
1882 
1883 	/*
1884 	 * We handle path MTU for source routed packets since the DCE
1885 	 * is looked up using the final destination.
1886 	 */
1887 	dst = ip_get_dst(ipha);
1888 
1889 	dce = dce_lookup_and_add_v4(dst, ipst);
1890 	if (dce == NULL) {
1891 		/* Couldn't add a unique one - ENOMEM */
1892 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1893 		    ntohl(dst)));
1894 		return;
1895 	}
1896 
1897 	/* Check for MTU discovery advice as described in RFC 1191 */
1898 	mtu = ntohs(icmph->icmph_du_mtu);
1899 	orig_mtu = mtu;
1900 	disable_pmtud = B_FALSE;
1901 
1902 	mutex_enter(&dce->dce_lock);
1903 	if (dce->dce_flags & DCEF_PMTU)
1904 		old_mtu = dce->dce_pmtu;
1905 	else
1906 		old_mtu = ill->ill_mtu;
1907 
1908 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1909 		uint32_t length;
1910 		int	i;
1911 
1912 		/*
1913 		 * Use the table from RFC 1191 to figure out
1914 		 * the next "plateau" based on the length in
1915 		 * the original IP packet.
1916 		 */
1917 		length = ntohs(ipha->ipha_length);
1918 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1919 		    uint32_t, length);
1920 		if (old_mtu <= length &&
1921 		    old_mtu >= length - hdr_length) {
1922 			/*
1923 			 * Handle broken BSD 4.2 systems that
1924 			 * return the wrong ipha_length in ICMP
1925 			 * errors.
1926 			 */
1927 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1928 			    length, old_mtu));
1929 			length -= hdr_length;
1930 		}
1931 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1932 			if (length > icmp_frag_size_table[i])
1933 				break;
1934 		}
1935 		if (i == A_CNT(icmp_frag_size_table)) {
1936 			/* Smaller than IP_MIN_MTU! */
1937 			ip1dbg(("Too big for packet size %d\n",
1938 			    length));
1939 			disable_pmtud = B_TRUE;
1940 			mtu = ipst->ips_ip_pmtu_min;
1941 		} else {
1942 			mtu = icmp_frag_size_table[i];
1943 			ip1dbg(("Calculated mtu %d, packet size %d, "
1944 			    "before %d\n", mtu, length, old_mtu));
1945 			if (mtu < ipst->ips_ip_pmtu_min) {
1946 				mtu = ipst->ips_ip_pmtu_min;
1947 				disable_pmtud = B_TRUE;
1948 			}
1949 		}
1950 	}
1951 	if (disable_pmtud)
1952 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1953 	else
1954 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1955 
1956 	dce->dce_pmtu = MIN(old_mtu, mtu);
1957 	/* Prepare to send the new max frag size for the ULP. */
1958 	icmph->icmph_du_zero = 0;
1959 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1960 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1961 	    dce, int, orig_mtu, int, mtu);
1962 
1963 	/* We now have a PMTU for sure */
1964 	dce->dce_flags |= DCEF_PMTU;
1965 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1966 	mutex_exit(&dce->dce_lock);
1967 	/*
1968 	 * After dropping the lock the new value is visible to everyone.
1969 	 * Then we bump the generation number so any cached values reinspect
1970 	 * the dce_t.
1971 	 */
1972 	dce_increment_generation(dce);
1973 	dce_refrele(dce);
1974 }
1975 
1976 /*
1977  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1978  * calls this function.
1979  */
1980 static mblk_t *
1981 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1982 {
1983 	int length;
1984 
1985 	ASSERT(mp->b_datap->db_type == M_DATA);
1986 
1987 	/* icmp_inbound_v4 has already pulled up the whole error packet */
1988 	ASSERT(mp->b_cont == NULL);
1989 
1990 	/*
1991 	 * The length that we want to overlay is the inner header
1992 	 * and what follows it.
1993 	 */
1994 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
1995 
1996 	/*
1997 	 * Overlay the inner header and whatever follows it over the
1998 	 * outer header.
1999 	 */
2000 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2001 
2002 	/* Adjust for what we removed */
2003 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2004 	return (mp);
2005 }
2006 
2007 /*
2008  * Try to pass the ICMP message upstream in case the ULP cares.
2009  *
2010  * If the packet that caused the ICMP error is secure, we send
2011  * it to AH/ESP to make sure that the attached packet has a
2012  * valid association. ipha in the code below points to the
2013  * IP header of the packet that caused the error.
2014  *
2015  * For IPsec cases, we let the next-layer-up (which has access to
2016  * cached policy on the conn_t, or can query the SPD directly)
2017  * subtract out any IPsec overhead if they must.  We therefore make no
2018  * adjustments here for IPsec overhead.
2019  *
2020  * IFN could have been generated locally or by some router.
2021  *
2022  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2023  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2024  *	    This happens because IP adjusted its value of MTU on an
2025  *	    earlier IFN message and could not tell the upper layer,
2026  *	    the new adjusted value of MTU e.g. Packet was encrypted
2027  *	    or there was not enough information to fanout to upper
2028  *	    layers. Thus on the next outbound datagram, ire_send_wire
2029  *	    generates the IFN, where IPsec processing has *not* been
2030  *	    done.
2031  *
2032  *	    Note that we retain ixa_fragsize across IPsec thus once
2033  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2034  *	    no change the fragsize even if the path MTU changes before
2035  *	    we reach ip_output_post_ipsec.
2036  *
2037  *	    In the local case, IRAF_LOOPBACK will be set indicating
2038  *	    that IFN was generated locally.
2039  *
2040  * ROUTER : IFN could be secure or non-secure.
2041  *
2042  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2043  *	      packet in error has AH/ESP headers to validate the AH/ESP
2044  *	      headers. AH/ESP will verify whether there is a valid SA or
2045  *	      not and send it back. We will fanout again if we have more
2046  *	      data in the packet.
2047  *
2048  *	      If the packet in error does not have AH/ESP, we handle it
2049  *	      like any other case.
2050  *
2051  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2052  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2053  *	      valid SA or not and send it back. We will fanout again if
2054  *	      we have more data in the packet.
2055  *
2056  *	      If the packet in error does not have AH/ESP, we handle it
2057  *	      like any other case.
2058  *
2059  * The caller must have called icmp_inbound_verify_v4.
2060  */
2061 static void
2062 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2063 {
2064 	uint16_t	*up;	/* Pointer to ports in ULP header */
2065 	uint32_t	ports;	/* reversed ports for fanout */
2066 	ipha_t		ripha;	/* With reversed addresses */
2067 	ipha_t		*ipha;  /* Inner IP header */
2068 	uint_t		hdr_length; /* Inner IP header length */
2069 	tcpha_t		*tcpha;
2070 	conn_t		*connp;
2071 	ill_t		*ill = ira->ira_ill;
2072 	ip_stack_t	*ipst = ill->ill_ipst;
2073 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2074 	ill_t		*rill = ira->ira_rill;
2075 
2076 	/* Caller already pulled up everything. */
2077 	ipha = (ipha_t *)&icmph[1];
2078 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2079 	ASSERT(mp->b_cont == NULL);
2080 
2081 	hdr_length = IPH_HDR_LENGTH(ipha);
2082 	ira->ira_protocol = ipha->ipha_protocol;
2083 
2084 	/*
2085 	 * We need a separate IP header with the source and destination
2086 	 * addresses reversed to do fanout/classification because the ipha in
2087 	 * the ICMP error is in the form we sent it out.
2088 	 */
2089 	ripha.ipha_src = ipha->ipha_dst;
2090 	ripha.ipha_dst = ipha->ipha_src;
2091 	ripha.ipha_protocol = ipha->ipha_protocol;
2092 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2093 
2094 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2095 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2096 	    ntohl(ipha->ipha_dst),
2097 	    icmph->icmph_type, icmph->icmph_code));
2098 
2099 	switch (ipha->ipha_protocol) {
2100 	case IPPROTO_UDP:
2101 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2102 
2103 		/* Attempt to find a client stream based on port. */
2104 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2105 		    ntohs(up[0]), ntohs(up[1])));
2106 
2107 		/* Note that we send error to all matches. */
2108 		ira->ira_flags |= IRAF_ICMP_ERROR;
2109 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2110 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2111 		return;
2112 
2113 	case IPPROTO_TCP:
2114 		/*
2115 		 * Find a TCP client stream for this packet.
2116 		 * Note that we do a reverse lookup since the header is
2117 		 * in the form we sent it out.
2118 		 */
2119 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2120 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2121 		    ipst);
2122 		if (connp == NULL)
2123 			goto discard_pkt;
2124 
2125 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2126 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2127 			mp = ipsec_check_inbound_policy(mp, connp,
2128 			    ipha, NULL, ira);
2129 			if (mp == NULL) {
2130 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2131 				/* Note that mp is NULL */
2132 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2133 				CONN_DEC_REF(connp);
2134 				return;
2135 			}
2136 		}
2137 
2138 		ira->ira_flags |= IRAF_ICMP_ERROR;
2139 		ira->ira_ill = ira->ira_rill = NULL;
2140 		if (IPCL_IS_TCP(connp)) {
2141 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2142 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2143 			    SQTAG_TCP_INPUT_ICMP_ERR);
2144 		} else {
2145 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2146 			(connp->conn_recv)(connp, mp, NULL, ira);
2147 			CONN_DEC_REF(connp);
2148 		}
2149 		ira->ira_ill = ill;
2150 		ira->ira_rill = rill;
2151 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2152 		return;
2153 
2154 	case IPPROTO_SCTP:
2155 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2156 		/* Find a SCTP client stream for this packet. */
2157 		((uint16_t *)&ports)[0] = up[1];
2158 		((uint16_t *)&ports)[1] = up[0];
2159 
2160 		ira->ira_flags |= IRAF_ICMP_ERROR;
2161 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2162 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2163 		return;
2164 
2165 	case IPPROTO_ESP:
2166 	case IPPROTO_AH:
2167 		if (!ipsec_loaded(ipss)) {
2168 			ip_proto_not_sup(mp, ira);
2169 			return;
2170 		}
2171 
2172 		if (ipha->ipha_protocol == IPPROTO_ESP)
2173 			mp = ipsecesp_icmp_error(mp, ira);
2174 		else
2175 			mp = ipsecah_icmp_error(mp, ira);
2176 		if (mp == NULL)
2177 			return;
2178 
2179 		/* Just in case ipsec didn't preserve the NULL b_cont */
2180 		if (mp->b_cont != NULL) {
2181 			if (!pullupmsg(mp, -1))
2182 				goto discard_pkt;
2183 		}
2184 
2185 		/*
2186 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2187 		 * correct, but we don't use them any more here.
2188 		 *
2189 		 * If succesful, the mp has been modified to not include
2190 		 * the ESP/AH header so we can fanout to the ULP's icmp
2191 		 * error handler.
2192 		 */
2193 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2194 			goto truncated;
2195 
2196 		/* Verify the modified message before any further processes. */
2197 		ipha = (ipha_t *)mp->b_rptr;
2198 		hdr_length = IPH_HDR_LENGTH(ipha);
2199 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2200 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2201 			freemsg(mp);
2202 			return;
2203 		}
2204 
2205 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2206 		return;
2207 
2208 	case IPPROTO_ENCAP: {
2209 		/* Look for self-encapsulated packets that caused an error */
2210 		ipha_t *in_ipha;
2211 
2212 		/*
2213 		 * Caller has verified that length has to be
2214 		 * at least the size of IP header.
2215 		 */
2216 		ASSERT(hdr_length >= sizeof (ipha_t));
2217 		/*
2218 		 * Check the sanity of the inner IP header like
2219 		 * we did for the outer header.
2220 		 */
2221 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2222 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2223 			goto discard_pkt;
2224 		}
2225 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2226 			goto discard_pkt;
2227 		}
2228 		/* Check for Self-encapsulated tunnels */
2229 		if (in_ipha->ipha_src == ipha->ipha_src &&
2230 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2231 
2232 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2233 			    in_ipha);
2234 			if (mp == NULL)
2235 				goto discard_pkt;
2236 
2237 			/*
2238 			 * Just in case self_encap didn't preserve the NULL
2239 			 * b_cont
2240 			 */
2241 			if (mp->b_cont != NULL) {
2242 				if (!pullupmsg(mp, -1))
2243 					goto discard_pkt;
2244 			}
2245 			/*
2246 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2247 			 * longer correct, but we don't use them any more here.
2248 			 */
2249 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2250 				goto truncated;
2251 
2252 			/*
2253 			 * Verify the modified message before any further
2254 			 * processes.
2255 			 */
2256 			ipha = (ipha_t *)mp->b_rptr;
2257 			hdr_length = IPH_HDR_LENGTH(ipha);
2258 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2259 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2260 				freemsg(mp);
2261 				return;
2262 			}
2263 
2264 			/*
2265 			 * The packet in error is self-encapsualted.
2266 			 * And we are finding it further encapsulated
2267 			 * which we could not have possibly generated.
2268 			 */
2269 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2270 				goto discard_pkt;
2271 			}
2272 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2273 			return;
2274 		}
2275 		/* No self-encapsulated */
2276 		/* FALLTHRU */
2277 	}
2278 	case IPPROTO_IPV6:
2279 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2280 		    &ripha.ipha_dst, ipst)) != NULL) {
2281 			ira->ira_flags |= IRAF_ICMP_ERROR;
2282 			connp->conn_recvicmp(connp, mp, NULL, ira);
2283 			CONN_DEC_REF(connp);
2284 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2285 			return;
2286 		}
2287 		/*
2288 		 * No IP tunnel is interested, fallthrough and see
2289 		 * if a raw socket will want it.
2290 		 */
2291 		/* FALLTHRU */
2292 	default:
2293 		ira->ira_flags |= IRAF_ICMP_ERROR;
2294 		ip_fanout_proto_v4(mp, &ripha, ira);
2295 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2296 		return;
2297 	}
2298 	/* NOTREACHED */
2299 discard_pkt:
2300 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2301 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2302 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2303 	freemsg(mp);
2304 	return;
2305 
2306 truncated:
2307 	/* We pulled up everthing already. Must be truncated */
2308 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2309 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2310 	freemsg(mp);
2311 }
2312 
2313 /*
2314  * Common IP options parser.
2315  *
2316  * Setup routine: fill in *optp with options-parsing state, then
2317  * tail-call ipoptp_next to return the first option.
2318  */
2319 uint8_t
2320 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2321 {
2322 	uint32_t totallen; /* total length of all options */
2323 
2324 	totallen = ipha->ipha_version_and_hdr_length -
2325 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2326 	totallen <<= 2;
2327 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2328 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2329 	optp->ipoptp_flags = 0;
2330 	return (ipoptp_next(optp));
2331 }
2332 
2333 /* Like above but without an ipha_t */
2334 uint8_t
2335 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2336 {
2337 	optp->ipoptp_next = opt;
2338 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2339 	optp->ipoptp_flags = 0;
2340 	return (ipoptp_next(optp));
2341 }
2342 
2343 /*
2344  * Common IP options parser: extract next option.
2345  */
2346 uint8_t
2347 ipoptp_next(ipoptp_t *optp)
2348 {
2349 	uint8_t *end = optp->ipoptp_end;
2350 	uint8_t *cur = optp->ipoptp_next;
2351 	uint8_t opt, len, pointer;
2352 
2353 	/*
2354 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2355 	 * has been corrupted.
2356 	 */
2357 	ASSERT(cur <= end);
2358 
2359 	if (cur == end)
2360 		return (IPOPT_EOL);
2361 
2362 	opt = cur[IPOPT_OPTVAL];
2363 
2364 	/*
2365 	 * Skip any NOP options.
2366 	 */
2367 	while (opt == IPOPT_NOP) {
2368 		cur++;
2369 		if (cur == end)
2370 			return (IPOPT_EOL);
2371 		opt = cur[IPOPT_OPTVAL];
2372 	}
2373 
2374 	if (opt == IPOPT_EOL)
2375 		return (IPOPT_EOL);
2376 
2377 	/*
2378 	 * Option requiring a length.
2379 	 */
2380 	if ((cur + 1) >= end) {
2381 		optp->ipoptp_flags |= IPOPTP_ERROR;
2382 		return (IPOPT_EOL);
2383 	}
2384 	len = cur[IPOPT_OLEN];
2385 	if (len < 2) {
2386 		optp->ipoptp_flags |= IPOPTP_ERROR;
2387 		return (IPOPT_EOL);
2388 	}
2389 	optp->ipoptp_cur = cur;
2390 	optp->ipoptp_len = len;
2391 	optp->ipoptp_next = cur + len;
2392 	if (cur + len > end) {
2393 		optp->ipoptp_flags |= IPOPTP_ERROR;
2394 		return (IPOPT_EOL);
2395 	}
2396 
2397 	/*
2398 	 * For the options which require a pointer field, make sure
2399 	 * its there, and make sure it points to either something
2400 	 * inside this option, or the end of the option.
2401 	 */
2402 	switch (opt) {
2403 	case IPOPT_RR:
2404 	case IPOPT_TS:
2405 	case IPOPT_LSRR:
2406 	case IPOPT_SSRR:
2407 		if (len <= IPOPT_OFFSET) {
2408 			optp->ipoptp_flags |= IPOPTP_ERROR;
2409 			return (opt);
2410 		}
2411 		pointer = cur[IPOPT_OFFSET];
2412 		if (pointer - 1 > len) {
2413 			optp->ipoptp_flags |= IPOPTP_ERROR;
2414 			return (opt);
2415 		}
2416 		break;
2417 	}
2418 
2419 	/*
2420 	 * Sanity check the pointer field based on the type of the
2421 	 * option.
2422 	 */
2423 	switch (opt) {
2424 	case IPOPT_RR:
2425 	case IPOPT_SSRR:
2426 	case IPOPT_LSRR:
2427 		if (pointer < IPOPT_MINOFF_SR)
2428 			optp->ipoptp_flags |= IPOPTP_ERROR;
2429 		break;
2430 	case IPOPT_TS:
2431 		if (pointer < IPOPT_MINOFF_IT)
2432 			optp->ipoptp_flags |= IPOPTP_ERROR;
2433 		/*
2434 		 * Note that the Internet Timestamp option also
2435 		 * contains two four bit fields (the Overflow field,
2436 		 * and the Flag field), which follow the pointer
2437 		 * field.  We don't need to check that these fields
2438 		 * fall within the length of the option because this
2439 		 * was implicitely done above.  We've checked that the
2440 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2441 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2442 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2443 		 */
2444 		ASSERT(len > IPOPT_POS_OV_FLG);
2445 		break;
2446 	}
2447 
2448 	return (opt);
2449 }
2450 
2451 /*
2452  * Use the outgoing IP header to create an IP_OPTIONS option the way
2453  * it was passed down from the application.
2454  *
2455  * This is compatible with BSD in that it returns
2456  * the reverse source route with the final destination
2457  * as the last entry. The first 4 bytes of the option
2458  * will contain the final destination.
2459  */
2460 int
2461 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2462 {
2463 	ipoptp_t	opts;
2464 	uchar_t		*opt;
2465 	uint8_t		optval;
2466 	uint8_t		optlen;
2467 	uint32_t	len = 0;
2468 	uchar_t		*buf1 = buf;
2469 	uint32_t	totallen;
2470 	ipaddr_t	dst;
2471 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2472 
2473 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2474 		return (0);
2475 
2476 	totallen = ipp->ipp_ipv4_options_len;
2477 	if (totallen & 0x3)
2478 		return (0);
2479 
2480 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2481 	len += IP_ADDR_LEN;
2482 	bzero(buf1, IP_ADDR_LEN);
2483 
2484 	dst = connp->conn_faddr_v4;
2485 
2486 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2487 	    optval != IPOPT_EOL;
2488 	    optval = ipoptp_next(&opts)) {
2489 		int	off;
2490 
2491 		opt = opts.ipoptp_cur;
2492 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2493 			break;
2494 		}
2495 		optlen = opts.ipoptp_len;
2496 
2497 		switch (optval) {
2498 		case IPOPT_SSRR:
2499 		case IPOPT_LSRR:
2500 
2501 			/*
2502 			 * Insert destination as the first entry in the source
2503 			 * route and move down the entries on step.
2504 			 * The last entry gets placed at buf1.
2505 			 */
2506 			buf[IPOPT_OPTVAL] = optval;
2507 			buf[IPOPT_OLEN] = optlen;
2508 			buf[IPOPT_OFFSET] = optlen;
2509 
2510 			off = optlen - IP_ADDR_LEN;
2511 			if (off < 0) {
2512 				/* No entries in source route */
2513 				break;
2514 			}
2515 			/* Last entry in source route if not already set */
2516 			if (dst == INADDR_ANY)
2517 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2518 			off -= IP_ADDR_LEN;
2519 
2520 			while (off > 0) {
2521 				bcopy(opt + off,
2522 				    buf + off + IP_ADDR_LEN,
2523 				    IP_ADDR_LEN);
2524 				off -= IP_ADDR_LEN;
2525 			}
2526 			/* ipha_dst into first slot */
2527 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2528 			    IP_ADDR_LEN);
2529 			buf += optlen;
2530 			len += optlen;
2531 			break;
2532 
2533 		default:
2534 			bcopy(opt, buf, optlen);
2535 			buf += optlen;
2536 			len += optlen;
2537 			break;
2538 		}
2539 	}
2540 done:
2541 	/* Pad the resulting options */
2542 	while (len & 0x3) {
2543 		*buf++ = IPOPT_EOL;
2544 		len++;
2545 	}
2546 	return (len);
2547 }
2548 
2549 /*
2550  * Update any record route or timestamp options to include this host.
2551  * Reverse any source route option.
2552  * This routine assumes that the options are well formed i.e. that they
2553  * have already been checked.
2554  */
2555 static void
2556 icmp_options_update(ipha_t *ipha)
2557 {
2558 	ipoptp_t	opts;
2559 	uchar_t		*opt;
2560 	uint8_t		optval;
2561 	ipaddr_t	src;		/* Our local address */
2562 	ipaddr_t	dst;
2563 
2564 	ip2dbg(("icmp_options_update\n"));
2565 	src = ipha->ipha_src;
2566 	dst = ipha->ipha_dst;
2567 
2568 	for (optval = ipoptp_first(&opts, ipha);
2569 	    optval != IPOPT_EOL;
2570 	    optval = ipoptp_next(&opts)) {
2571 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2572 		opt = opts.ipoptp_cur;
2573 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2574 		    optval, opts.ipoptp_len));
2575 		switch (optval) {
2576 			int off1, off2;
2577 		case IPOPT_SSRR:
2578 		case IPOPT_LSRR:
2579 			/*
2580 			 * Reverse the source route.  The first entry
2581 			 * should be the next to last one in the current
2582 			 * source route (the last entry is our address).
2583 			 * The last entry should be the final destination.
2584 			 */
2585 			off1 = IPOPT_MINOFF_SR - 1;
2586 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2587 			if (off2 < 0) {
2588 				/* No entries in source route */
2589 				ip1dbg((
2590 				    "icmp_options_update: bad src route\n"));
2591 				break;
2592 			}
2593 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2594 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2595 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2596 			off2 -= IP_ADDR_LEN;
2597 
2598 			while (off1 < off2) {
2599 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2600 				bcopy((char *)opt + off2, (char *)opt + off1,
2601 				    IP_ADDR_LEN);
2602 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2603 				off1 += IP_ADDR_LEN;
2604 				off2 -= IP_ADDR_LEN;
2605 			}
2606 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2607 			break;
2608 		}
2609 	}
2610 }
2611 
2612 /*
2613  * Process received ICMP Redirect messages.
2614  * Assumes the caller has verified that the headers are in the pulled up mblk.
2615  * Consumes mp.
2616  */
2617 static void
2618 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2619 {
2620 	ire_t		*ire, *nire;
2621 	ire_t		*prev_ire;
2622 	ipaddr_t  	src, dst, gateway;
2623 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2624 	ipha_t		*inner_ipha;	/* Inner IP header */
2625 
2626 	/* Caller already pulled up everything. */
2627 	inner_ipha = (ipha_t *)&icmph[1];
2628 	src = ipha->ipha_src;
2629 	dst = inner_ipha->ipha_dst;
2630 	gateway = icmph->icmph_rd_gateway;
2631 	/* Make sure the new gateway is reachable somehow. */
2632 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2633 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2634 	/*
2635 	 * Make sure we had a route for the dest in question and that
2636 	 * that route was pointing to the old gateway (the source of the
2637 	 * redirect packet.)
2638 	 * We do longest match and then compare ire_gateway_addr below.
2639 	 */
2640 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2641 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2642 	/*
2643 	 * Check that
2644 	 *	the redirect was not from ourselves
2645 	 *	the new gateway and the old gateway are directly reachable
2646 	 */
2647 	if (prev_ire == NULL || ire == NULL ||
2648 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2649 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2650 	    !(ire->ire_type & IRE_IF_ALL) ||
2651 	    prev_ire->ire_gateway_addr != src) {
2652 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2653 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2654 		freemsg(mp);
2655 		if (ire != NULL)
2656 			ire_refrele(ire);
2657 		if (prev_ire != NULL)
2658 			ire_refrele(prev_ire);
2659 		return;
2660 	}
2661 
2662 	ire_refrele(prev_ire);
2663 	ire_refrele(ire);
2664 
2665 	/*
2666 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2667 	 * require TOS routing
2668 	 */
2669 	switch (icmph->icmph_code) {
2670 	case 0:
2671 	case 1:
2672 		/* TODO: TOS specificity for cases 2 and 3 */
2673 	case 2:
2674 	case 3:
2675 		break;
2676 	default:
2677 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2678 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2679 		freemsg(mp);
2680 		return;
2681 	}
2682 	/*
2683 	 * Create a Route Association.  This will allow us to remember that
2684 	 * someone we believe told us to use the particular gateway.
2685 	 */
2686 	ire = ire_create(
2687 	    (uchar_t *)&dst,			/* dest addr */
2688 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2689 	    (uchar_t *)&gateway,		/* gateway addr */
2690 	    IRE_HOST,
2691 	    NULL,				/* ill */
2692 	    ALL_ZONES,
2693 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2694 	    NULL,				/* tsol_gc_t */
2695 	    ipst);
2696 
2697 	if (ire == NULL) {
2698 		freemsg(mp);
2699 		return;
2700 	}
2701 	nire = ire_add(ire);
2702 	/* Check if it was a duplicate entry */
2703 	if (nire != NULL && nire != ire) {
2704 		ASSERT(nire->ire_identical_ref > 1);
2705 		ire_delete(nire);
2706 		ire_refrele(nire);
2707 		nire = NULL;
2708 	}
2709 	ire = nire;
2710 	if (ire != NULL) {
2711 		ire_refrele(ire);		/* Held in ire_add */
2712 
2713 		/* tell routing sockets that we received a redirect */
2714 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2715 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2716 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2717 	}
2718 
2719 	/*
2720 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2721 	 * This together with the added IRE has the effect of
2722 	 * modifying an existing redirect.
2723 	 */
2724 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2725 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2726 	if (prev_ire != NULL) {
2727 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2728 			ire_delete(prev_ire);
2729 		ire_refrele(prev_ire);
2730 	}
2731 
2732 	freemsg(mp);
2733 }
2734 
2735 /*
2736  * Generate an ICMP parameter problem message.
2737  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2738  * constructed by the caller.
2739  */
2740 static void
2741 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2742 {
2743 	icmph_t	icmph;
2744 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2745 
2746 	mp = icmp_pkt_err_ok(mp, ira);
2747 	if (mp == NULL)
2748 		return;
2749 
2750 	bzero(&icmph, sizeof (icmph_t));
2751 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2752 	icmph.icmph_pp_ptr = ptr;
2753 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2754 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2755 }
2756 
2757 /*
2758  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2759  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2760  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2761  * an icmp error packet can be sent.
2762  * Assigns an appropriate source address to the packet. If ipha_dst is
2763  * one of our addresses use it for source. Otherwise let ip_output_simple
2764  * pick the source address.
2765  */
2766 static void
2767 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2768 {
2769 	ipaddr_t dst;
2770 	icmph_t	*icmph;
2771 	ipha_t	*ipha;
2772 	uint_t	len_needed;
2773 	size_t	msg_len;
2774 	mblk_t	*mp1;
2775 	ipaddr_t src;
2776 	ire_t	*ire;
2777 	ip_xmit_attr_t ixas;
2778 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2779 
2780 	ipha = (ipha_t *)mp->b_rptr;
2781 
2782 	bzero(&ixas, sizeof (ixas));
2783 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2784 	ixas.ixa_zoneid = ira->ira_zoneid;
2785 	ixas.ixa_ifindex = 0;
2786 	ixas.ixa_ipst = ipst;
2787 	ixas.ixa_cred = kcred;
2788 	ixas.ixa_cpid = NOPID;
2789 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2790 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2791 
2792 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2793 		/*
2794 		 * Apply IPsec based on how IPsec was applied to
2795 		 * the packet that had the error.
2796 		 *
2797 		 * If it was an outbound packet that caused the ICMP
2798 		 * error, then the caller will have setup the IRA
2799 		 * appropriately.
2800 		 */
2801 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2802 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2803 			/* Note: mp already consumed and ip_drop_packet done */
2804 			return;
2805 		}
2806 	} else {
2807 		/*
2808 		 * This is in clear. The icmp message we are building
2809 		 * here should go out in clear, independent of our policy.
2810 		 */
2811 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2812 	}
2813 
2814 	/* Remember our eventual destination */
2815 	dst = ipha->ipha_src;
2816 
2817 	/*
2818 	 * If the packet was for one of our unicast addresses, make
2819 	 * sure we respond with that as the source. Otherwise
2820 	 * have ip_output_simple pick the source address.
2821 	 */
2822 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2823 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2824 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2825 	if (ire != NULL) {
2826 		ire_refrele(ire);
2827 		src = ipha->ipha_dst;
2828 	} else {
2829 		src = INADDR_ANY;
2830 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2831 	}
2832 
2833 	/*
2834 	 * Check if we can send back more then 8 bytes in addition to
2835 	 * the IP header.  We try to send 64 bytes of data and the internal
2836 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2837 	 */
2838 	len_needed = IPH_HDR_LENGTH(ipha);
2839 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2840 	    ipha->ipha_protocol == IPPROTO_IPV6) {
2841 		if (!pullupmsg(mp, -1)) {
2842 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2843 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2844 			freemsg(mp);
2845 			return;
2846 		}
2847 		ipha = (ipha_t *)mp->b_rptr;
2848 
2849 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2850 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2851 			    len_needed));
2852 		} else {
2853 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2854 
2855 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2856 			len_needed += ip_hdr_length_v6(mp, ip6h);
2857 		}
2858 	}
2859 	len_needed += ipst->ips_ip_icmp_return;
2860 	msg_len = msgdsize(mp);
2861 	if (msg_len > len_needed) {
2862 		(void) adjmsg(mp, len_needed - msg_len);
2863 		msg_len = len_needed;
2864 	}
2865 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2866 	if (mp1 == NULL) {
2867 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2868 		freemsg(mp);
2869 		return;
2870 	}
2871 	mp1->b_cont = mp;
2872 	mp = mp1;
2873 
2874 	/*
2875 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2876 	 * node generates be accepted in peace by all on-host destinations.
2877 	 * If we do NOT assume that all on-host destinations trust
2878 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2879 	 * (Look for IXAF_TRUSTED_ICMP).
2880 	 */
2881 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2882 
2883 	ipha = (ipha_t *)mp->b_rptr;
2884 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2885 	*ipha = icmp_ipha;
2886 	ipha->ipha_src = src;
2887 	ipha->ipha_dst = dst;
2888 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2889 	msg_len += sizeof (icmp_ipha) + len;
2890 	if (msg_len > IP_MAXPACKET) {
2891 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
2892 		msg_len = IP_MAXPACKET;
2893 	}
2894 	ipha->ipha_length = htons((uint16_t)msg_len);
2895 	icmph = (icmph_t *)&ipha[1];
2896 	bcopy(stuff, icmph, len);
2897 	icmph->icmph_checksum = 0;
2898 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2899 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2900 
2901 	(void) ip_output_simple(mp, &ixas);
2902 	ixa_cleanup(&ixas);
2903 }
2904 
2905 /*
2906  * Determine if an ICMP error packet can be sent given the rate limit.
2907  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2908  * in milliseconds) and a burst size. Burst size number of packets can
2909  * be sent arbitrarely closely spaced.
2910  * The state is tracked using two variables to implement an approximate
2911  * token bucket filter:
2912  *	icmp_pkt_err_last - lbolt value when the last burst started
2913  *	icmp_pkt_err_sent - number of packets sent in current burst
2914  */
2915 boolean_t
2916 icmp_err_rate_limit(ip_stack_t *ipst)
2917 {
2918 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2919 	uint_t refilled; /* Number of packets refilled in tbf since last */
2920 	/* Guard against changes by loading into local variable */
2921 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2922 
2923 	if (err_interval == 0)
2924 		return (B_FALSE);
2925 
2926 	if (ipst->ips_icmp_pkt_err_last > now) {
2927 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2928 		ipst->ips_icmp_pkt_err_last = 0;
2929 		ipst->ips_icmp_pkt_err_sent = 0;
2930 	}
2931 	/*
2932 	 * If we are in a burst update the token bucket filter.
2933 	 * Update the "last" time to be close to "now" but make sure
2934 	 * we don't loose precision.
2935 	 */
2936 	if (ipst->ips_icmp_pkt_err_sent != 0) {
2937 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2938 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
2939 			ipst->ips_icmp_pkt_err_sent = 0;
2940 		} else {
2941 			ipst->ips_icmp_pkt_err_sent -= refilled;
2942 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2943 		}
2944 	}
2945 	if (ipst->ips_icmp_pkt_err_sent == 0) {
2946 		/* Start of new burst */
2947 		ipst->ips_icmp_pkt_err_last = now;
2948 	}
2949 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2950 		ipst->ips_icmp_pkt_err_sent++;
2951 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2952 		    ipst->ips_icmp_pkt_err_sent));
2953 		return (B_FALSE);
2954 	}
2955 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
2956 	return (B_TRUE);
2957 }
2958 
2959 /*
2960  * Check if it is ok to send an IPv4 ICMP error packet in
2961  * response to the IPv4 packet in mp.
2962  * Free the message and return null if no
2963  * ICMP error packet should be sent.
2964  */
2965 static mblk_t *
2966 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2967 {
2968 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2969 	icmph_t	*icmph;
2970 	ipha_t	*ipha;
2971 	uint_t	len_needed;
2972 
2973 	if (!mp)
2974 		return (NULL);
2975 	ipha = (ipha_t *)mp->b_rptr;
2976 	if (ip_csum_hdr(ipha)) {
2977 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2978 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2979 		freemsg(mp);
2980 		return (NULL);
2981 	}
2982 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2983 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2984 	    CLASSD(ipha->ipha_dst) ||
2985 	    CLASSD(ipha->ipha_src) ||
2986 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2987 		/* Note: only errors to the fragment with offset 0 */
2988 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2989 		freemsg(mp);
2990 		return (NULL);
2991 	}
2992 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
2993 		/*
2994 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
2995 		 * errors in response to any ICMP errors.
2996 		 */
2997 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
2998 		if (mp->b_wptr - mp->b_rptr < len_needed) {
2999 			if (!pullupmsg(mp, len_needed)) {
3000 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3001 				freemsg(mp);
3002 				return (NULL);
3003 			}
3004 			ipha = (ipha_t *)mp->b_rptr;
3005 		}
3006 		icmph = (icmph_t *)
3007 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3008 		switch (icmph->icmph_type) {
3009 		case ICMP_DEST_UNREACHABLE:
3010 		case ICMP_SOURCE_QUENCH:
3011 		case ICMP_TIME_EXCEEDED:
3012 		case ICMP_PARAM_PROBLEM:
3013 		case ICMP_REDIRECT:
3014 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3015 			freemsg(mp);
3016 			return (NULL);
3017 		default:
3018 			break;
3019 		}
3020 	}
3021 	/*
3022 	 * If this is a labeled system, then check to see if we're allowed to
3023 	 * send a response to this particular sender.  If not, then just drop.
3024 	 */
3025 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3026 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3027 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3028 		freemsg(mp);
3029 		return (NULL);
3030 	}
3031 	if (icmp_err_rate_limit(ipst)) {
3032 		/*
3033 		 * Only send ICMP error packets every so often.
3034 		 * This should be done on a per port/source basis,
3035 		 * but for now this will suffice.
3036 		 */
3037 		freemsg(mp);
3038 		return (NULL);
3039 	}
3040 	return (mp);
3041 }
3042 
3043 /*
3044  * Called when a packet was sent out the same link that it arrived on.
3045  * Check if it is ok to send a redirect and then send it.
3046  */
3047 void
3048 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3049     ip_recv_attr_t *ira)
3050 {
3051 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3052 	ipaddr_t	src, nhop;
3053 	mblk_t		*mp1;
3054 	ire_t		*nhop_ire;
3055 
3056 	/*
3057 	 * Check the source address to see if it originated
3058 	 * on the same logical subnet it is going back out on.
3059 	 * If so, we should be able to send it a redirect.
3060 	 * Avoid sending a redirect if the destination
3061 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3062 	 * or if the packet was source routed out this interface.
3063 	 *
3064 	 * We avoid sending a redirect if the
3065 	 * destination is directly connected
3066 	 * because it is possible that multiple
3067 	 * IP subnets may have been configured on
3068 	 * the link, and the source may not
3069 	 * be on the same subnet as ip destination,
3070 	 * even though they are on the same
3071 	 * physical link.
3072 	 */
3073 	if ((ire->ire_type & IRE_ONLINK) ||
3074 	    ip_source_routed(ipha, ipst))
3075 		return;
3076 
3077 	nhop_ire = ire_nexthop(ire);
3078 	if (nhop_ire == NULL)
3079 		return;
3080 
3081 	nhop = nhop_ire->ire_addr;
3082 
3083 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3084 		ire_t	*ire2;
3085 
3086 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3087 		mutex_enter(&nhop_ire->ire_lock);
3088 		ire2 = nhop_ire->ire_dep_parent;
3089 		if (ire2 != NULL)
3090 			ire_refhold(ire2);
3091 		mutex_exit(&nhop_ire->ire_lock);
3092 		ire_refrele(nhop_ire);
3093 		nhop_ire = ire2;
3094 	}
3095 	if (nhop_ire == NULL)
3096 		return;
3097 
3098 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3099 
3100 	src = ipha->ipha_src;
3101 
3102 	/*
3103 	 * We look at the interface ire for the nexthop,
3104 	 * to see if ipha_src is in the same subnet
3105 	 * as the nexthop.
3106 	 */
3107 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3108 		/*
3109 		 * The source is directly connected.
3110 		 */
3111 		mp1 = copymsg(mp);
3112 		if (mp1 != NULL) {
3113 			icmp_send_redirect(mp1, nhop, ira);
3114 		}
3115 	}
3116 	ire_refrele(nhop_ire);
3117 }
3118 
3119 /*
3120  * Generate an ICMP redirect message.
3121  */
3122 static void
3123 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3124 {
3125 	icmph_t	icmph;
3126 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3127 
3128 	mp = icmp_pkt_err_ok(mp, ira);
3129 	if (mp == NULL)
3130 		return;
3131 
3132 	bzero(&icmph, sizeof (icmph_t));
3133 	icmph.icmph_type = ICMP_REDIRECT;
3134 	icmph.icmph_code = 1;
3135 	icmph.icmph_rd_gateway = gateway;
3136 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3137 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3138 }
3139 
3140 /*
3141  * Generate an ICMP time exceeded message.
3142  */
3143 void
3144 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3145 {
3146 	icmph_t	icmph;
3147 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3148 
3149 	mp = icmp_pkt_err_ok(mp, ira);
3150 	if (mp == NULL)
3151 		return;
3152 
3153 	bzero(&icmph, sizeof (icmph_t));
3154 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3155 	icmph.icmph_code = code;
3156 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3157 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3158 }
3159 
3160 /*
3161  * Generate an ICMP unreachable message.
3162  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3163  * constructed by the caller.
3164  */
3165 void
3166 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3167 {
3168 	icmph_t	icmph;
3169 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3170 
3171 	mp = icmp_pkt_err_ok(mp, ira);
3172 	if (mp == NULL)
3173 		return;
3174 
3175 	bzero(&icmph, sizeof (icmph_t));
3176 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3177 	icmph.icmph_code = code;
3178 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3179 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3180 }
3181 
3182 /*
3183  * Latch in the IPsec state for a stream based the policy in the listener
3184  * and the actions in the ip_recv_attr_t.
3185  * Called directly from TCP and SCTP.
3186  */
3187 boolean_t
3188 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3189 {
3190 	ASSERT(lconnp->conn_policy != NULL);
3191 	ASSERT(connp->conn_policy == NULL);
3192 
3193 	IPPH_REFHOLD(lconnp->conn_policy);
3194 	connp->conn_policy = lconnp->conn_policy;
3195 
3196 	if (ira->ira_ipsec_action != NULL) {
3197 		if (connp->conn_latch == NULL) {
3198 			connp->conn_latch = iplatch_create();
3199 			if (connp->conn_latch == NULL)
3200 				return (B_FALSE);
3201 		}
3202 		ipsec_latch_inbound(connp, ira);
3203 	}
3204 	return (B_TRUE);
3205 }
3206 
3207 /*
3208  * Verify whether or not the IP address is a valid local address.
3209  * Could be a unicast, including one for a down interface.
3210  * If allow_mcbc then a multicast or broadcast address is also
3211  * acceptable.
3212  *
3213  * In the case of a broadcast/multicast address, however, the
3214  * upper protocol is expected to reset the src address
3215  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3216  * no packets are emitted with broadcast/multicast address as
3217  * source address (that violates hosts requirements RFC 1122)
3218  * The addresses valid for bind are:
3219  *	(1) - INADDR_ANY (0)
3220  *	(2) - IP address of an UP interface
3221  *	(3) - IP address of a DOWN interface
3222  *	(4) - valid local IP broadcast addresses. In this case
3223  *	the conn will only receive packets destined to
3224  *	the specified broadcast address.
3225  *	(5) - a multicast address. In this case
3226  *	the conn will only receive packets destined to
3227  *	the specified multicast address. Note: the
3228  *	application still has to issue an
3229  *	IP_ADD_MEMBERSHIP socket option.
3230  *
3231  * In all the above cases, the bound address must be valid in the current zone.
3232  * When the address is loopback, multicast or broadcast, there might be many
3233  * matching IREs so bind has to look up based on the zone.
3234  */
3235 ip_laddr_t
3236 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3237     ip_stack_t *ipst, boolean_t allow_mcbc)
3238 {
3239 	ire_t *src_ire;
3240 
3241 	ASSERT(src_addr != INADDR_ANY);
3242 
3243 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3244 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3245 
3246 	/*
3247 	 * If an address other than in6addr_any is requested,
3248 	 * we verify that it is a valid address for bind
3249 	 * Note: Following code is in if-else-if form for
3250 	 * readability compared to a condition check.
3251 	 */
3252 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3253 		/*
3254 		 * (2) Bind to address of local UP interface
3255 		 */
3256 		ire_refrele(src_ire);
3257 		return (IPVL_UNICAST_UP);
3258 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3259 		/*
3260 		 * (4) Bind to broadcast address
3261 		 */
3262 		ire_refrele(src_ire);
3263 		if (allow_mcbc)
3264 			return (IPVL_BCAST);
3265 		else
3266 			return (IPVL_BAD);
3267 	} else if (CLASSD(src_addr)) {
3268 		/* (5) bind to multicast address. */
3269 		if (src_ire != NULL)
3270 			ire_refrele(src_ire);
3271 
3272 		if (allow_mcbc)
3273 			return (IPVL_MCAST);
3274 		else
3275 			return (IPVL_BAD);
3276 	} else {
3277 		ipif_t *ipif;
3278 
3279 		/*
3280 		 * (3) Bind to address of local DOWN interface?
3281 		 * (ipif_lookup_addr() looks up all interfaces
3282 		 * but we do not get here for UP interfaces
3283 		 * - case (2) above)
3284 		 */
3285 		if (src_ire != NULL)
3286 			ire_refrele(src_ire);
3287 
3288 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3289 		if (ipif == NULL)
3290 			return (IPVL_BAD);
3291 
3292 		/* Not a useful source? */
3293 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3294 			ipif_refrele(ipif);
3295 			return (IPVL_BAD);
3296 		}
3297 		ipif_refrele(ipif);
3298 		return (IPVL_UNICAST_DOWN);
3299 	}
3300 }
3301 
3302 /*
3303  * Insert in the bind fanout for IPv4 and IPv6.
3304  * The caller should already have used ip_laddr_verify_v*() before calling
3305  * this.
3306  */
3307 int
3308 ip_laddr_fanout_insert(conn_t *connp)
3309 {
3310 	int		error;
3311 
3312 	/*
3313 	 * Allow setting new policies. For example, disconnects result
3314 	 * in us being called. As we would have set conn_policy_cached
3315 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3316 	 * can change after the disconnect.
3317 	 */
3318 	connp->conn_policy_cached = B_FALSE;
3319 
3320 	error = ipcl_bind_insert(connp);
3321 	if (error != 0) {
3322 		if (connp->conn_anon_port) {
3323 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3324 			    connp->conn_mlp_type, connp->conn_proto,
3325 			    ntohs(connp->conn_lport), B_FALSE);
3326 		}
3327 		connp->conn_mlp_type = mlptSingle;
3328 	}
3329 	return (error);
3330 }
3331 
3332 /*
3333  * Verify that both the source and destination addresses are valid. If
3334  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3335  * i.e. have no route to it.  Protocols like TCP want to verify destination
3336  * reachability, while tunnels do not.
3337  *
3338  * Determine the route, the interface, and (optionally) the source address
3339  * to use to reach a given destination.
3340  * Note that we allow connect to broadcast and multicast addresses when
3341  * IPDF_ALLOW_MCBC is set.
3342  * first_hop and dst_addr are normally the same, but if source routing
3343  * they will differ; in that case the first_hop is what we'll use for the
3344  * routing lookup but the dce and label checks will be done on dst_addr,
3345  *
3346  * If uinfo is set, then we fill in the best available information
3347  * we have for the destination. This is based on (in priority order) any
3348  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3349  * ill_mtu.
3350  *
3351  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3352  * always do the label check on dst_addr.
3353  */
3354 int
3355 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3356     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3357 {
3358 	ire_t		*ire = NULL;
3359 	int		error = 0;
3360 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3361 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3362 	ip_stack_t	*ipst = ixa->ixa_ipst;
3363 	dce_t		*dce;
3364 	uint_t		pmtu;
3365 	uint_t		generation;
3366 	nce_t		*nce;
3367 	ill_t		*ill = NULL;
3368 	boolean_t	multirt = B_FALSE;
3369 
3370 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3371 
3372 	/*
3373 	 * We never send to zero; the ULPs map it to the loopback address.
3374 	 * We can't allow it since we use zero to mean unitialized in some
3375 	 * places.
3376 	 */
3377 	ASSERT(dst_addr != INADDR_ANY);
3378 
3379 	if (is_system_labeled()) {
3380 		ts_label_t *tsl = NULL;
3381 
3382 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3383 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3384 		if (error != 0)
3385 			return (error);
3386 		if (tsl != NULL) {
3387 			/* Update the label */
3388 			ip_xmit_attr_replace_tsl(ixa, tsl);
3389 		}
3390 	}
3391 
3392 	setsrc = INADDR_ANY;
3393 	/*
3394 	 * Select a route; For IPMP interfaces, we would only select
3395 	 * a "hidden" route (i.e., going through a specific under_ill)
3396 	 * if ixa_ifindex has been specified.
3397 	 */
3398 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3399 	    &generation, &setsrc, &error, &multirt);
3400 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3401 	if (error != 0)
3402 		goto bad_addr;
3403 
3404 	/*
3405 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3406 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3407 	 * Otherwise the destination needn't be reachable.
3408 	 *
3409 	 * If we match on a reject or black hole, then we've got a
3410 	 * local failure.  May as well fail out the connect() attempt,
3411 	 * since it's never going to succeed.
3412 	 */
3413 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3414 		/*
3415 		 * If we're verifying destination reachability, we always want
3416 		 * to complain here.
3417 		 *
3418 		 * If we're not verifying destination reachability but the
3419 		 * destination has a route, we still want to fail on the
3420 		 * temporary address and broadcast address tests.
3421 		 *
3422 		 * In both cases do we let the code continue so some reasonable
3423 		 * information is returned to the caller. That enables the
3424 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3425 		 * use the generation mismatch path to check for the unreachable
3426 		 * case thereby avoiding any specific check in the main path.
3427 		 */
3428 		ASSERT(generation == IRE_GENERATION_VERIFY);
3429 		if (flags & IPDF_VERIFY_DST) {
3430 			/*
3431 			 * Set errno but continue to set up ixa_ire to be
3432 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3433 			 * That allows callers to use ip_output to get an
3434 			 * ICMP error back.
3435 			 */
3436 			if (!(ire->ire_type & IRE_HOST))
3437 				error = ENETUNREACH;
3438 			else
3439 				error = EHOSTUNREACH;
3440 		}
3441 	}
3442 
3443 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3444 	    !(flags & IPDF_ALLOW_MCBC)) {
3445 		ire_refrele(ire);
3446 		ire = ire_reject(ipst, B_FALSE);
3447 		generation = IRE_GENERATION_VERIFY;
3448 		error = ENETUNREACH;
3449 	}
3450 
3451 	/* Cache things */
3452 	if (ixa->ixa_ire != NULL)
3453 		ire_refrele_notr(ixa->ixa_ire);
3454 #ifdef DEBUG
3455 	ire_refhold_notr(ire);
3456 	ire_refrele(ire);
3457 #endif
3458 	ixa->ixa_ire = ire;
3459 	ixa->ixa_ire_generation = generation;
3460 
3461 	/*
3462 	 * For multicast with multirt we have a flag passed back from
3463 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3464 	 * possible multicast address.
3465 	 * We also need a flag for multicast since we can't check
3466 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3467 	 */
3468 	if (multirt) {
3469 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3470 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3471 	} else {
3472 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3473 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3474 	}
3475 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3476 		/* Get an nce to cache. */
3477 		nce = ire_to_nce(ire, firsthop, NULL);
3478 		if (nce == NULL) {
3479 			/* Allocation failure? */
3480 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3481 		} else {
3482 			if (ixa->ixa_nce != NULL)
3483 				nce_refrele(ixa->ixa_nce);
3484 			ixa->ixa_nce = nce;
3485 		}
3486 	}
3487 
3488 	/*
3489 	 * If the source address is a loopback address, the
3490 	 * destination had best be local or multicast.
3491 	 * If we are sending to an IRE_LOCAL using a loopback source then
3492 	 * it had better be the same zoneid.
3493 	 */
3494 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3495 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3496 			ire = NULL;	/* Stored in ixa_ire */
3497 			error = EADDRNOTAVAIL;
3498 			goto bad_addr;
3499 		}
3500 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3501 			ire = NULL;	/* Stored in ixa_ire */
3502 			error = EADDRNOTAVAIL;
3503 			goto bad_addr;
3504 		}
3505 	}
3506 	if (ire->ire_type & IRE_BROADCAST) {
3507 		/*
3508 		 * If the ULP didn't have a specified source, then we
3509 		 * make sure we reselect the source when sending
3510 		 * broadcasts out different interfaces.
3511 		 */
3512 		if (flags & IPDF_SELECT_SRC)
3513 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3514 		else
3515 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3516 	}
3517 
3518 	/*
3519 	 * Does the caller want us to pick a source address?
3520 	 */
3521 	if (flags & IPDF_SELECT_SRC) {
3522 		ipaddr_t	src_addr;
3523 
3524 		/*
3525 		 * We use use ire_nexthop_ill to avoid the under ipmp
3526 		 * interface for source address selection. Note that for ipmp
3527 		 * probe packets, ixa_ifindex would have been specified, and
3528 		 * the ip_select_route() invocation would have picked an ire
3529 		 * will ire_ill pointing at an under interface.
3530 		 */
3531 		ill = ire_nexthop_ill(ire);
3532 
3533 		/* If unreachable we have no ill but need some source */
3534 		if (ill == NULL) {
3535 			src_addr = htonl(INADDR_LOOPBACK);
3536 			/* Make sure we look for a better source address */
3537 			generation = SRC_GENERATION_VERIFY;
3538 		} else {
3539 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3540 			    ixa->ixa_multicast_ifaddr, zoneid,
3541 			    ipst, &src_addr, &generation, NULL);
3542 			if (error != 0) {
3543 				ire = NULL;	/* Stored in ixa_ire */
3544 				goto bad_addr;
3545 			}
3546 		}
3547 
3548 		/*
3549 		 * We allow the source address to to down.
3550 		 * However, we check that we don't use the loopback address
3551 		 * as a source when sending out on the wire.
3552 		 */
3553 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3554 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3555 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3556 			ire = NULL;	/* Stored in ixa_ire */
3557 			error = EADDRNOTAVAIL;
3558 			goto bad_addr;
3559 		}
3560 
3561 		*src_addrp = src_addr;
3562 		ixa->ixa_src_generation = generation;
3563 	}
3564 
3565 	if (flags & IPDF_UNIQUE_DCE) {
3566 		/* Fallback to the default dce if allocation fails */
3567 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3568 		if (dce != NULL)
3569 			generation = dce->dce_generation;
3570 		else
3571 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3572 	} else {
3573 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3574 	}
3575 	ASSERT(dce != NULL);
3576 	if (ixa->ixa_dce != NULL)
3577 		dce_refrele_notr(ixa->ixa_dce);
3578 #ifdef DEBUG
3579 	dce_refhold_notr(dce);
3580 	dce_refrele(dce);
3581 #endif
3582 	ixa->ixa_dce = dce;
3583 	ixa->ixa_dce_generation = generation;
3584 
3585 	/*
3586 	 * Make sure we don't leave an unreachable ixa_nce in place
3587 	 * since ip_select_route is used when we unplumb i.e., remove
3588 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3589 	 */
3590 	nce = ixa->ixa_nce;
3591 	if (nce != NULL && nce->nce_is_condemned) {
3592 		nce_refrele(nce);
3593 		ixa->ixa_nce = NULL;
3594 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3595 	}
3596 
3597 	/*
3598 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3599 	 * However, we can't do it for IPv4 multicast or broadcast.
3600 	 */
3601 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3602 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3603 
3604 	/*
3605 	 * Set initial value for fragmentation limit. Either conn_ip_output
3606 	 * or ULP might updates it when there are routing changes.
3607 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3608 	 */
3609 	pmtu = ip_get_pmtu(ixa);
3610 	ixa->ixa_fragsize = pmtu;
3611 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3612 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3613 		ixa->ixa_pmtu = pmtu;
3614 
3615 	/*
3616 	 * Extract information useful for some transports.
3617 	 * First we look for DCE metrics. Then we take what we have in
3618 	 * the metrics in the route, where the offlink is used if we have
3619 	 * one.
3620 	 */
3621 	if (uinfo != NULL) {
3622 		bzero(uinfo, sizeof (*uinfo));
3623 
3624 		if (dce->dce_flags & DCEF_UINFO)
3625 			*uinfo = dce->dce_uinfo;
3626 
3627 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3628 
3629 		/* Allow ire_metrics to decrease the path MTU from above */
3630 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3631 			uinfo->iulp_mtu = pmtu;
3632 
3633 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3634 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3635 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3636 	}
3637 
3638 	if (ill != NULL)
3639 		ill_refrele(ill);
3640 
3641 	return (error);
3642 
3643 bad_addr:
3644 	if (ire != NULL)
3645 		ire_refrele(ire);
3646 
3647 	if (ill != NULL)
3648 		ill_refrele(ill);
3649 
3650 	/*
3651 	 * Make sure we don't leave an unreachable ixa_nce in place
3652 	 * since ip_select_route is used when we unplumb i.e., remove
3653 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3654 	 */
3655 	nce = ixa->ixa_nce;
3656 	if (nce != NULL && nce->nce_is_condemned) {
3657 		nce_refrele(nce);
3658 		ixa->ixa_nce = NULL;
3659 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3660 	}
3661 
3662 	return (error);
3663 }
3664 
3665 
3666 /*
3667  * Get the base MTU for the case when path MTU discovery is not used.
3668  * Takes the MTU of the IRE into account.
3669  */
3670 uint_t
3671 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3672 {
3673 	uint_t mtu = ill->ill_mtu;
3674 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3675 
3676 	if (iremtu != 0 && iremtu < mtu)
3677 		mtu = iremtu;
3678 
3679 	return (mtu);
3680 }
3681 
3682 /*
3683  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3684  * Assumes that ixa_ire, dce, and nce have already been set up.
3685  *
3686  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3687  * We avoid path MTU discovery if it is disabled with ndd.
3688  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3689  *
3690  * NOTE: We also used to turn it off for source routed packets. That
3691  * is no longer required since the dce is per final destination.
3692  */
3693 uint_t
3694 ip_get_pmtu(ip_xmit_attr_t *ixa)
3695 {
3696 	ip_stack_t	*ipst = ixa->ixa_ipst;
3697 	dce_t		*dce;
3698 	nce_t		*nce;
3699 	ire_t		*ire;
3700 	uint_t		pmtu;
3701 
3702 	ire = ixa->ixa_ire;
3703 	dce = ixa->ixa_dce;
3704 	nce = ixa->ixa_nce;
3705 
3706 	/*
3707 	 * If path MTU discovery has been turned off by ndd, then we ignore
3708 	 * any dce_pmtu and for IPv4 we will not set DF.
3709 	 */
3710 	if (!ipst->ips_ip_path_mtu_discovery)
3711 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3712 
3713 	pmtu = IP_MAXPACKET;
3714 	/*
3715 	 * Decide whether whether IPv4 sets DF
3716 	 * For IPv6 "no DF" means to use the 1280 mtu
3717 	 */
3718 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3719 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3720 	} else {
3721 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3722 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3723 			pmtu = IPV6_MIN_MTU;
3724 	}
3725 
3726 	/* Check if the PMTU is to old before we use it */
3727 	if ((dce->dce_flags & DCEF_PMTU) &&
3728 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3729 	    ipst->ips_ip_pathmtu_interval) {
3730 		/*
3731 		 * Older than 20 minutes. Drop the path MTU information.
3732 		 */
3733 		mutex_enter(&dce->dce_lock);
3734 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3735 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3736 		mutex_exit(&dce->dce_lock);
3737 		dce_increment_generation(dce);
3738 	}
3739 
3740 	/* The metrics on the route can lower the path MTU */
3741 	if (ire->ire_metrics.iulp_mtu != 0 &&
3742 	    ire->ire_metrics.iulp_mtu < pmtu)
3743 		pmtu = ire->ire_metrics.iulp_mtu;
3744 
3745 	/*
3746 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3747 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3748 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3749 	 */
3750 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3751 		if (dce->dce_flags & DCEF_PMTU) {
3752 			if (dce->dce_pmtu < pmtu)
3753 				pmtu = dce->dce_pmtu;
3754 
3755 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3756 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3757 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3758 			} else {
3759 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3760 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3761 			}
3762 		} else {
3763 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3764 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3765 		}
3766 	}
3767 
3768 	/*
3769 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3770 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3771 	 * mtu as IRE_LOOPBACK.
3772 	 */
3773 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3774 		uint_t loopback_mtu;
3775 
3776 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3777 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3778 
3779 		if (loopback_mtu < pmtu)
3780 			pmtu = loopback_mtu;
3781 	} else if (nce != NULL) {
3782 		/*
3783 		 * Make sure we don't exceed the interface MTU.
3784 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3785 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3786 		 * to tell the transport something larger than zero.
3787 		 */
3788 		if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3789 			pmtu = nce->nce_common->ncec_ill->ill_mtu;
3790 		if (nce->nce_common->ncec_ill != nce->nce_ill &&
3791 		    nce->nce_ill->ill_mtu < pmtu) {
3792 			/*
3793 			 * for interfaces in an IPMP group, the mtu of
3794 			 * the nce_ill (under_ill) could be different
3795 			 * from the mtu of the ncec_ill, so we take the
3796 			 * min of the two.
3797 			 */
3798 			pmtu = nce->nce_ill->ill_mtu;
3799 		}
3800 	}
3801 
3802 	/*
3803 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3804 	 * Only applies to IPv6.
3805 	 */
3806 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3807 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3808 			switch (ixa->ixa_use_min_mtu) {
3809 			case IPV6_USE_MIN_MTU_MULTICAST:
3810 				if (ire->ire_type & IRE_MULTICAST)
3811 					pmtu = IPV6_MIN_MTU;
3812 				break;
3813 			case IPV6_USE_MIN_MTU_ALWAYS:
3814 				pmtu = IPV6_MIN_MTU;
3815 				break;
3816 			case IPV6_USE_MIN_MTU_NEVER:
3817 				break;
3818 			}
3819 		} else {
3820 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3821 			if (ire->ire_type & IRE_MULTICAST)
3822 				pmtu = IPV6_MIN_MTU;
3823 		}
3824 	}
3825 
3826 	/*
3827 	 * After receiving an ICMPv6 "packet too big" message with a
3828 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3829 	 * will insert a 8-byte fragment header in every packet. We compensate
3830 	 * for those cases by returning a smaller path MTU to the ULP.
3831 	 *
3832 	 * In the case of CGTP then ip_output will add a fragment header.
3833 	 * Make sure there is room for it by telling a smaller number
3834 	 * to the transport.
3835 	 *
3836 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3837 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3838 	 * which is the size of the packets it can send.
3839 	 */
3840 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3841 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
3842 		    (ire->ire_flags & RTF_MULTIRT) ||
3843 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3844 			pmtu -= sizeof (ip6_frag_t);
3845 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3846 		}
3847 	}
3848 
3849 	return (pmtu);
3850 }
3851 
3852 /*
3853  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3854  * the final piece where we don't.  Return a pointer to the first mblk in the
3855  * result, and update the pointer to the next mblk to chew on.  If anything
3856  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3857  * NULL pointer.
3858  */
3859 mblk_t *
3860 ip_carve_mp(mblk_t **mpp, ssize_t len)
3861 {
3862 	mblk_t	*mp0;
3863 	mblk_t	*mp1;
3864 	mblk_t	*mp2;
3865 
3866 	if (!len || !mpp || !(mp0 = *mpp))
3867 		return (NULL);
3868 	/* If we aren't going to consume the first mblk, we need a dup. */
3869 	if (mp0->b_wptr - mp0->b_rptr > len) {
3870 		mp1 = dupb(mp0);
3871 		if (mp1) {
3872 			/* Partition the data between the two mblks. */
3873 			mp1->b_wptr = mp1->b_rptr + len;
3874 			mp0->b_rptr = mp1->b_wptr;
3875 			/*
3876 			 * after adjustments if mblk not consumed is now
3877 			 * unaligned, try to align it. If this fails free
3878 			 * all messages and let upper layer recover.
3879 			 */
3880 			if (!OK_32PTR(mp0->b_rptr)) {
3881 				if (!pullupmsg(mp0, -1)) {
3882 					freemsg(mp0);
3883 					freemsg(mp1);
3884 					*mpp = NULL;
3885 					return (NULL);
3886 				}
3887 			}
3888 		}
3889 		return (mp1);
3890 	}
3891 	/* Eat through as many mblks as we need to get len bytes. */
3892 	len -= mp0->b_wptr - mp0->b_rptr;
3893 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3894 		if (mp2->b_wptr - mp2->b_rptr > len) {
3895 			/*
3896 			 * We won't consume the entire last mblk.  Like
3897 			 * above, dup and partition it.
3898 			 */
3899 			mp1->b_cont = dupb(mp2);
3900 			mp1 = mp1->b_cont;
3901 			if (!mp1) {
3902 				/*
3903 				 * Trouble.  Rather than go to a lot of
3904 				 * trouble to clean up, we free the messages.
3905 				 * This won't be any worse than losing it on
3906 				 * the wire.
3907 				 */
3908 				freemsg(mp0);
3909 				freemsg(mp2);
3910 				*mpp = NULL;
3911 				return (NULL);
3912 			}
3913 			mp1->b_wptr = mp1->b_rptr + len;
3914 			mp2->b_rptr = mp1->b_wptr;
3915 			/*
3916 			 * after adjustments if mblk not consumed is now
3917 			 * unaligned, try to align it. If this fails free
3918 			 * all messages and let upper layer recover.
3919 			 */
3920 			if (!OK_32PTR(mp2->b_rptr)) {
3921 				if (!pullupmsg(mp2, -1)) {
3922 					freemsg(mp0);
3923 					freemsg(mp2);
3924 					*mpp = NULL;
3925 					return (NULL);
3926 				}
3927 			}
3928 			*mpp = mp2;
3929 			return (mp0);
3930 		}
3931 		/* Decrement len by the amount we just got. */
3932 		len -= mp2->b_wptr - mp2->b_rptr;
3933 	}
3934 	/*
3935 	 * len should be reduced to zero now.  If not our caller has
3936 	 * screwed up.
3937 	 */
3938 	if (len) {
3939 		/* Shouldn't happen! */
3940 		freemsg(mp0);
3941 		*mpp = NULL;
3942 		return (NULL);
3943 	}
3944 	/*
3945 	 * We consumed up to exactly the end of an mblk.  Detach the part
3946 	 * we are returning from the rest of the chain.
3947 	 */
3948 	mp1->b_cont = NULL;
3949 	*mpp = mp2;
3950 	return (mp0);
3951 }
3952 
3953 /* The ill stream is being unplumbed. Called from ip_close */
3954 int
3955 ip_modclose(ill_t *ill)
3956 {
3957 	boolean_t success;
3958 	ipsq_t	*ipsq;
3959 	ipif_t	*ipif;
3960 	queue_t	*q = ill->ill_rq;
3961 	ip_stack_t	*ipst = ill->ill_ipst;
3962 	int	i;
3963 	arl_ill_common_t *ai = ill->ill_common;
3964 
3965 	/*
3966 	 * The punlink prior to this may have initiated a capability
3967 	 * negotiation. But ipsq_enter will block until that finishes or
3968 	 * times out.
3969 	 */
3970 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
3971 
3972 	/*
3973 	 * Open/close/push/pop is guaranteed to be single threaded
3974 	 * per stream by STREAMS. FS guarantees that all references
3975 	 * from top are gone before close is called. So there can't
3976 	 * be another close thread that has set CONDEMNED on this ill.
3977 	 * and cause ipsq_enter to return failure.
3978 	 */
3979 	ASSERT(success);
3980 	ipsq = ill->ill_phyint->phyint_ipsq;
3981 
3982 	/*
3983 	 * Mark it condemned. No new reference will be made to this ill.
3984 	 * Lookup functions will return an error. Threads that try to
3985 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
3986 	 * that the refcnt will drop down to zero.
3987 	 */
3988 	mutex_enter(&ill->ill_lock);
3989 	ill->ill_state_flags |= ILL_CONDEMNED;
3990 	for (ipif = ill->ill_ipif; ipif != NULL;
3991 	    ipif = ipif->ipif_next) {
3992 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
3993 	}
3994 	/*
3995 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
3996 	 * returns  error if ILL_CONDEMNED is set
3997 	 */
3998 	cv_broadcast(&ill->ill_cv);
3999 	mutex_exit(&ill->ill_lock);
4000 
4001 	/*
4002 	 * Send all the deferred DLPI messages downstream which came in
4003 	 * during the small window right before ipsq_enter(). We do this
4004 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4005 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4006 	 */
4007 	ill_dlpi_send_deferred(ill);
4008 
4009 	/*
4010 	 * Shut down fragmentation reassembly.
4011 	 * ill_frag_timer won't start a timer again.
4012 	 * Now cancel any existing timer
4013 	 */
4014 	(void) untimeout(ill->ill_frag_timer_id);
4015 	(void) ill_frag_timeout(ill, 0);
4016 
4017 	/*
4018 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4019 	 * this ill. Then wait for the refcnts to drop to zero.
4020 	 * ill_is_freeable checks whether the ill is really quiescent.
4021 	 * Then make sure that threads that are waiting to enter the
4022 	 * ipsq have seen the error returned by ipsq_enter and have
4023 	 * gone away. Then we call ill_delete_tail which does the
4024 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4025 	 */
4026 	ill_delete(ill);
4027 	mutex_enter(&ill->ill_lock);
4028 	while (!ill_is_freeable(ill))
4029 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4030 
4031 	while (ill->ill_waiters)
4032 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4033 
4034 	mutex_exit(&ill->ill_lock);
4035 
4036 	/*
4037 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4038 	 * it held until the end of the function since the cleanup
4039 	 * below needs to be able to use the ip_stack_t.
4040 	 */
4041 	netstack_hold(ipst->ips_netstack);
4042 
4043 	/* qprocsoff is done via ill_delete_tail */
4044 	ill_delete_tail(ill);
4045 	/*
4046 	 * synchronously wait for arp stream to unbind. After this, we
4047 	 * cannot get any data packets up from the driver.
4048 	 */
4049 	arp_unbind_complete(ill);
4050 	ASSERT(ill->ill_ipst == NULL);
4051 
4052 	/*
4053 	 * Walk through all conns and qenable those that have queued data.
4054 	 * Close synchronization needs this to
4055 	 * be done to ensure that all upper layers blocked
4056 	 * due to flow control to the closing device
4057 	 * get unblocked.
4058 	 */
4059 	ip1dbg(("ip_wsrv: walking\n"));
4060 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4061 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4062 	}
4063 
4064 	/*
4065 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4066 	 * stream is being torn down before ARP was plumbed (e.g.,
4067 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4068 	 * an error
4069 	 */
4070 	if (ai != NULL) {
4071 		ASSERT(!ill->ill_isv6);
4072 		mutex_enter(&ai->ai_lock);
4073 		ai->ai_ill = NULL;
4074 		if (ai->ai_arl == NULL) {
4075 			mutex_destroy(&ai->ai_lock);
4076 			kmem_free(ai, sizeof (*ai));
4077 		} else {
4078 			cv_signal(&ai->ai_ill_unplumb_done);
4079 			mutex_exit(&ai->ai_lock);
4080 		}
4081 	}
4082 
4083 	mutex_enter(&ipst->ips_ip_mi_lock);
4084 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4085 	mutex_exit(&ipst->ips_ip_mi_lock);
4086 
4087 	/*
4088 	 * credp could be null if the open didn't succeed and ip_modopen
4089 	 * itself calls ip_close.
4090 	 */
4091 	if (ill->ill_credp != NULL)
4092 		crfree(ill->ill_credp);
4093 
4094 	mutex_destroy(&ill->ill_saved_ire_lock);
4095 	mutex_destroy(&ill->ill_lock);
4096 	rw_destroy(&ill->ill_mcast_lock);
4097 	mutex_destroy(&ill->ill_mcast_serializer);
4098 	list_destroy(&ill->ill_nce);
4099 
4100 	/*
4101 	 * Now we are done with the module close pieces that
4102 	 * need the netstack_t.
4103 	 */
4104 	netstack_rele(ipst->ips_netstack);
4105 
4106 	mi_close_free((IDP)ill);
4107 	q->q_ptr = WR(q)->q_ptr = NULL;
4108 
4109 	ipsq_exit(ipsq);
4110 
4111 	return (0);
4112 }
4113 
4114 /*
4115  * This is called as part of close() for IP, UDP, ICMP, and RTS
4116  * in order to quiesce the conn.
4117  */
4118 void
4119 ip_quiesce_conn(conn_t *connp)
4120 {
4121 	boolean_t	drain_cleanup_reqd = B_FALSE;
4122 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4123 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4124 	ip_stack_t	*ipst;
4125 
4126 	ASSERT(!IPCL_IS_TCP(connp));
4127 	ipst = connp->conn_netstack->netstack_ip;
4128 
4129 	/*
4130 	 * Mark the conn as closing, and this conn must not be
4131 	 * inserted in future into any list. Eg. conn_drain_insert(),
4132 	 * won't insert this conn into the conn_drain_list.
4133 	 *
4134 	 * conn_idl, and conn_ilg cannot get set henceforth.
4135 	 */
4136 	mutex_enter(&connp->conn_lock);
4137 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4138 	connp->conn_state_flags |= CONN_CLOSING;
4139 	if (connp->conn_idl != NULL)
4140 		drain_cleanup_reqd = B_TRUE;
4141 	if (connp->conn_oper_pending_ill != NULL)
4142 		conn_ioctl_cleanup_reqd = B_TRUE;
4143 	if (connp->conn_dhcpinit_ill != NULL) {
4144 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4145 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4146 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4147 		connp->conn_dhcpinit_ill = NULL;
4148 	}
4149 	if (connp->conn_ilg != NULL)
4150 		ilg_cleanup_reqd = B_TRUE;
4151 	mutex_exit(&connp->conn_lock);
4152 
4153 	if (conn_ioctl_cleanup_reqd)
4154 		conn_ioctl_cleanup(connp);
4155 
4156 	if (is_system_labeled() && connp->conn_anon_port) {
4157 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4158 		    connp->conn_mlp_type, connp->conn_proto,
4159 		    ntohs(connp->conn_lport), B_FALSE);
4160 		connp->conn_anon_port = 0;
4161 	}
4162 	connp->conn_mlp_type = mlptSingle;
4163 
4164 	/*
4165 	 * Remove this conn from any fanout list it is on.
4166 	 * and then wait for any threads currently operating
4167 	 * on this endpoint to finish
4168 	 */
4169 	ipcl_hash_remove(connp);
4170 
4171 	/*
4172 	 * Remove this conn from the drain list, and do any other cleanup that
4173 	 * may be required.  (TCP conns are never flow controlled, and
4174 	 * conn_idl will be NULL.)
4175 	 */
4176 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4177 		idl_t *idl = connp->conn_idl;
4178 
4179 		mutex_enter(&idl->idl_lock);
4180 		conn_drain(connp, B_TRUE);
4181 		mutex_exit(&idl->idl_lock);
4182 	}
4183 
4184 	if (connp == ipst->ips_ip_g_mrouter)
4185 		(void) ip_mrouter_done(ipst);
4186 
4187 	if (ilg_cleanup_reqd)
4188 		ilg_delete_all(connp);
4189 
4190 	/*
4191 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4192 	 * callers from write side can't be there now because close
4193 	 * is in progress. The only other caller is ipcl_walk
4194 	 * which checks for the condemned flag.
4195 	 */
4196 	mutex_enter(&connp->conn_lock);
4197 	connp->conn_state_flags |= CONN_CONDEMNED;
4198 	while (connp->conn_ref != 1)
4199 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4200 	connp->conn_state_flags |= CONN_QUIESCED;
4201 	mutex_exit(&connp->conn_lock);
4202 }
4203 
4204 /* ARGSUSED */
4205 int
4206 ip_close(queue_t *q, int flags)
4207 {
4208 	conn_t		*connp;
4209 
4210 	/*
4211 	 * Call the appropriate delete routine depending on whether this is
4212 	 * a module or device.
4213 	 */
4214 	if (WR(q)->q_next != NULL) {
4215 		/* This is a module close */
4216 		return (ip_modclose((ill_t *)q->q_ptr));
4217 	}
4218 
4219 	connp = q->q_ptr;
4220 	ip_quiesce_conn(connp);
4221 
4222 	qprocsoff(q);
4223 
4224 	/*
4225 	 * Now we are truly single threaded on this stream, and can
4226 	 * delete the things hanging off the connp, and finally the connp.
4227 	 * We removed this connp from the fanout list, it cannot be
4228 	 * accessed thru the fanouts, and we already waited for the
4229 	 * conn_ref to drop to 0. We are already in close, so
4230 	 * there cannot be any other thread from the top. qprocsoff
4231 	 * has completed, and service has completed or won't run in
4232 	 * future.
4233 	 */
4234 	ASSERT(connp->conn_ref == 1);
4235 
4236 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4237 
4238 	connp->conn_ref--;
4239 	ipcl_conn_destroy(connp);
4240 
4241 	q->q_ptr = WR(q)->q_ptr = NULL;
4242 	return (0);
4243 }
4244 
4245 /*
4246  * Wapper around putnext() so that ip_rts_request can merely use
4247  * conn_recv.
4248  */
4249 /*ARGSUSED2*/
4250 static void
4251 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4252 {
4253 	conn_t *connp = (conn_t *)arg1;
4254 
4255 	putnext(connp->conn_rq, mp);
4256 }
4257 
4258 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4259 /* ARGSUSED */
4260 static void
4261 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4262 {
4263 	freemsg(mp);
4264 }
4265 
4266 /*
4267  * Called when the module is about to be unloaded
4268  */
4269 void
4270 ip_ddi_destroy(void)
4271 {
4272 	tnet_fini();
4273 
4274 	icmp_ddi_g_destroy();
4275 	rts_ddi_g_destroy();
4276 	udp_ddi_g_destroy();
4277 	sctp_ddi_g_destroy();
4278 	tcp_ddi_g_destroy();
4279 	ilb_ddi_g_destroy();
4280 	dce_g_destroy();
4281 	ipsec_policy_g_destroy();
4282 	ipcl_g_destroy();
4283 	ip_net_g_destroy();
4284 	ip_ire_g_fini();
4285 	inet_minor_destroy(ip_minor_arena_sa);
4286 #if defined(_LP64)
4287 	inet_minor_destroy(ip_minor_arena_la);
4288 #endif
4289 
4290 #ifdef DEBUG
4291 	list_destroy(&ip_thread_list);
4292 	rw_destroy(&ip_thread_rwlock);
4293 	tsd_destroy(&ip_thread_data);
4294 #endif
4295 
4296 	netstack_unregister(NS_IP);
4297 }
4298 
4299 /*
4300  * First step in cleanup.
4301  */
4302 /* ARGSUSED */
4303 static void
4304 ip_stack_shutdown(netstackid_t stackid, void *arg)
4305 {
4306 	ip_stack_t *ipst = (ip_stack_t *)arg;
4307 
4308 #ifdef NS_DEBUG
4309 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4310 #endif
4311 
4312 	/*
4313 	 * Perform cleanup for special interfaces (loopback and IPMP).
4314 	 */
4315 	ip_interface_cleanup(ipst);
4316 
4317 	/*
4318 	 * The *_hook_shutdown()s start the process of notifying any
4319 	 * consumers that things are going away.... nothing is destroyed.
4320 	 */
4321 	ipv4_hook_shutdown(ipst);
4322 	ipv6_hook_shutdown(ipst);
4323 	arp_hook_shutdown(ipst);
4324 
4325 	mutex_enter(&ipst->ips_capab_taskq_lock);
4326 	ipst->ips_capab_taskq_quit = B_TRUE;
4327 	cv_signal(&ipst->ips_capab_taskq_cv);
4328 	mutex_exit(&ipst->ips_capab_taskq_lock);
4329 }
4330 
4331 /*
4332  * Free the IP stack instance.
4333  */
4334 static void
4335 ip_stack_fini(netstackid_t stackid, void *arg)
4336 {
4337 	ip_stack_t *ipst = (ip_stack_t *)arg;
4338 	int ret;
4339 
4340 #ifdef NS_DEBUG
4341 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4342 #endif
4343 	/*
4344 	 * At this point, all of the notifications that the events and
4345 	 * protocols are going away have been run, meaning that we can
4346 	 * now set about starting to clean things up.
4347 	 */
4348 	ipobs_fini(ipst);
4349 	ipv4_hook_destroy(ipst);
4350 	ipv6_hook_destroy(ipst);
4351 	arp_hook_destroy(ipst);
4352 	ip_net_destroy(ipst);
4353 
4354 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4355 	cv_destroy(&ipst->ips_capab_taskq_cv);
4356 
4357 	ipmp_destroy(ipst);
4358 	rw_destroy(&ipst->ips_srcid_lock);
4359 
4360 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4361 	ipst->ips_ip_mibkp = NULL;
4362 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4363 	ipst->ips_icmp_mibkp = NULL;
4364 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4365 	ipst->ips_ip_kstat = NULL;
4366 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4367 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4368 	ipst->ips_ip6_kstat = NULL;
4369 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4370 
4371 	kmem_free(ipst->ips_propinfo_tbl,
4372 	    ip_propinfo_count * sizeof (mod_prop_info_t));
4373 	ipst->ips_propinfo_tbl = NULL;
4374 
4375 	dce_stack_destroy(ipst);
4376 	ip_mrouter_stack_destroy(ipst);
4377 
4378 	mutex_destroy(&ipst->ips_ip_mi_lock);
4379 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4380 
4381 	ret = untimeout(ipst->ips_igmp_timeout_id);
4382 	if (ret == -1) {
4383 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4384 	} else {
4385 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4386 		ipst->ips_igmp_timeout_id = 0;
4387 	}
4388 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4389 	if (ret == -1) {
4390 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4391 	} else {
4392 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4393 		ipst->ips_igmp_slowtimeout_id = 0;
4394 	}
4395 	ret = untimeout(ipst->ips_mld_timeout_id);
4396 	if (ret == -1) {
4397 		ASSERT(ipst->ips_mld_timeout_id == 0);
4398 	} else {
4399 		ASSERT(ipst->ips_mld_timeout_id != 0);
4400 		ipst->ips_mld_timeout_id = 0;
4401 	}
4402 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4403 	if (ret == -1) {
4404 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4405 	} else {
4406 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4407 		ipst->ips_mld_slowtimeout_id = 0;
4408 	}
4409 
4410 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4411 	mutex_destroy(&ipst->ips_mld_timer_lock);
4412 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4413 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4414 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4415 	rw_destroy(&ipst->ips_ill_g_lock);
4416 
4417 	ip_ire_fini(ipst);
4418 	ip6_asp_free(ipst);
4419 	conn_drain_fini(ipst);
4420 	ipcl_destroy(ipst);
4421 
4422 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4423 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4424 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4425 	ipst->ips_ndp4 = NULL;
4426 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4427 	ipst->ips_ndp6 = NULL;
4428 
4429 	if (ipst->ips_loopback_ksp != NULL) {
4430 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4431 		ipst->ips_loopback_ksp = NULL;
4432 	}
4433 
4434 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4435 	ipst->ips_phyint_g_list = NULL;
4436 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4437 	ipst->ips_ill_g_heads = NULL;
4438 
4439 	ldi_ident_release(ipst->ips_ldi_ident);
4440 	kmem_free(ipst, sizeof (*ipst));
4441 }
4442 
4443 /*
4444  * This function is called from the TSD destructor, and is used to debug
4445  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4446  * details.
4447  */
4448 static void
4449 ip_thread_exit(void *phash)
4450 {
4451 	th_hash_t *thh = phash;
4452 
4453 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4454 	list_remove(&ip_thread_list, thh);
4455 	rw_exit(&ip_thread_rwlock);
4456 	mod_hash_destroy_hash(thh->thh_hash);
4457 	kmem_free(thh, sizeof (*thh));
4458 }
4459 
4460 /*
4461  * Called when the IP kernel module is loaded into the kernel
4462  */
4463 void
4464 ip_ddi_init(void)
4465 {
4466 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4467 
4468 	/*
4469 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4470 	 * initial devices: ip, ip6, tcp, tcp6.
4471 	 */
4472 	/*
4473 	 * If this is a 64-bit kernel, then create two separate arenas -
4474 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4475 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4476 	 */
4477 	ip_minor_arena_la = NULL;
4478 	ip_minor_arena_sa = NULL;
4479 #if defined(_LP64)
4480 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4481 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4482 		cmn_err(CE_PANIC,
4483 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4484 	}
4485 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4486 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4487 		cmn_err(CE_PANIC,
4488 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4489 	}
4490 #else
4491 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4492 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4493 		cmn_err(CE_PANIC,
4494 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4495 	}
4496 #endif
4497 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4498 
4499 	ipcl_g_init();
4500 	ip_ire_g_init();
4501 	ip_net_g_init();
4502 
4503 #ifdef DEBUG
4504 	tsd_create(&ip_thread_data, ip_thread_exit);
4505 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4506 	list_create(&ip_thread_list, sizeof (th_hash_t),
4507 	    offsetof(th_hash_t, thh_link));
4508 #endif
4509 	ipsec_policy_g_init();
4510 	tcp_ddi_g_init();
4511 	sctp_ddi_g_init();
4512 	dce_g_init();
4513 
4514 	/*
4515 	 * We want to be informed each time a stack is created or
4516 	 * destroyed in the kernel, so we can maintain the
4517 	 * set of udp_stack_t's.
4518 	 */
4519 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4520 	    ip_stack_fini);
4521 
4522 	tnet_init();
4523 
4524 	udp_ddi_g_init();
4525 	rts_ddi_g_init();
4526 	icmp_ddi_g_init();
4527 	ilb_ddi_g_init();
4528 }
4529 
4530 /*
4531  * Initialize the IP stack instance.
4532  */
4533 static void *
4534 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4535 {
4536 	ip_stack_t	*ipst;
4537 	size_t		arrsz;
4538 	major_t		major;
4539 
4540 #ifdef NS_DEBUG
4541 	printf("ip_stack_init(stack %d)\n", stackid);
4542 #endif
4543 
4544 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4545 	ipst->ips_netstack = ns;
4546 
4547 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4548 	    KM_SLEEP);
4549 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4550 	    KM_SLEEP);
4551 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4552 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4553 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4554 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4555 
4556 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4557 	ipst->ips_igmp_deferred_next = INFINITY;
4558 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4559 	ipst->ips_mld_deferred_next = INFINITY;
4560 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4561 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4562 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4563 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4564 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4565 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4566 
4567 	ipcl_init(ipst);
4568 	ip_ire_init(ipst);
4569 	ip6_asp_init(ipst);
4570 	ipif_init(ipst);
4571 	conn_drain_init(ipst);
4572 	ip_mrouter_stack_init(ipst);
4573 	dce_stack_init(ipst);
4574 
4575 	ipst->ips_ip_multirt_log_interval = 1000;
4576 
4577 	ipst->ips_ill_index = 1;
4578 
4579 	ipst->ips_saved_ip_forwarding = -1;
4580 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4581 
4582 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4583 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4584 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4585 
4586 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4587 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4588 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4589 	ipst->ips_ip6_kstat =
4590 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4591 
4592 	ipst->ips_ip_src_id = 1;
4593 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4594 
4595 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4596 
4597 	ip_net_init(ipst, ns);
4598 	ipv4_hook_init(ipst);
4599 	ipv6_hook_init(ipst);
4600 	arp_hook_init(ipst);
4601 	ipmp_init(ipst);
4602 	ipobs_init(ipst);
4603 
4604 	/*
4605 	 * Create the taskq dispatcher thread and initialize related stuff.
4606 	 */
4607 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4608 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4609 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4610 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4611 
4612 	major = mod_name_to_major(INET_NAME);
4613 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4614 	return (ipst);
4615 }
4616 
4617 /*
4618  * Allocate and initialize a DLPI template of the specified length.  (May be
4619  * called as writer.)
4620  */
4621 mblk_t *
4622 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4623 {
4624 	mblk_t	*mp;
4625 
4626 	mp = allocb(len, BPRI_MED);
4627 	if (!mp)
4628 		return (NULL);
4629 
4630 	/*
4631 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4632 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4633 	 * that other DLPI are M_PROTO.
4634 	 */
4635 	if (prim == DL_INFO_REQ) {
4636 		mp->b_datap->db_type = M_PCPROTO;
4637 	} else {
4638 		mp->b_datap->db_type = M_PROTO;
4639 	}
4640 
4641 	mp->b_wptr = mp->b_rptr + len;
4642 	bzero(mp->b_rptr, len);
4643 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4644 	return (mp);
4645 }
4646 
4647 /*
4648  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4649  */
4650 mblk_t *
4651 ip_dlnotify_alloc(uint_t notification, uint_t data)
4652 {
4653 	dl_notify_ind_t	*notifyp;
4654 	mblk_t		*mp;
4655 
4656 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4657 		return (NULL);
4658 
4659 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4660 	notifyp->dl_notification = notification;
4661 	notifyp->dl_data = data;
4662 	return (mp);
4663 }
4664 
4665 /*
4666  * Debug formatting routine.  Returns a character string representation of the
4667  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4668  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4669  *
4670  * Once the ndd table-printing interfaces are removed, this can be changed to
4671  * standard dotted-decimal form.
4672  */
4673 char *
4674 ip_dot_addr(ipaddr_t addr, char *buf)
4675 {
4676 	uint8_t *ap = (uint8_t *)&addr;
4677 
4678 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4679 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4680 	return (buf);
4681 }
4682 
4683 /*
4684  * Write the given MAC address as a printable string in the usual colon-
4685  * separated format.
4686  */
4687 const char *
4688 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4689 {
4690 	char *bp;
4691 
4692 	if (alen == 0 || buflen < 4)
4693 		return ("?");
4694 	bp = buf;
4695 	for (;;) {
4696 		/*
4697 		 * If there are more MAC address bytes available, but we won't
4698 		 * have any room to print them, then add "..." to the string
4699 		 * instead.  See below for the 'magic number' explanation.
4700 		 */
4701 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4702 			(void) strcpy(bp, "...");
4703 			break;
4704 		}
4705 		(void) sprintf(bp, "%02x", *addr++);
4706 		bp += 2;
4707 		if (--alen == 0)
4708 			break;
4709 		*bp++ = ':';
4710 		buflen -= 3;
4711 		/*
4712 		 * At this point, based on the first 'if' statement above,
4713 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4714 		 * buflen >= 4.  The first case leaves room for the final "xx"
4715 		 * number and trailing NUL byte.  The second leaves room for at
4716 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4717 		 * that statement.
4718 		 */
4719 	}
4720 	return (buf);
4721 }
4722 
4723 /*
4724  * Called when it is conceptually a ULP that would sent the packet
4725  * e.g., port unreachable and protocol unreachable. Check that the packet
4726  * would have passed the IPsec global policy before sending the error.
4727  *
4728  * Send an ICMP error after patching up the packet appropriately.
4729  * Uses ip_drop_input and bumps the appropriate MIB.
4730  */
4731 void
4732 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4733     ip_recv_attr_t *ira)
4734 {
4735 	ipha_t		*ipha;
4736 	boolean_t	secure;
4737 	ill_t		*ill = ira->ira_ill;
4738 	ip_stack_t	*ipst = ill->ill_ipst;
4739 	netstack_t	*ns = ipst->ips_netstack;
4740 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4741 
4742 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4743 
4744 	/*
4745 	 * We are generating an icmp error for some inbound packet.
4746 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4747 	 * Before we generate an error, check with global policy
4748 	 * to see whether this is allowed to enter the system. As
4749 	 * there is no "conn", we are checking with global policy.
4750 	 */
4751 	ipha = (ipha_t *)mp->b_rptr;
4752 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4753 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4754 		if (mp == NULL)
4755 			return;
4756 	}
4757 
4758 	/* We never send errors for protocols that we do implement */
4759 	if (ira->ira_protocol == IPPROTO_ICMP ||
4760 	    ira->ira_protocol == IPPROTO_IGMP) {
4761 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4762 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4763 		freemsg(mp);
4764 		return;
4765 	}
4766 	/*
4767 	 * Have to correct checksum since
4768 	 * the packet might have been
4769 	 * fragmented and the reassembly code in ip_rput
4770 	 * does not restore the IP checksum.
4771 	 */
4772 	ipha->ipha_hdr_checksum = 0;
4773 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4774 
4775 	switch (icmp_type) {
4776 	case ICMP_DEST_UNREACHABLE:
4777 		switch (icmp_code) {
4778 		case ICMP_PROTOCOL_UNREACHABLE:
4779 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4780 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4781 			break;
4782 		case ICMP_PORT_UNREACHABLE:
4783 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4784 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4785 			break;
4786 		}
4787 
4788 		icmp_unreachable(mp, icmp_code, ira);
4789 		break;
4790 	default:
4791 #ifdef DEBUG
4792 		panic("ip_fanout_send_icmp_v4: wrong type");
4793 		/*NOTREACHED*/
4794 #else
4795 		freemsg(mp);
4796 		break;
4797 #endif
4798 	}
4799 }
4800 
4801 /*
4802  * Used to send an ICMP error message when a packet is received for
4803  * a protocol that is not supported. The mblk passed as argument
4804  * is consumed by this function.
4805  */
4806 void
4807 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4808 {
4809 	ipha_t		*ipha;
4810 
4811 	ipha = (ipha_t *)mp->b_rptr;
4812 	if (ira->ira_flags & IRAF_IS_IPV4) {
4813 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4814 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4815 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4816 	} else {
4817 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4818 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4819 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4820 	}
4821 }
4822 
4823 /*
4824  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4825  * Handles IPv4 and IPv6.
4826  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4827  * Caller is responsible for dropping references to the conn.
4828  */
4829 void
4830 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4831     ip_recv_attr_t *ira)
4832 {
4833 	ill_t		*ill = ira->ira_ill;
4834 	ip_stack_t	*ipst = ill->ill_ipst;
4835 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4836 	boolean_t	secure;
4837 	uint_t		protocol = ira->ira_protocol;
4838 	iaflags_t	iraflags = ira->ira_flags;
4839 	queue_t		*rq;
4840 
4841 	secure = iraflags & IRAF_IPSEC_SECURE;
4842 
4843 	rq = connp->conn_rq;
4844 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4845 		switch (protocol) {
4846 		case IPPROTO_ICMPV6:
4847 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4848 			break;
4849 		case IPPROTO_ICMP:
4850 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4851 			break;
4852 		default:
4853 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4854 			break;
4855 		}
4856 		freemsg(mp);
4857 		return;
4858 	}
4859 
4860 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4861 
4862 	if (((iraflags & IRAF_IS_IPV4) ?
4863 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4864 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4865 	    secure) {
4866 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4867 		    ip6h, ira);
4868 		if (mp == NULL) {
4869 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4870 			/* Note that mp is NULL */
4871 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4872 			return;
4873 		}
4874 	}
4875 
4876 	if (iraflags & IRAF_ICMP_ERROR) {
4877 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4878 	} else {
4879 		ill_t *rill = ira->ira_rill;
4880 
4881 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4882 		ira->ira_ill = ira->ira_rill = NULL;
4883 		/* Send it upstream */
4884 		(connp->conn_recv)(connp, mp, NULL, ira);
4885 		ira->ira_ill = ill;
4886 		ira->ira_rill = rill;
4887 	}
4888 }
4889 
4890 /*
4891  * Handle protocols with which IP is less intimate.  There
4892  * can be more than one stream bound to a particular
4893  * protocol.  When this is the case, normally each one gets a copy
4894  * of any incoming packets.
4895  *
4896  * IPsec NOTE :
4897  *
4898  * Don't allow a secure packet going up a non-secure connection.
4899  * We don't allow this because
4900  *
4901  * 1) Reply might go out in clear which will be dropped at
4902  *    the sending side.
4903  * 2) If the reply goes out in clear it will give the
4904  *    adversary enough information for getting the key in
4905  *    most of the cases.
4906  *
4907  * Moreover getting a secure packet when we expect clear
4908  * implies that SA's were added without checking for
4909  * policy on both ends. This should not happen once ISAKMP
4910  * is used to negotiate SAs as SAs will be added only after
4911  * verifying the policy.
4912  *
4913  * Zones notes:
4914  * Earlier in ip_input on a system with multiple shared-IP zones we
4915  * duplicate the multicast and broadcast packets and send them up
4916  * with each explicit zoneid that exists on that ill.
4917  * This means that here we can match the zoneid with SO_ALLZONES being special.
4918  */
4919 void
4920 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
4921 {
4922 	mblk_t		*mp1;
4923 	ipaddr_t	laddr;
4924 	conn_t		*connp, *first_connp, *next_connp;
4925 	connf_t		*connfp;
4926 	ill_t		*ill = ira->ira_ill;
4927 	ip_stack_t	*ipst = ill->ill_ipst;
4928 
4929 	laddr = ipha->ipha_dst;
4930 
4931 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
4932 	mutex_enter(&connfp->connf_lock);
4933 	connp = connfp->connf_head;
4934 	for (connp = connfp->connf_head; connp != NULL;
4935 	    connp = connp->conn_next) {
4936 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4937 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4938 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4939 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
4940 			break;
4941 		}
4942 	}
4943 
4944 	if (connp == NULL) {
4945 		/*
4946 		 * No one bound to these addresses.  Is
4947 		 * there a client that wants all
4948 		 * unclaimed datagrams?
4949 		 */
4950 		mutex_exit(&connfp->connf_lock);
4951 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4952 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4953 		return;
4954 	}
4955 
4956 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
4957 
4958 	CONN_INC_REF(connp);
4959 	first_connp = connp;
4960 	connp = connp->conn_next;
4961 
4962 	for (;;) {
4963 		while (connp != NULL) {
4964 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4965 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4966 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4967 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
4968 			    ira, connp)))
4969 				break;
4970 			connp = connp->conn_next;
4971 		}
4972 
4973 		if (connp == NULL) {
4974 			/* No more interested clients */
4975 			connp = first_connp;
4976 			break;
4977 		}
4978 		if (((mp1 = dupmsg(mp)) == NULL) &&
4979 		    ((mp1 = copymsg(mp)) == NULL)) {
4980 			/* Memory allocation failed */
4981 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4982 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4983 			connp = first_connp;
4984 			break;
4985 		}
4986 
4987 		CONN_INC_REF(connp);
4988 		mutex_exit(&connfp->connf_lock);
4989 
4990 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
4991 		    ira);
4992 
4993 		mutex_enter(&connfp->connf_lock);
4994 		/* Follow the next pointer before releasing the conn. */
4995 		next_connp = connp->conn_next;
4996 		CONN_DEC_REF(connp);
4997 		connp = next_connp;
4998 	}
4999 
5000 	/* Last one.  Send it upstream. */
5001 	mutex_exit(&connfp->connf_lock);
5002 
5003 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5004 
5005 	CONN_DEC_REF(connp);
5006 }
5007 
5008 /*
5009  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5010  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5011  * is not consumed.
5012  *
5013  * One of three things can happen, all of which affect the passed-in mblk:
5014  *
5015  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5016  *
5017  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5018  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5019  *
5020  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5021  */
5022 mblk_t *
5023 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5024 {
5025 	int shift, plen, iph_len;
5026 	ipha_t *ipha;
5027 	udpha_t *udpha;
5028 	uint32_t *spi;
5029 	uint32_t esp_ports;
5030 	uint8_t *orptr;
5031 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5032 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5033 
5034 	ipha = (ipha_t *)mp->b_rptr;
5035 	iph_len = ira->ira_ip_hdr_length;
5036 	plen = ira->ira_pktlen;
5037 
5038 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5039 		/*
5040 		 * Most likely a keepalive for the benefit of an intervening
5041 		 * NAT.  These aren't for us, per se, so drop it.
5042 		 *
5043 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5044 		 * byte packets (keepalives are 1-byte), but we'll drop them
5045 		 * also.
5046 		 */
5047 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5048 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5049 		return (NULL);
5050 	}
5051 
5052 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5053 		/* might as well pull it all up - it might be ESP. */
5054 		if (!pullupmsg(mp, -1)) {
5055 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5056 			    DROPPER(ipss, ipds_esp_nomem),
5057 			    &ipss->ipsec_dropper);
5058 			return (NULL);
5059 		}
5060 
5061 		ipha = (ipha_t *)mp->b_rptr;
5062 	}
5063 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5064 	if (*spi == 0) {
5065 		/* UDP packet - remove 0-spi. */
5066 		shift = sizeof (uint32_t);
5067 	} else {
5068 		/* ESP-in-UDP packet - reduce to ESP. */
5069 		ipha->ipha_protocol = IPPROTO_ESP;
5070 		shift = sizeof (udpha_t);
5071 	}
5072 
5073 	/* Fix IP header */
5074 	ira->ira_pktlen = (plen - shift);
5075 	ipha->ipha_length = htons(ira->ira_pktlen);
5076 	ipha->ipha_hdr_checksum = 0;
5077 
5078 	orptr = mp->b_rptr;
5079 	mp->b_rptr += shift;
5080 
5081 	udpha = (udpha_t *)(orptr + iph_len);
5082 	if (*spi == 0) {
5083 		ASSERT((uint8_t *)ipha == orptr);
5084 		udpha->uha_length = htons(plen - shift - iph_len);
5085 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5086 		esp_ports = 0;
5087 	} else {
5088 		esp_ports = *((uint32_t *)udpha);
5089 		ASSERT(esp_ports != 0);
5090 	}
5091 	ovbcopy(orptr, orptr + shift, iph_len);
5092 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5093 		ipha = (ipha_t *)(orptr + shift);
5094 
5095 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5096 		ira->ira_esp_udp_ports = esp_ports;
5097 		ip_fanout_v4(mp, ipha, ira);
5098 		return (NULL);
5099 	}
5100 	return (mp);
5101 }
5102 
5103 /*
5104  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5105  * Handles IPv4 and IPv6.
5106  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5107  * Caller is responsible for dropping references to the conn.
5108  */
5109 void
5110 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5111     ip_recv_attr_t *ira)
5112 {
5113 	ill_t		*ill = ira->ira_ill;
5114 	ip_stack_t	*ipst = ill->ill_ipst;
5115 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5116 	boolean_t	secure;
5117 	iaflags_t	iraflags = ira->ira_flags;
5118 
5119 	secure = iraflags & IRAF_IPSEC_SECURE;
5120 
5121 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5122 	    !canputnext(connp->conn_rq)) {
5123 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5124 		freemsg(mp);
5125 		return;
5126 	}
5127 
5128 	if (((iraflags & IRAF_IS_IPV4) ?
5129 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5130 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5131 	    secure) {
5132 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5133 		    ip6h, ira);
5134 		if (mp == NULL) {
5135 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5136 			/* Note that mp is NULL */
5137 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5138 			return;
5139 		}
5140 	}
5141 
5142 	/*
5143 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5144 	 * check. Only ip_fanout_v4 has that check.
5145 	 */
5146 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5147 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5148 	} else {
5149 		ill_t *rill = ira->ira_rill;
5150 
5151 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5152 		ira->ira_ill = ira->ira_rill = NULL;
5153 		/* Send it upstream */
5154 		(connp->conn_recv)(connp, mp, NULL, ira);
5155 		ira->ira_ill = ill;
5156 		ira->ira_rill = rill;
5157 	}
5158 }
5159 
5160 /*
5161  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5162  * (Unicast fanout is handled in ip_input_v4.)
5163  *
5164  * If SO_REUSEADDR is set all multicast and broadcast packets
5165  * will be delivered to all conns bound to the same port.
5166  *
5167  * If there is at least one matching AF_INET receiver, then we will
5168  * ignore any AF_INET6 receivers.
5169  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5170  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5171  * packets.
5172  *
5173  * Zones notes:
5174  * Earlier in ip_input on a system with multiple shared-IP zones we
5175  * duplicate the multicast and broadcast packets and send them up
5176  * with each explicit zoneid that exists on that ill.
5177  * This means that here we can match the zoneid with SO_ALLZONES being special.
5178  */
5179 void
5180 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5181     ip_recv_attr_t *ira)
5182 {
5183 	ipaddr_t	laddr;
5184 	in6_addr_t	v6faddr;
5185 	conn_t		*connp;
5186 	connf_t		*connfp;
5187 	ipaddr_t	faddr;
5188 	ill_t		*ill = ira->ira_ill;
5189 	ip_stack_t	*ipst = ill->ill_ipst;
5190 
5191 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5192 
5193 	laddr = ipha->ipha_dst;
5194 	faddr = ipha->ipha_src;
5195 
5196 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5197 	mutex_enter(&connfp->connf_lock);
5198 	connp = connfp->connf_head;
5199 
5200 	/*
5201 	 * If SO_REUSEADDR has been set on the first we send the
5202 	 * packet to all clients that have joined the group and
5203 	 * match the port.
5204 	 */
5205 	while (connp != NULL) {
5206 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5207 		    conn_wantpacket(connp, ira, ipha) &&
5208 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5209 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5210 			break;
5211 		connp = connp->conn_next;
5212 	}
5213 
5214 	if (connp == NULL)
5215 		goto notfound;
5216 
5217 	CONN_INC_REF(connp);
5218 
5219 	if (connp->conn_reuseaddr) {
5220 		conn_t		*first_connp = connp;
5221 		conn_t		*next_connp;
5222 		mblk_t		*mp1;
5223 
5224 		connp = connp->conn_next;
5225 		for (;;) {
5226 			while (connp != NULL) {
5227 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5228 				    fport, faddr) &&
5229 				    conn_wantpacket(connp, ira, ipha) &&
5230 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5231 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5232 				    ira, connp)))
5233 					break;
5234 				connp = connp->conn_next;
5235 			}
5236 			if (connp == NULL) {
5237 				/* No more interested clients */
5238 				connp = first_connp;
5239 				break;
5240 			}
5241 			if (((mp1 = dupmsg(mp)) == NULL) &&
5242 			    ((mp1 = copymsg(mp)) == NULL)) {
5243 				/* Memory allocation failed */
5244 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5245 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5246 				connp = first_connp;
5247 				break;
5248 			}
5249 			CONN_INC_REF(connp);
5250 			mutex_exit(&connfp->connf_lock);
5251 
5252 			IP_STAT(ipst, ip_udp_fanmb);
5253 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5254 			    NULL, ira);
5255 			mutex_enter(&connfp->connf_lock);
5256 			/* Follow the next pointer before releasing the conn */
5257 			next_connp = connp->conn_next;
5258 			CONN_DEC_REF(connp);
5259 			connp = next_connp;
5260 		}
5261 	}
5262 
5263 	/* Last one.  Send it upstream. */
5264 	mutex_exit(&connfp->connf_lock);
5265 	IP_STAT(ipst, ip_udp_fanmb);
5266 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5267 	CONN_DEC_REF(connp);
5268 	return;
5269 
5270 notfound:
5271 	mutex_exit(&connfp->connf_lock);
5272 	/*
5273 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5274 	 * have already been matched above, since they live in the IPv4
5275 	 * fanout tables. This implies we only need to
5276 	 * check for IPv6 in6addr_any endpoints here.
5277 	 * Thus we compare using ipv6_all_zeros instead of the destination
5278 	 * address, except for the multicast group membership lookup which
5279 	 * uses the IPv4 destination.
5280 	 */
5281 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5282 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5283 	mutex_enter(&connfp->connf_lock);
5284 	connp = connfp->connf_head;
5285 	/*
5286 	 * IPv4 multicast packet being delivered to an AF_INET6
5287 	 * in6addr_any endpoint.
5288 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5289 	 * and not conn_wantpacket_v6() since any multicast membership is
5290 	 * for an IPv4-mapped multicast address.
5291 	 */
5292 	while (connp != NULL) {
5293 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5294 		    fport, v6faddr) &&
5295 		    conn_wantpacket(connp, ira, ipha) &&
5296 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5297 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5298 			break;
5299 		connp = connp->conn_next;
5300 	}
5301 
5302 	if (connp == NULL) {
5303 		/*
5304 		 * No one bound to this port.  Is
5305 		 * there a client that wants all
5306 		 * unclaimed datagrams?
5307 		 */
5308 		mutex_exit(&connfp->connf_lock);
5309 
5310 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5311 		    NULL) {
5312 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5313 			ip_fanout_proto_v4(mp, ipha, ira);
5314 		} else {
5315 			/*
5316 			 * We used to attempt to send an icmp error here, but
5317 			 * since this is known to be a multicast packet
5318 			 * and we don't send icmp errors in response to
5319 			 * multicast, just drop the packet and give up sooner.
5320 			 */
5321 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5322 			freemsg(mp);
5323 		}
5324 		return;
5325 	}
5326 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5327 
5328 	/*
5329 	 * If SO_REUSEADDR has been set on the first we send the
5330 	 * packet to all clients that have joined the group and
5331 	 * match the port.
5332 	 */
5333 	if (connp->conn_reuseaddr) {
5334 		conn_t		*first_connp = connp;
5335 		conn_t		*next_connp;
5336 		mblk_t		*mp1;
5337 
5338 		CONN_INC_REF(connp);
5339 		connp = connp->conn_next;
5340 		for (;;) {
5341 			while (connp != NULL) {
5342 				if (IPCL_UDP_MATCH_V6(connp, lport,
5343 				    ipv6_all_zeros, fport, v6faddr) &&
5344 				    conn_wantpacket(connp, ira, ipha) &&
5345 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5346 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5347 				    ira, connp)))
5348 					break;
5349 				connp = connp->conn_next;
5350 			}
5351 			if (connp == NULL) {
5352 				/* No more interested clients */
5353 				connp = first_connp;
5354 				break;
5355 			}
5356 			if (((mp1 = dupmsg(mp)) == NULL) &&
5357 			    ((mp1 = copymsg(mp)) == NULL)) {
5358 				/* Memory allocation failed */
5359 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5360 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5361 				connp = first_connp;
5362 				break;
5363 			}
5364 			CONN_INC_REF(connp);
5365 			mutex_exit(&connfp->connf_lock);
5366 
5367 			IP_STAT(ipst, ip_udp_fanmb);
5368 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5369 			    NULL, ira);
5370 			mutex_enter(&connfp->connf_lock);
5371 			/* Follow the next pointer before releasing the conn */
5372 			next_connp = connp->conn_next;
5373 			CONN_DEC_REF(connp);
5374 			connp = next_connp;
5375 		}
5376 	}
5377 
5378 	/* Last one.  Send it upstream. */
5379 	mutex_exit(&connfp->connf_lock);
5380 	IP_STAT(ipst, ip_udp_fanmb);
5381 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5382 	CONN_DEC_REF(connp);
5383 }
5384 
5385 /*
5386  * Split an incoming packet's IPv4 options into the label and the other options.
5387  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5388  * clearing out any leftover label or options.
5389  * Otherwise it just makes ipp point into the packet.
5390  *
5391  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5392  */
5393 int
5394 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5395 {
5396 	uchar_t		*opt;
5397 	uint32_t	totallen;
5398 	uint32_t	optval;
5399 	uint32_t	optlen;
5400 
5401 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5402 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5403 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5404 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5405 
5406 	/*
5407 	 * Get length (in 4 byte octets) of IP header options.
5408 	 */
5409 	totallen = ipha->ipha_version_and_hdr_length -
5410 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5411 
5412 	if (totallen == 0) {
5413 		if (!allocate)
5414 			return (0);
5415 
5416 		/* Clear out anything from a previous packet */
5417 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5418 			kmem_free(ipp->ipp_ipv4_options,
5419 			    ipp->ipp_ipv4_options_len);
5420 			ipp->ipp_ipv4_options = NULL;
5421 			ipp->ipp_ipv4_options_len = 0;
5422 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5423 		}
5424 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5425 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5426 			ipp->ipp_label_v4 = NULL;
5427 			ipp->ipp_label_len_v4 = 0;
5428 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5429 		}
5430 		return (0);
5431 	}
5432 
5433 	totallen <<= 2;
5434 	opt = (uchar_t *)&ipha[1];
5435 	if (!is_system_labeled()) {
5436 
5437 	copyall:
5438 		if (!allocate) {
5439 			if (totallen != 0) {
5440 				ipp->ipp_ipv4_options = opt;
5441 				ipp->ipp_ipv4_options_len = totallen;
5442 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5443 			}
5444 			return (0);
5445 		}
5446 		/* Just copy all of options */
5447 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5448 			if (totallen == ipp->ipp_ipv4_options_len) {
5449 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5450 				return (0);
5451 			}
5452 			kmem_free(ipp->ipp_ipv4_options,
5453 			    ipp->ipp_ipv4_options_len);
5454 			ipp->ipp_ipv4_options = NULL;
5455 			ipp->ipp_ipv4_options_len = 0;
5456 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5457 		}
5458 		if (totallen == 0)
5459 			return (0);
5460 
5461 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5462 		if (ipp->ipp_ipv4_options == NULL)
5463 			return (ENOMEM);
5464 		ipp->ipp_ipv4_options_len = totallen;
5465 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5466 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5467 		return (0);
5468 	}
5469 
5470 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5471 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5472 		ipp->ipp_label_v4 = NULL;
5473 		ipp->ipp_label_len_v4 = 0;
5474 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5475 	}
5476 
5477 	/*
5478 	 * Search for CIPSO option.
5479 	 * We assume CIPSO is first in options if it is present.
5480 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5481 	 * prior to the CIPSO option.
5482 	 */
5483 	while (totallen != 0) {
5484 		switch (optval = opt[IPOPT_OPTVAL]) {
5485 		case IPOPT_EOL:
5486 			return (0);
5487 		case IPOPT_NOP:
5488 			optlen = 1;
5489 			break;
5490 		default:
5491 			if (totallen <= IPOPT_OLEN)
5492 				return (EINVAL);
5493 			optlen = opt[IPOPT_OLEN];
5494 			if (optlen < 2)
5495 				return (EINVAL);
5496 		}
5497 		if (optlen > totallen)
5498 			return (EINVAL);
5499 
5500 		switch (optval) {
5501 		case IPOPT_COMSEC:
5502 			if (!allocate) {
5503 				ipp->ipp_label_v4 = opt;
5504 				ipp->ipp_label_len_v4 = optlen;
5505 				ipp->ipp_fields |= IPPF_LABEL_V4;
5506 			} else {
5507 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5508 				    KM_NOSLEEP);
5509 				if (ipp->ipp_label_v4 == NULL)
5510 					return (ENOMEM);
5511 				ipp->ipp_label_len_v4 = optlen;
5512 				ipp->ipp_fields |= IPPF_LABEL_V4;
5513 				bcopy(opt, ipp->ipp_label_v4, optlen);
5514 			}
5515 			totallen -= optlen;
5516 			opt += optlen;
5517 
5518 			/* Skip padding bytes until we get to a multiple of 4 */
5519 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5520 				totallen--;
5521 				opt++;
5522 			}
5523 			/* Remaining as ipp_ipv4_options */
5524 			goto copyall;
5525 		}
5526 		totallen -= optlen;
5527 		opt += optlen;
5528 	}
5529 	/* No CIPSO found; return everything as ipp_ipv4_options */
5530 	totallen = ipha->ipha_version_and_hdr_length -
5531 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5532 	totallen <<= 2;
5533 	opt = (uchar_t *)&ipha[1];
5534 	goto copyall;
5535 }
5536 
5537 /*
5538  * Efficient versions of lookup for an IRE when we only
5539  * match the address.
5540  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5541  * Does not handle multicast addresses.
5542  */
5543 uint_t
5544 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5545 {
5546 	ire_t *ire;
5547 	uint_t result;
5548 
5549 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5550 	ASSERT(ire != NULL);
5551 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5552 		result = IRE_NOROUTE;
5553 	else
5554 		result = ire->ire_type;
5555 	ire_refrele(ire);
5556 	return (result);
5557 }
5558 
5559 /*
5560  * Efficient versions of lookup for an IRE when we only
5561  * match the address.
5562  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5563  * Does not handle multicast addresses.
5564  */
5565 uint_t
5566 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5567 {
5568 	ire_t *ire;
5569 	uint_t result;
5570 
5571 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5572 	ASSERT(ire != NULL);
5573 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5574 		result = IRE_NOROUTE;
5575 	else
5576 		result = ire->ire_type;
5577 	ire_refrele(ire);
5578 	return (result);
5579 }
5580 
5581 /*
5582  * Nobody should be sending
5583  * packets up this stream
5584  */
5585 static void
5586 ip_lrput(queue_t *q, mblk_t *mp)
5587 {
5588 	switch (mp->b_datap->db_type) {
5589 	case M_FLUSH:
5590 		/* Turn around */
5591 		if (*mp->b_rptr & FLUSHW) {
5592 			*mp->b_rptr &= ~FLUSHR;
5593 			qreply(q, mp);
5594 			return;
5595 		}
5596 		break;
5597 	}
5598 	freemsg(mp);
5599 }
5600 
5601 /* Nobody should be sending packets down this stream */
5602 /* ARGSUSED */
5603 void
5604 ip_lwput(queue_t *q, mblk_t *mp)
5605 {
5606 	freemsg(mp);
5607 }
5608 
5609 /*
5610  * Move the first hop in any source route to ipha_dst and remove that part of
5611  * the source route.  Called by other protocols.  Errors in option formatting
5612  * are ignored - will be handled by ip_output_options. Return the final
5613  * destination (either ipha_dst or the last entry in a source route.)
5614  */
5615 ipaddr_t
5616 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5617 {
5618 	ipoptp_t	opts;
5619 	uchar_t		*opt;
5620 	uint8_t		optval;
5621 	uint8_t		optlen;
5622 	ipaddr_t	dst;
5623 	int		i;
5624 	ip_stack_t	*ipst = ns->netstack_ip;
5625 
5626 	ip2dbg(("ip_massage_options\n"));
5627 	dst = ipha->ipha_dst;
5628 	for (optval = ipoptp_first(&opts, ipha);
5629 	    optval != IPOPT_EOL;
5630 	    optval = ipoptp_next(&opts)) {
5631 		opt = opts.ipoptp_cur;
5632 		switch (optval) {
5633 			uint8_t off;
5634 		case IPOPT_SSRR:
5635 		case IPOPT_LSRR:
5636 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5637 				ip1dbg(("ip_massage_options: bad src route\n"));
5638 				break;
5639 			}
5640 			optlen = opts.ipoptp_len;
5641 			off = opt[IPOPT_OFFSET];
5642 			off--;
5643 		redo_srr:
5644 			if (optlen < IP_ADDR_LEN ||
5645 			    off > optlen - IP_ADDR_LEN) {
5646 				/* End of source route */
5647 				ip1dbg(("ip_massage_options: end of SR\n"));
5648 				break;
5649 			}
5650 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5651 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5652 			    ntohl(dst)));
5653 			/*
5654 			 * Check if our address is present more than
5655 			 * once as consecutive hops in source route.
5656 			 * XXX verify per-interface ip_forwarding
5657 			 * for source route?
5658 			 */
5659 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5660 				off += IP_ADDR_LEN;
5661 				goto redo_srr;
5662 			}
5663 			if (dst == htonl(INADDR_LOOPBACK)) {
5664 				ip1dbg(("ip_massage_options: loopback addr in "
5665 				    "source route!\n"));
5666 				break;
5667 			}
5668 			/*
5669 			 * Update ipha_dst to be the first hop and remove the
5670 			 * first hop from the source route (by overwriting
5671 			 * part of the option with NOP options).
5672 			 */
5673 			ipha->ipha_dst = dst;
5674 			/* Put the last entry in dst */
5675 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5676 			    3;
5677 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5678 
5679 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5680 			    ntohl(dst)));
5681 			/* Move down and overwrite */
5682 			opt[IP_ADDR_LEN] = opt[0];
5683 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5684 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5685 			for (i = 0; i < IP_ADDR_LEN; i++)
5686 				opt[i] = IPOPT_NOP;
5687 			break;
5688 		}
5689 	}
5690 	return (dst);
5691 }
5692 
5693 /*
5694  * Return the network mask
5695  * associated with the specified address.
5696  */
5697 ipaddr_t
5698 ip_net_mask(ipaddr_t addr)
5699 {
5700 	uchar_t	*up = (uchar_t *)&addr;
5701 	ipaddr_t mask = 0;
5702 	uchar_t	*maskp = (uchar_t *)&mask;
5703 
5704 #if defined(__i386) || defined(__amd64)
5705 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5706 #endif
5707 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5708 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5709 #endif
5710 	if (CLASSD(addr)) {
5711 		maskp[0] = 0xF0;
5712 		return (mask);
5713 	}
5714 
5715 	/* We assume Class E default netmask to be 32 */
5716 	if (CLASSE(addr))
5717 		return (0xffffffffU);
5718 
5719 	if (addr == 0)
5720 		return (0);
5721 	maskp[0] = 0xFF;
5722 	if ((up[0] & 0x80) == 0)
5723 		return (mask);
5724 
5725 	maskp[1] = 0xFF;
5726 	if ((up[0] & 0xC0) == 0x80)
5727 		return (mask);
5728 
5729 	maskp[2] = 0xFF;
5730 	if ((up[0] & 0xE0) == 0xC0)
5731 		return (mask);
5732 
5733 	/* Otherwise return no mask */
5734 	return ((ipaddr_t)0);
5735 }
5736 
5737 /* Name/Value Table Lookup Routine */
5738 char *
5739 ip_nv_lookup(nv_t *nv, int value)
5740 {
5741 	if (!nv)
5742 		return (NULL);
5743 	for (; nv->nv_name; nv++) {
5744 		if (nv->nv_value == value)
5745 			return (nv->nv_name);
5746 	}
5747 	return ("unknown");
5748 }
5749 
5750 static int
5751 ip_wait_for_info_ack(ill_t *ill)
5752 {
5753 	int err;
5754 
5755 	mutex_enter(&ill->ill_lock);
5756 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5757 		/*
5758 		 * Return value of 0 indicates a pending signal.
5759 		 */
5760 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5761 		if (err == 0) {
5762 			mutex_exit(&ill->ill_lock);
5763 			return (EINTR);
5764 		}
5765 	}
5766 	mutex_exit(&ill->ill_lock);
5767 	/*
5768 	 * ip_rput_other could have set an error  in ill_error on
5769 	 * receipt of M_ERROR.
5770 	 */
5771 	return (ill->ill_error);
5772 }
5773 
5774 /*
5775  * This is a module open, i.e. this is a control stream for access
5776  * to a DLPI device.  We allocate an ill_t as the instance data in
5777  * this case.
5778  */
5779 static int
5780 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5781 {
5782 	ill_t	*ill;
5783 	int	err;
5784 	zoneid_t zoneid;
5785 	netstack_t *ns;
5786 	ip_stack_t *ipst;
5787 
5788 	/*
5789 	 * Prevent unprivileged processes from pushing IP so that
5790 	 * they can't send raw IP.
5791 	 */
5792 	if (secpolicy_net_rawaccess(credp) != 0)
5793 		return (EPERM);
5794 
5795 	ns = netstack_find_by_cred(credp);
5796 	ASSERT(ns != NULL);
5797 	ipst = ns->netstack_ip;
5798 	ASSERT(ipst != NULL);
5799 
5800 	/*
5801 	 * For exclusive stacks we set the zoneid to zero
5802 	 * to make IP operate as if in the global zone.
5803 	 */
5804 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5805 		zoneid = GLOBAL_ZONEID;
5806 	else
5807 		zoneid = crgetzoneid(credp);
5808 
5809 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5810 	q->q_ptr = WR(q)->q_ptr = ill;
5811 	ill->ill_ipst = ipst;
5812 	ill->ill_zoneid = zoneid;
5813 
5814 	/*
5815 	 * ill_init initializes the ill fields and then sends down
5816 	 * down a DL_INFO_REQ after calling qprocson.
5817 	 */
5818 	err = ill_init(q, ill);
5819 
5820 	if (err != 0) {
5821 		mi_free(ill);
5822 		netstack_rele(ipst->ips_netstack);
5823 		q->q_ptr = NULL;
5824 		WR(q)->q_ptr = NULL;
5825 		return (err);
5826 	}
5827 
5828 	/*
5829 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5830 	 *
5831 	 * ill_init initializes the ipsq marking this thread as
5832 	 * writer
5833 	 */
5834 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5835 	err = ip_wait_for_info_ack(ill);
5836 	if (err == 0)
5837 		ill->ill_credp = credp;
5838 	else
5839 		goto fail;
5840 
5841 	crhold(credp);
5842 
5843 	mutex_enter(&ipst->ips_ip_mi_lock);
5844 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5845 	    sflag, credp);
5846 	mutex_exit(&ipst->ips_ip_mi_lock);
5847 fail:
5848 	if (err) {
5849 		(void) ip_close(q, 0);
5850 		return (err);
5851 	}
5852 	return (0);
5853 }
5854 
5855 /* For /dev/ip aka AF_INET open */
5856 int
5857 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5858 {
5859 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5860 }
5861 
5862 /* For /dev/ip6 aka AF_INET6 open */
5863 int
5864 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5865 {
5866 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5867 }
5868 
5869 /* IP open routine. */
5870 int
5871 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5872     boolean_t isv6)
5873 {
5874 	conn_t 		*connp;
5875 	major_t		maj;
5876 	zoneid_t	zoneid;
5877 	netstack_t	*ns;
5878 	ip_stack_t	*ipst;
5879 
5880 	/* Allow reopen. */
5881 	if (q->q_ptr != NULL)
5882 		return (0);
5883 
5884 	if (sflag & MODOPEN) {
5885 		/* This is a module open */
5886 		return (ip_modopen(q, devp, flag, sflag, credp));
5887 	}
5888 
5889 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5890 		/*
5891 		 * Non streams based socket looking for a stream
5892 		 * to access IP
5893 		 */
5894 		return (ip_helper_stream_setup(q, devp, flag, sflag,
5895 		    credp, isv6));
5896 	}
5897 
5898 	ns = netstack_find_by_cred(credp);
5899 	ASSERT(ns != NULL);
5900 	ipst = ns->netstack_ip;
5901 	ASSERT(ipst != NULL);
5902 
5903 	/*
5904 	 * For exclusive stacks we set the zoneid to zero
5905 	 * to make IP operate as if in the global zone.
5906 	 */
5907 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5908 		zoneid = GLOBAL_ZONEID;
5909 	else
5910 		zoneid = crgetzoneid(credp);
5911 
5912 	/*
5913 	 * We are opening as a device. This is an IP client stream, and we
5914 	 * allocate an conn_t as the instance data.
5915 	 */
5916 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
5917 
5918 	/*
5919 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
5920 	 * done by netstack_find_by_cred()
5921 	 */
5922 	netstack_rele(ipst->ips_netstack);
5923 
5924 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
5925 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
5926 	connp->conn_ixa->ixa_zoneid = zoneid;
5927 	connp->conn_zoneid = zoneid;
5928 
5929 	connp->conn_rq = q;
5930 	q->q_ptr = WR(q)->q_ptr = connp;
5931 
5932 	/* Minor tells us which /dev entry was opened */
5933 	if (isv6) {
5934 		connp->conn_family = AF_INET6;
5935 		connp->conn_ipversion = IPV6_VERSION;
5936 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
5937 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
5938 	} else {
5939 		connp->conn_family = AF_INET;
5940 		connp->conn_ipversion = IPV4_VERSION;
5941 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
5942 	}
5943 
5944 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
5945 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
5946 		connp->conn_minor_arena = ip_minor_arena_la;
5947 	} else {
5948 		/*
5949 		 * Either minor numbers in the large arena were exhausted
5950 		 * or a non socket application is doing the open.
5951 		 * Try to allocate from the small arena.
5952 		 */
5953 		if ((connp->conn_dev =
5954 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
5955 			/* CONN_DEC_REF takes care of netstack_rele() */
5956 			q->q_ptr = WR(q)->q_ptr = NULL;
5957 			CONN_DEC_REF(connp);
5958 			return (EBUSY);
5959 		}
5960 		connp->conn_minor_arena = ip_minor_arena_sa;
5961 	}
5962 
5963 	maj = getemajor(*devp);
5964 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
5965 
5966 	/*
5967 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
5968 	 */
5969 	connp->conn_cred = credp;
5970 	connp->conn_cpid = curproc->p_pid;
5971 	/* Cache things in ixa without an extra refhold */
5972 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
5973 	connp->conn_ixa->ixa_cred = connp->conn_cred;
5974 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
5975 	if (is_system_labeled())
5976 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
5977 
5978 	/*
5979 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
5980 	 */
5981 	connp->conn_recv = ip_conn_input;
5982 	connp->conn_recvicmp = ip_conn_input_icmp;
5983 
5984 	crhold(connp->conn_cred);
5985 
5986 	/*
5987 	 * If the caller has the process-wide flag set, then default to MAC
5988 	 * exempt mode.  This allows read-down to unlabeled hosts.
5989 	 */
5990 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5991 		connp->conn_mac_mode = CONN_MAC_AWARE;
5992 
5993 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
5994 
5995 	connp->conn_rq = q;
5996 	connp->conn_wq = WR(q);
5997 
5998 	/* Non-zero default values */
5999 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6000 
6001 	/*
6002 	 * Make the conn globally visible to walkers
6003 	 */
6004 	ASSERT(connp->conn_ref == 1);
6005 	mutex_enter(&connp->conn_lock);
6006 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6007 	mutex_exit(&connp->conn_lock);
6008 
6009 	qprocson(q);
6010 
6011 	return (0);
6012 }
6013 
6014 /*
6015  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6016  * all of them are copied to the conn_t. If the req is "zero", the policy is
6017  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6018  * fields.
6019  * We keep only the latest setting of the policy and thus policy setting
6020  * is not incremental/cumulative.
6021  *
6022  * Requests to set policies with multiple alternative actions will
6023  * go through a different API.
6024  */
6025 int
6026 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6027 {
6028 	uint_t ah_req = 0;
6029 	uint_t esp_req = 0;
6030 	uint_t se_req = 0;
6031 	ipsec_act_t *actp = NULL;
6032 	uint_t nact;
6033 	ipsec_policy_head_t *ph;
6034 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6035 	int error = 0;
6036 	netstack_t	*ns = connp->conn_netstack;
6037 	ip_stack_t	*ipst = ns->netstack_ip;
6038 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6039 
6040 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6041 
6042 	/*
6043 	 * The IP_SEC_OPT option does not allow variable length parameters,
6044 	 * hence a request cannot be NULL.
6045 	 */
6046 	if (req == NULL)
6047 		return (EINVAL);
6048 
6049 	ah_req = req->ipsr_ah_req;
6050 	esp_req = req->ipsr_esp_req;
6051 	se_req = req->ipsr_self_encap_req;
6052 
6053 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6054 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6055 		return (EINVAL);
6056 
6057 	/*
6058 	 * Are we dealing with a request to reset the policy (i.e.
6059 	 * zero requests).
6060 	 */
6061 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6062 	    (esp_req & REQ_MASK) == 0 &&
6063 	    (se_req & REQ_MASK) == 0);
6064 
6065 	if (!is_pol_reset) {
6066 		/*
6067 		 * If we couldn't load IPsec, fail with "protocol
6068 		 * not supported".
6069 		 * IPsec may not have been loaded for a request with zero
6070 		 * policies, so we don't fail in this case.
6071 		 */
6072 		mutex_enter(&ipss->ipsec_loader_lock);
6073 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6074 			mutex_exit(&ipss->ipsec_loader_lock);
6075 			return (EPROTONOSUPPORT);
6076 		}
6077 		mutex_exit(&ipss->ipsec_loader_lock);
6078 
6079 		/*
6080 		 * Test for valid requests. Invalid algorithms
6081 		 * need to be tested by IPsec code because new
6082 		 * algorithms can be added dynamically.
6083 		 */
6084 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6085 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6086 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6087 			return (EINVAL);
6088 		}
6089 
6090 		/*
6091 		 * Only privileged users can issue these
6092 		 * requests.
6093 		 */
6094 		if (((ah_req & IPSEC_PREF_NEVER) ||
6095 		    (esp_req & IPSEC_PREF_NEVER) ||
6096 		    (se_req & IPSEC_PREF_NEVER)) &&
6097 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6098 			return (EPERM);
6099 		}
6100 
6101 		/*
6102 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6103 		 * are mutually exclusive.
6104 		 */
6105 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6106 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6107 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6108 			/* Both of them are set */
6109 			return (EINVAL);
6110 		}
6111 	}
6112 
6113 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6114 
6115 	/*
6116 	 * If we have already cached policies in conn_connect(), don't
6117 	 * let them change now. We cache policies for connections
6118 	 * whose src,dst [addr, port] is known.
6119 	 */
6120 	if (connp->conn_policy_cached) {
6121 		return (EINVAL);
6122 	}
6123 
6124 	/*
6125 	 * We have a zero policies, reset the connection policy if already
6126 	 * set. This will cause the connection to inherit the
6127 	 * global policy, if any.
6128 	 */
6129 	if (is_pol_reset) {
6130 		if (connp->conn_policy != NULL) {
6131 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6132 			connp->conn_policy = NULL;
6133 		}
6134 		connp->conn_in_enforce_policy = B_FALSE;
6135 		connp->conn_out_enforce_policy = B_FALSE;
6136 		return (0);
6137 	}
6138 
6139 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6140 	    ipst->ips_netstack);
6141 	if (ph == NULL)
6142 		goto enomem;
6143 
6144 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6145 	if (actp == NULL)
6146 		goto enomem;
6147 
6148 	/*
6149 	 * Always insert IPv4 policy entries, since they can also apply to
6150 	 * ipv6 sockets being used in ipv4-compat mode.
6151 	 */
6152 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6153 	    IPSEC_TYPE_INBOUND, ns))
6154 		goto enomem;
6155 	is_pol_inserted = B_TRUE;
6156 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6157 	    IPSEC_TYPE_OUTBOUND, ns))
6158 		goto enomem;
6159 
6160 	/*
6161 	 * We're looking at a v6 socket, also insert the v6-specific
6162 	 * entries.
6163 	 */
6164 	if (connp->conn_family == AF_INET6) {
6165 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6166 		    IPSEC_TYPE_INBOUND, ns))
6167 			goto enomem;
6168 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6169 		    IPSEC_TYPE_OUTBOUND, ns))
6170 			goto enomem;
6171 	}
6172 
6173 	ipsec_actvec_free(actp, nact);
6174 
6175 	/*
6176 	 * If the requests need security, set enforce_policy.
6177 	 * If the requests are IPSEC_PREF_NEVER, one should
6178 	 * still set conn_out_enforce_policy so that ip_set_destination
6179 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6180 	 * for connections that we don't cache policy in at connect time,
6181 	 * if global policy matches in ip_output_attach_policy, we
6182 	 * don't wrongly inherit global policy. Similarly, we need
6183 	 * to set conn_in_enforce_policy also so that we don't verify
6184 	 * policy wrongly.
6185 	 */
6186 	if ((ah_req & REQ_MASK) != 0 ||
6187 	    (esp_req & REQ_MASK) != 0 ||
6188 	    (se_req & REQ_MASK) != 0) {
6189 		connp->conn_in_enforce_policy = B_TRUE;
6190 		connp->conn_out_enforce_policy = B_TRUE;
6191 	}
6192 
6193 	return (error);
6194 #undef REQ_MASK
6195 
6196 	/*
6197 	 * Common memory-allocation-failure exit path.
6198 	 */
6199 enomem:
6200 	if (actp != NULL)
6201 		ipsec_actvec_free(actp, nact);
6202 	if (is_pol_inserted)
6203 		ipsec_polhead_flush(ph, ns);
6204 	return (ENOMEM);
6205 }
6206 
6207 /*
6208  * Set socket options for joining and leaving multicast groups.
6209  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6210  * The caller has already check that the option name is consistent with
6211  * the address family of the socket.
6212  */
6213 int
6214 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6215     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6216 {
6217 	int		*i1 = (int *)invalp;
6218 	int		error = 0;
6219 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6220 	struct ip_mreq	*v4_mreqp;
6221 	struct ipv6_mreq *v6_mreqp;
6222 	struct group_req *greqp;
6223 	ire_t *ire;
6224 	boolean_t done = B_FALSE;
6225 	ipaddr_t ifaddr;
6226 	in6_addr_t v6group;
6227 	uint_t ifindex;
6228 	boolean_t mcast_opt = B_TRUE;
6229 	mcast_record_t fmode;
6230 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6231 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6232 
6233 	switch (name) {
6234 	case IP_ADD_MEMBERSHIP:
6235 	case IPV6_JOIN_GROUP:
6236 		mcast_opt = B_FALSE;
6237 		/* FALLTHRU */
6238 	case MCAST_JOIN_GROUP:
6239 		fmode = MODE_IS_EXCLUDE;
6240 		optfn = ip_opt_add_group;
6241 		break;
6242 
6243 	case IP_DROP_MEMBERSHIP:
6244 	case IPV6_LEAVE_GROUP:
6245 		mcast_opt = B_FALSE;
6246 		/* FALLTHRU */
6247 	case MCAST_LEAVE_GROUP:
6248 		fmode = MODE_IS_INCLUDE;
6249 		optfn = ip_opt_delete_group;
6250 		break;
6251 	default:
6252 		ASSERT(0);
6253 	}
6254 
6255 	if (mcast_opt) {
6256 		struct sockaddr_in *sin;
6257 		struct sockaddr_in6 *sin6;
6258 
6259 		greqp = (struct group_req *)i1;
6260 		if (greqp->gr_group.ss_family == AF_INET) {
6261 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6262 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6263 		} else {
6264 			if (!inet6)
6265 				return (EINVAL);	/* Not on INET socket */
6266 
6267 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6268 			v6group = sin6->sin6_addr;
6269 		}
6270 		ifaddr = INADDR_ANY;
6271 		ifindex = greqp->gr_interface;
6272 	} else if (inet6) {
6273 		v6_mreqp = (struct ipv6_mreq *)i1;
6274 		v6group = v6_mreqp->ipv6mr_multiaddr;
6275 		ifaddr = INADDR_ANY;
6276 		ifindex = v6_mreqp->ipv6mr_interface;
6277 	} else {
6278 		v4_mreqp = (struct ip_mreq *)i1;
6279 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6280 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6281 		ifindex = 0;
6282 	}
6283 
6284 	/*
6285 	 * In the multirouting case, we need to replicate
6286 	 * the request on all interfaces that will take part
6287 	 * in replication.  We do so because multirouting is
6288 	 * reflective, thus we will probably receive multi-
6289 	 * casts on those interfaces.
6290 	 * The ip_multirt_apply_membership() succeeds if
6291 	 * the operation succeeds on at least one interface.
6292 	 */
6293 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6294 		ipaddr_t group;
6295 
6296 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6297 
6298 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6299 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6300 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6301 	} else {
6302 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6303 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6304 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6305 	}
6306 	if (ire != NULL) {
6307 		if (ire->ire_flags & RTF_MULTIRT) {
6308 			error = ip_multirt_apply_membership(optfn, ire, connp,
6309 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6310 			done = B_TRUE;
6311 		}
6312 		ire_refrele(ire);
6313 	}
6314 
6315 	if (!done) {
6316 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6317 		    fmode, &ipv6_all_zeros);
6318 	}
6319 	return (error);
6320 }
6321 
6322 /*
6323  * Set socket options for joining and leaving multicast groups
6324  * for specific sources.
6325  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6326  * The caller has already check that the option name is consistent with
6327  * the address family of the socket.
6328  */
6329 int
6330 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6331     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6332 {
6333 	int		*i1 = (int *)invalp;
6334 	int		error = 0;
6335 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6336 	struct ip_mreq_source *imreqp;
6337 	struct group_source_req *gsreqp;
6338 	in6_addr_t v6group, v6src;
6339 	uint32_t ifindex;
6340 	ipaddr_t ifaddr;
6341 	boolean_t mcast_opt = B_TRUE;
6342 	mcast_record_t fmode;
6343 	ire_t *ire;
6344 	boolean_t done = B_FALSE;
6345 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6346 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6347 
6348 	switch (name) {
6349 	case IP_BLOCK_SOURCE:
6350 		mcast_opt = B_FALSE;
6351 		/* FALLTHRU */
6352 	case MCAST_BLOCK_SOURCE:
6353 		fmode = MODE_IS_EXCLUDE;
6354 		optfn = ip_opt_add_group;
6355 		break;
6356 
6357 	case IP_UNBLOCK_SOURCE:
6358 		mcast_opt = B_FALSE;
6359 		/* FALLTHRU */
6360 	case MCAST_UNBLOCK_SOURCE:
6361 		fmode = MODE_IS_EXCLUDE;
6362 		optfn = ip_opt_delete_group;
6363 		break;
6364 
6365 	case IP_ADD_SOURCE_MEMBERSHIP:
6366 		mcast_opt = B_FALSE;
6367 		/* FALLTHRU */
6368 	case MCAST_JOIN_SOURCE_GROUP:
6369 		fmode = MODE_IS_INCLUDE;
6370 		optfn = ip_opt_add_group;
6371 		break;
6372 
6373 	case IP_DROP_SOURCE_MEMBERSHIP:
6374 		mcast_opt = B_FALSE;
6375 		/* FALLTHRU */
6376 	case MCAST_LEAVE_SOURCE_GROUP:
6377 		fmode = MODE_IS_INCLUDE;
6378 		optfn = ip_opt_delete_group;
6379 		break;
6380 	default:
6381 		ASSERT(0);
6382 	}
6383 
6384 	if (mcast_opt) {
6385 		gsreqp = (struct group_source_req *)i1;
6386 		ifindex = gsreqp->gsr_interface;
6387 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6388 			struct sockaddr_in *s;
6389 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6390 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6391 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6392 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6393 		} else {
6394 			struct sockaddr_in6 *s6;
6395 
6396 			if (!inet6)
6397 				return (EINVAL);	/* Not on INET socket */
6398 
6399 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6400 			v6group = s6->sin6_addr;
6401 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6402 			v6src = s6->sin6_addr;
6403 		}
6404 		ifaddr = INADDR_ANY;
6405 	} else {
6406 		imreqp = (struct ip_mreq_source *)i1;
6407 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6408 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6409 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6410 		ifindex = 0;
6411 	}
6412 
6413 	/*
6414 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6415 	 */
6416 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6417 		v6src = ipv6_all_zeros;
6418 
6419 	/*
6420 	 * In the multirouting case, we need to replicate
6421 	 * the request as noted in the mcast cases above.
6422 	 */
6423 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6424 		ipaddr_t group;
6425 
6426 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6427 
6428 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6429 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6430 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6431 	} else {
6432 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6433 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6434 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6435 	}
6436 	if (ire != NULL) {
6437 		if (ire->ire_flags & RTF_MULTIRT) {
6438 			error = ip_multirt_apply_membership(optfn, ire, connp,
6439 			    checkonly, &v6group, fmode, &v6src);
6440 			done = B_TRUE;
6441 		}
6442 		ire_refrele(ire);
6443 	}
6444 	if (!done) {
6445 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6446 		    fmode, &v6src);
6447 	}
6448 	return (error);
6449 }
6450 
6451 /*
6452  * Given a destination address and a pointer to where to put the information
6453  * this routine fills in the mtuinfo.
6454  * The socket must be connected.
6455  * For sctp conn_faddr is the primary address.
6456  */
6457 int
6458 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6459 {
6460 	uint32_t	pmtu = IP_MAXPACKET;
6461 	uint_t		scopeid;
6462 
6463 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6464 		return (-1);
6465 
6466 	/* In case we never sent or called ip_set_destination_v4/v6 */
6467 	if (ixa->ixa_ire != NULL)
6468 		pmtu = ip_get_pmtu(ixa);
6469 
6470 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6471 		scopeid = ixa->ixa_scopeid;
6472 	else
6473 		scopeid = 0;
6474 
6475 	bzero(mtuinfo, sizeof (*mtuinfo));
6476 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6477 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6478 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6479 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6480 	mtuinfo->ip6m_mtu = pmtu;
6481 
6482 	return (sizeof (struct ip6_mtuinfo));
6483 }
6484 
6485 /*
6486  * When the src multihoming is changed from weak to [strong, preferred]
6487  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6488  * and identify routes that were created by user-applications in the
6489  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6490  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6491  * is selected by finding an interface route for the gateway.
6492  */
6493 /* ARGSUSED */
6494 void
6495 ip_ire_rebind_walker(ire_t *ire, void *notused)
6496 {
6497 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6498 		return;
6499 	ire_rebind(ire);
6500 	ire_delete(ire);
6501 }
6502 
6503 /*
6504  * When the src multihoming is changed from  [strong, preferred] to weak,
6505  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6506  * set any entries that were created by user-applications in the unbound state
6507  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6508  */
6509 /* ARGSUSED */
6510 void
6511 ip_ire_unbind_walker(ire_t *ire, void *notused)
6512 {
6513 	ire_t *new_ire;
6514 
6515 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6516 		return;
6517 	if (ire->ire_ipversion == IPV6_VERSION) {
6518 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6519 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6520 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6521 	} else {
6522 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6523 		    (uchar_t *)&ire->ire_mask,
6524 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6525 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6526 	}
6527 	if (new_ire == NULL)
6528 		return;
6529 	new_ire->ire_unbound = B_TRUE;
6530 	/*
6531 	 * The bound ire must first be deleted so that we don't return
6532 	 * the existing one on the attempt to add the unbound new_ire.
6533 	 */
6534 	ire_delete(ire);
6535 	new_ire = ire_add(new_ire);
6536 	if (new_ire != NULL)
6537 		ire_refrele(new_ire);
6538 }
6539 
6540 /*
6541  * When the settings of ip*_strict_src_multihoming tunables are changed,
6542  * all cached routes need to be recomputed. This recomputation needs to be
6543  * done when going from weaker to stronger modes so that the cached ire
6544  * for the connection does not violate the current ip*_strict_src_multihoming
6545  * setting. It also needs to be done when going from stronger to weaker modes,
6546  * so that we fall back to matching on the longest-matching-route (as opposed
6547  * to a shorter match that may have been selected in the strong mode
6548  * to satisfy src_multihoming settings).
6549  *
6550  * The cached ixa_ire entires for all conn_t entries are marked as
6551  * "verify" so that they will be recomputed for the next packet.
6552  */
6553 void
6554 conn_ire_revalidate(conn_t *connp, void *arg)
6555 {
6556 	boolean_t isv6 = (boolean_t)arg;
6557 
6558 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6559 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6560 		return;
6561 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6562 }
6563 
6564 /*
6565  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6566  * When an ipf is passed here for the first time, if
6567  * we already have in-order fragments on the queue, we convert from the fast-
6568  * path reassembly scheme to the hard-case scheme.  From then on, additional
6569  * fragments are reassembled here.  We keep track of the start and end offsets
6570  * of each piece, and the number of holes in the chain.  When the hole count
6571  * goes to zero, we are done!
6572  *
6573  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6574  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6575  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6576  * after the call to ip_reassemble().
6577  */
6578 int
6579 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6580     size_t msg_len)
6581 {
6582 	uint_t	end;
6583 	mblk_t	*next_mp;
6584 	mblk_t	*mp1;
6585 	uint_t	offset;
6586 	boolean_t incr_dups = B_TRUE;
6587 	boolean_t offset_zero_seen = B_FALSE;
6588 	boolean_t pkt_boundary_checked = B_FALSE;
6589 
6590 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6591 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6592 
6593 	/* Add in byte count */
6594 	ipf->ipf_count += msg_len;
6595 	if (ipf->ipf_end) {
6596 		/*
6597 		 * We were part way through in-order reassembly, but now there
6598 		 * is a hole.  We walk through messages already queued, and
6599 		 * mark them for hard case reassembly.  We know that up till
6600 		 * now they were in order starting from offset zero.
6601 		 */
6602 		offset = 0;
6603 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6604 			IP_REASS_SET_START(mp1, offset);
6605 			if (offset == 0) {
6606 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6607 				offset = -ipf->ipf_nf_hdr_len;
6608 			}
6609 			offset += mp1->b_wptr - mp1->b_rptr;
6610 			IP_REASS_SET_END(mp1, offset);
6611 		}
6612 		/* One hole at the end. */
6613 		ipf->ipf_hole_cnt = 1;
6614 		/* Brand it as a hard case, forever. */
6615 		ipf->ipf_end = 0;
6616 	}
6617 	/* Walk through all the new pieces. */
6618 	do {
6619 		end = start + (mp->b_wptr - mp->b_rptr);
6620 		/*
6621 		 * If start is 0, decrease 'end' only for the first mblk of
6622 		 * the fragment. Otherwise 'end' can get wrong value in the
6623 		 * second pass of the loop if first mblk is exactly the
6624 		 * size of ipf_nf_hdr_len.
6625 		 */
6626 		if (start == 0 && !offset_zero_seen) {
6627 			/* First segment */
6628 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6629 			end -= ipf->ipf_nf_hdr_len;
6630 			offset_zero_seen = B_TRUE;
6631 		}
6632 		next_mp = mp->b_cont;
6633 		/*
6634 		 * We are checking to see if there is any interesing data
6635 		 * to process.  If there isn't and the mblk isn't the
6636 		 * one which carries the unfragmentable header then we
6637 		 * drop it.  It's possible to have just the unfragmentable
6638 		 * header come through without any data.  That needs to be
6639 		 * saved.
6640 		 *
6641 		 * If the assert at the top of this function holds then the
6642 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6643 		 * is infrequently traveled enough that the test is left in
6644 		 * to protect against future code changes which break that
6645 		 * invariant.
6646 		 */
6647 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6648 			/* Empty.  Blast it. */
6649 			IP_REASS_SET_START(mp, 0);
6650 			IP_REASS_SET_END(mp, 0);
6651 			/*
6652 			 * If the ipf points to the mblk we are about to free,
6653 			 * update ipf to point to the next mblk (or NULL
6654 			 * if none).
6655 			 */
6656 			if (ipf->ipf_mp->b_cont == mp)
6657 				ipf->ipf_mp->b_cont = next_mp;
6658 			freeb(mp);
6659 			continue;
6660 		}
6661 		mp->b_cont = NULL;
6662 		IP_REASS_SET_START(mp, start);
6663 		IP_REASS_SET_END(mp, end);
6664 		if (!ipf->ipf_tail_mp) {
6665 			ipf->ipf_tail_mp = mp;
6666 			ipf->ipf_mp->b_cont = mp;
6667 			if (start == 0 || !more) {
6668 				ipf->ipf_hole_cnt = 1;
6669 				/*
6670 				 * if the first fragment comes in more than one
6671 				 * mblk, this loop will be executed for each
6672 				 * mblk. Need to adjust hole count so exiting
6673 				 * this routine will leave hole count at 1.
6674 				 */
6675 				if (next_mp)
6676 					ipf->ipf_hole_cnt++;
6677 			} else
6678 				ipf->ipf_hole_cnt = 2;
6679 			continue;
6680 		} else if (ipf->ipf_last_frag_seen && !more &&
6681 		    !pkt_boundary_checked) {
6682 			/*
6683 			 * We check datagram boundary only if this fragment
6684 			 * claims to be the last fragment and we have seen a
6685 			 * last fragment in the past too. We do this only
6686 			 * once for a given fragment.
6687 			 *
6688 			 * start cannot be 0 here as fragments with start=0
6689 			 * and MF=0 gets handled as a complete packet. These
6690 			 * fragments should not reach here.
6691 			 */
6692 
6693 			if (start + msgdsize(mp) !=
6694 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6695 				/*
6696 				 * We have two fragments both of which claim
6697 				 * to be the last fragment but gives conflicting
6698 				 * information about the whole datagram size.
6699 				 * Something fishy is going on. Drop the
6700 				 * fragment and free up the reassembly list.
6701 				 */
6702 				return (IP_REASS_FAILED);
6703 			}
6704 
6705 			/*
6706 			 * We shouldn't come to this code block again for this
6707 			 * particular fragment.
6708 			 */
6709 			pkt_boundary_checked = B_TRUE;
6710 		}
6711 
6712 		/* New stuff at or beyond tail? */
6713 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6714 		if (start >= offset) {
6715 			if (ipf->ipf_last_frag_seen) {
6716 				/* current fragment is beyond last fragment */
6717 				return (IP_REASS_FAILED);
6718 			}
6719 			/* Link it on end. */
6720 			ipf->ipf_tail_mp->b_cont = mp;
6721 			ipf->ipf_tail_mp = mp;
6722 			if (more) {
6723 				if (start != offset)
6724 					ipf->ipf_hole_cnt++;
6725 			} else if (start == offset && next_mp == NULL)
6726 					ipf->ipf_hole_cnt--;
6727 			continue;
6728 		}
6729 		mp1 = ipf->ipf_mp->b_cont;
6730 		offset = IP_REASS_START(mp1);
6731 		/* New stuff at the front? */
6732 		if (start < offset) {
6733 			if (start == 0) {
6734 				if (end >= offset) {
6735 					/* Nailed the hole at the begining. */
6736 					ipf->ipf_hole_cnt--;
6737 				}
6738 			} else if (end < offset) {
6739 				/*
6740 				 * A hole, stuff, and a hole where there used
6741 				 * to be just a hole.
6742 				 */
6743 				ipf->ipf_hole_cnt++;
6744 			}
6745 			mp->b_cont = mp1;
6746 			/* Check for overlap. */
6747 			while (end > offset) {
6748 				if (end < IP_REASS_END(mp1)) {
6749 					mp->b_wptr -= end - offset;
6750 					IP_REASS_SET_END(mp, offset);
6751 					BUMP_MIB(ill->ill_ip_mib,
6752 					    ipIfStatsReasmPartDups);
6753 					break;
6754 				}
6755 				/* Did we cover another hole? */
6756 				if ((mp1->b_cont &&
6757 				    IP_REASS_END(mp1) !=
6758 				    IP_REASS_START(mp1->b_cont) &&
6759 				    end >= IP_REASS_START(mp1->b_cont)) ||
6760 				    (!ipf->ipf_last_frag_seen && !more)) {
6761 					ipf->ipf_hole_cnt--;
6762 				}
6763 				/* Clip out mp1. */
6764 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6765 					/*
6766 					 * After clipping out mp1, this guy
6767 					 * is now hanging off the end.
6768 					 */
6769 					ipf->ipf_tail_mp = mp;
6770 				}
6771 				IP_REASS_SET_START(mp1, 0);
6772 				IP_REASS_SET_END(mp1, 0);
6773 				/* Subtract byte count */
6774 				ipf->ipf_count -= mp1->b_datap->db_lim -
6775 				    mp1->b_datap->db_base;
6776 				freeb(mp1);
6777 				BUMP_MIB(ill->ill_ip_mib,
6778 				    ipIfStatsReasmPartDups);
6779 				mp1 = mp->b_cont;
6780 				if (!mp1)
6781 					break;
6782 				offset = IP_REASS_START(mp1);
6783 			}
6784 			ipf->ipf_mp->b_cont = mp;
6785 			continue;
6786 		}
6787 		/*
6788 		 * The new piece starts somewhere between the start of the head
6789 		 * and before the end of the tail.
6790 		 */
6791 		for (; mp1; mp1 = mp1->b_cont) {
6792 			offset = IP_REASS_END(mp1);
6793 			if (start < offset) {
6794 				if (end <= offset) {
6795 					/* Nothing new. */
6796 					IP_REASS_SET_START(mp, 0);
6797 					IP_REASS_SET_END(mp, 0);
6798 					/* Subtract byte count */
6799 					ipf->ipf_count -= mp->b_datap->db_lim -
6800 					    mp->b_datap->db_base;
6801 					if (incr_dups) {
6802 						ipf->ipf_num_dups++;
6803 						incr_dups = B_FALSE;
6804 					}
6805 					freeb(mp);
6806 					BUMP_MIB(ill->ill_ip_mib,
6807 					    ipIfStatsReasmDuplicates);
6808 					break;
6809 				}
6810 				/*
6811 				 * Trim redundant stuff off beginning of new
6812 				 * piece.
6813 				 */
6814 				IP_REASS_SET_START(mp, offset);
6815 				mp->b_rptr += offset - start;
6816 				BUMP_MIB(ill->ill_ip_mib,
6817 				    ipIfStatsReasmPartDups);
6818 				start = offset;
6819 				if (!mp1->b_cont) {
6820 					/*
6821 					 * After trimming, this guy is now
6822 					 * hanging off the end.
6823 					 */
6824 					mp1->b_cont = mp;
6825 					ipf->ipf_tail_mp = mp;
6826 					if (!more) {
6827 						ipf->ipf_hole_cnt--;
6828 					}
6829 					break;
6830 				}
6831 			}
6832 			if (start >= IP_REASS_START(mp1->b_cont))
6833 				continue;
6834 			/* Fill a hole */
6835 			if (start > offset)
6836 				ipf->ipf_hole_cnt++;
6837 			mp->b_cont = mp1->b_cont;
6838 			mp1->b_cont = mp;
6839 			mp1 = mp->b_cont;
6840 			offset = IP_REASS_START(mp1);
6841 			if (end >= offset) {
6842 				ipf->ipf_hole_cnt--;
6843 				/* Check for overlap. */
6844 				while (end > offset) {
6845 					if (end < IP_REASS_END(mp1)) {
6846 						mp->b_wptr -= end - offset;
6847 						IP_REASS_SET_END(mp, offset);
6848 						/*
6849 						 * TODO we might bump
6850 						 * this up twice if there is
6851 						 * overlap at both ends.
6852 						 */
6853 						BUMP_MIB(ill->ill_ip_mib,
6854 						    ipIfStatsReasmPartDups);
6855 						break;
6856 					}
6857 					/* Did we cover another hole? */
6858 					if ((mp1->b_cont &&
6859 					    IP_REASS_END(mp1)
6860 					    != IP_REASS_START(mp1->b_cont) &&
6861 					    end >=
6862 					    IP_REASS_START(mp1->b_cont)) ||
6863 					    (!ipf->ipf_last_frag_seen &&
6864 					    !more)) {
6865 						ipf->ipf_hole_cnt--;
6866 					}
6867 					/* Clip out mp1. */
6868 					if ((mp->b_cont = mp1->b_cont) ==
6869 					    NULL) {
6870 						/*
6871 						 * After clipping out mp1,
6872 						 * this guy is now hanging
6873 						 * off the end.
6874 						 */
6875 						ipf->ipf_tail_mp = mp;
6876 					}
6877 					IP_REASS_SET_START(mp1, 0);
6878 					IP_REASS_SET_END(mp1, 0);
6879 					/* Subtract byte count */
6880 					ipf->ipf_count -=
6881 					    mp1->b_datap->db_lim -
6882 					    mp1->b_datap->db_base;
6883 					freeb(mp1);
6884 					BUMP_MIB(ill->ill_ip_mib,
6885 					    ipIfStatsReasmPartDups);
6886 					mp1 = mp->b_cont;
6887 					if (!mp1)
6888 						break;
6889 					offset = IP_REASS_START(mp1);
6890 				}
6891 			}
6892 			break;
6893 		}
6894 	} while (start = end, mp = next_mp);
6895 
6896 	/* Fragment just processed could be the last one. Remember this fact */
6897 	if (!more)
6898 		ipf->ipf_last_frag_seen = B_TRUE;
6899 
6900 	/* Still got holes? */
6901 	if (ipf->ipf_hole_cnt)
6902 		return (IP_REASS_PARTIAL);
6903 	/* Clean up overloaded fields to avoid upstream disasters. */
6904 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6905 		IP_REASS_SET_START(mp1, 0);
6906 		IP_REASS_SET_END(mp1, 0);
6907 	}
6908 	return (IP_REASS_COMPLETE);
6909 }
6910 
6911 /*
6912  * Fragmentation reassembly.  Each ILL has a hash table for
6913  * queuing packets undergoing reassembly for all IPIFs
6914  * associated with the ILL.  The hash is based on the packet
6915  * IP ident field.  The ILL frag hash table was allocated
6916  * as a timer block at the time the ILL was created.  Whenever
6917  * there is anything on the reassembly queue, the timer will
6918  * be running.  Returns the reassembled packet if reassembly completes.
6919  */
6920 mblk_t *
6921 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
6922 {
6923 	uint32_t	frag_offset_flags;
6924 	mblk_t		*t_mp;
6925 	ipaddr_t	dst;
6926 	uint8_t		proto = ipha->ipha_protocol;
6927 	uint32_t	sum_val;
6928 	uint16_t	sum_flags;
6929 	ipf_t		*ipf;
6930 	ipf_t		**ipfp;
6931 	ipfb_t		*ipfb;
6932 	uint16_t	ident;
6933 	uint32_t	offset;
6934 	ipaddr_t	src;
6935 	uint_t		hdr_length;
6936 	uint32_t	end;
6937 	mblk_t		*mp1;
6938 	mblk_t		*tail_mp;
6939 	size_t		count;
6940 	size_t		msg_len;
6941 	uint8_t		ecn_info = 0;
6942 	uint32_t	packet_size;
6943 	boolean_t	pruned = B_FALSE;
6944 	ill_t		*ill = ira->ira_ill;
6945 	ip_stack_t	*ipst = ill->ill_ipst;
6946 
6947 	/*
6948 	 * Drop the fragmented as early as possible, if
6949 	 * we don't have resource(s) to re-assemble.
6950 	 */
6951 	if (ipst->ips_ip_reass_queue_bytes == 0) {
6952 		freemsg(mp);
6953 		return (NULL);
6954 	}
6955 
6956 	/* Check for fragmentation offset; return if there's none */
6957 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
6958 	    (IPH_MF | IPH_OFFSET)) == 0)
6959 		return (mp);
6960 
6961 	/*
6962 	 * We utilize hardware computed checksum info only for UDP since
6963 	 * IP fragmentation is a normal occurrence for the protocol.  In
6964 	 * addition, checksum offload support for IP fragments carrying
6965 	 * UDP payload is commonly implemented across network adapters.
6966 	 */
6967 	ASSERT(ira->ira_rill != NULL);
6968 	if (proto == IPPROTO_UDP && dohwcksum &&
6969 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
6970 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
6971 		mblk_t *mp1 = mp->b_cont;
6972 		int32_t len;
6973 
6974 		/* Record checksum information from the packet */
6975 		sum_val = (uint32_t)DB_CKSUM16(mp);
6976 		sum_flags = DB_CKSUMFLAGS(mp);
6977 
6978 		/* IP payload offset from beginning of mblk */
6979 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
6980 
6981 		if ((sum_flags & HCK_PARTIALCKSUM) &&
6982 		    (mp1 == NULL || mp1->b_cont == NULL) &&
6983 		    offset >= DB_CKSUMSTART(mp) &&
6984 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
6985 			uint32_t adj;
6986 			/*
6987 			 * Partial checksum has been calculated by hardware
6988 			 * and attached to the packet; in addition, any
6989 			 * prepended extraneous data is even byte aligned.
6990 			 * If any such data exists, we adjust the checksum;
6991 			 * this would also handle any postpended data.
6992 			 */
6993 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
6994 			    mp, mp1, len, adj);
6995 
6996 			/* One's complement subtract extraneous checksum */
6997 			if (adj >= sum_val)
6998 				sum_val = ~(adj - sum_val) & 0xFFFF;
6999 			else
7000 				sum_val -= adj;
7001 		}
7002 	} else {
7003 		sum_val = 0;
7004 		sum_flags = 0;
7005 	}
7006 
7007 	/* Clear hardware checksumming flag */
7008 	DB_CKSUMFLAGS(mp) = 0;
7009 
7010 	ident = ipha->ipha_ident;
7011 	offset = (frag_offset_flags << 3) & 0xFFFF;
7012 	src = ipha->ipha_src;
7013 	dst = ipha->ipha_dst;
7014 	hdr_length = IPH_HDR_LENGTH(ipha);
7015 	end = ntohs(ipha->ipha_length) - hdr_length;
7016 
7017 	/* If end == 0 then we have a packet with no data, so just free it */
7018 	if (end == 0) {
7019 		freemsg(mp);
7020 		return (NULL);
7021 	}
7022 
7023 	/* Record the ECN field info. */
7024 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7025 	if (offset != 0) {
7026 		/*
7027 		 * If this isn't the first piece, strip the header, and
7028 		 * add the offset to the end value.
7029 		 */
7030 		mp->b_rptr += hdr_length;
7031 		end += offset;
7032 	}
7033 
7034 	/* Handle vnic loopback of fragments */
7035 	if (mp->b_datap->db_ref > 2)
7036 		msg_len = 0;
7037 	else
7038 		msg_len = MBLKSIZE(mp);
7039 
7040 	tail_mp = mp;
7041 	while (tail_mp->b_cont != NULL) {
7042 		tail_mp = tail_mp->b_cont;
7043 		if (tail_mp->b_datap->db_ref <= 2)
7044 			msg_len += MBLKSIZE(tail_mp);
7045 	}
7046 
7047 	/* If the reassembly list for this ILL will get too big, prune it */
7048 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7049 	    ipst->ips_ip_reass_queue_bytes) {
7050 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7051 		    uint_t, ill->ill_frag_count,
7052 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7053 		ill_frag_prune(ill,
7054 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7055 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7056 		pruned = B_TRUE;
7057 	}
7058 
7059 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7060 	mutex_enter(&ipfb->ipfb_lock);
7061 
7062 	ipfp = &ipfb->ipfb_ipf;
7063 	/* Try to find an existing fragment queue for this packet. */
7064 	for (;;) {
7065 		ipf = ipfp[0];
7066 		if (ipf != NULL) {
7067 			/*
7068 			 * It has to match on ident and src/dst address.
7069 			 */
7070 			if (ipf->ipf_ident == ident &&
7071 			    ipf->ipf_src == src &&
7072 			    ipf->ipf_dst == dst &&
7073 			    ipf->ipf_protocol == proto) {
7074 				/*
7075 				 * If we have received too many
7076 				 * duplicate fragments for this packet
7077 				 * free it.
7078 				 */
7079 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7080 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7081 					freemsg(mp);
7082 					mutex_exit(&ipfb->ipfb_lock);
7083 					return (NULL);
7084 				}
7085 				/* Found it. */
7086 				break;
7087 			}
7088 			ipfp = &ipf->ipf_hash_next;
7089 			continue;
7090 		}
7091 
7092 		/*
7093 		 * If we pruned the list, do we want to store this new
7094 		 * fragment?. We apply an optimization here based on the
7095 		 * fact that most fragments will be received in order.
7096 		 * So if the offset of this incoming fragment is zero,
7097 		 * it is the first fragment of a new packet. We will
7098 		 * keep it.  Otherwise drop the fragment, as we have
7099 		 * probably pruned the packet already (since the
7100 		 * packet cannot be found).
7101 		 */
7102 		if (pruned && offset != 0) {
7103 			mutex_exit(&ipfb->ipfb_lock);
7104 			freemsg(mp);
7105 			return (NULL);
7106 		}
7107 
7108 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7109 			/*
7110 			 * Too many fragmented packets in this hash
7111 			 * bucket. Free the oldest.
7112 			 */
7113 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7114 		}
7115 
7116 		/* New guy.  Allocate a frag message. */
7117 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7118 		if (mp1 == NULL) {
7119 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7120 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7121 			freemsg(mp);
7122 reass_done:
7123 			mutex_exit(&ipfb->ipfb_lock);
7124 			return (NULL);
7125 		}
7126 
7127 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7128 		mp1->b_cont = mp;
7129 
7130 		/* Initialize the fragment header. */
7131 		ipf = (ipf_t *)mp1->b_rptr;
7132 		ipf->ipf_mp = mp1;
7133 		ipf->ipf_ptphn = ipfp;
7134 		ipfp[0] = ipf;
7135 		ipf->ipf_hash_next = NULL;
7136 		ipf->ipf_ident = ident;
7137 		ipf->ipf_protocol = proto;
7138 		ipf->ipf_src = src;
7139 		ipf->ipf_dst = dst;
7140 		ipf->ipf_nf_hdr_len = 0;
7141 		/* Record reassembly start time. */
7142 		ipf->ipf_timestamp = gethrestime_sec();
7143 		/* Record ipf generation and account for frag header */
7144 		ipf->ipf_gen = ill->ill_ipf_gen++;
7145 		ipf->ipf_count = MBLKSIZE(mp1);
7146 		ipf->ipf_last_frag_seen = B_FALSE;
7147 		ipf->ipf_ecn = ecn_info;
7148 		ipf->ipf_num_dups = 0;
7149 		ipfb->ipfb_frag_pkts++;
7150 		ipf->ipf_checksum = 0;
7151 		ipf->ipf_checksum_flags = 0;
7152 
7153 		/* Store checksum value in fragment header */
7154 		if (sum_flags != 0) {
7155 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7156 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7157 			ipf->ipf_checksum = sum_val;
7158 			ipf->ipf_checksum_flags = sum_flags;
7159 		}
7160 
7161 		/*
7162 		 * We handle reassembly two ways.  In the easy case,
7163 		 * where all the fragments show up in order, we do
7164 		 * minimal bookkeeping, and just clip new pieces on
7165 		 * the end.  If we ever see a hole, then we go off
7166 		 * to ip_reassemble which has to mark the pieces and
7167 		 * keep track of the number of holes, etc.  Obviously,
7168 		 * the point of having both mechanisms is so we can
7169 		 * handle the easy case as efficiently as possible.
7170 		 */
7171 		if (offset == 0) {
7172 			/* Easy case, in-order reassembly so far. */
7173 			ipf->ipf_count += msg_len;
7174 			ipf->ipf_tail_mp = tail_mp;
7175 			/*
7176 			 * Keep track of next expected offset in
7177 			 * ipf_end.
7178 			 */
7179 			ipf->ipf_end = end;
7180 			ipf->ipf_nf_hdr_len = hdr_length;
7181 		} else {
7182 			/* Hard case, hole at the beginning. */
7183 			ipf->ipf_tail_mp = NULL;
7184 			/*
7185 			 * ipf_end == 0 means that we have given up
7186 			 * on easy reassembly.
7187 			 */
7188 			ipf->ipf_end = 0;
7189 
7190 			/* Forget checksum offload from now on */
7191 			ipf->ipf_checksum_flags = 0;
7192 
7193 			/*
7194 			 * ipf_hole_cnt is set by ip_reassemble.
7195 			 * ipf_count is updated by ip_reassemble.
7196 			 * No need to check for return value here
7197 			 * as we don't expect reassembly to complete
7198 			 * or fail for the first fragment itself.
7199 			 */
7200 			(void) ip_reassemble(mp, ipf,
7201 			    (frag_offset_flags & IPH_OFFSET) << 3,
7202 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7203 		}
7204 		/* Update per ipfb and ill byte counts */
7205 		ipfb->ipfb_count += ipf->ipf_count;
7206 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7207 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7208 		/* If the frag timer wasn't already going, start it. */
7209 		mutex_enter(&ill->ill_lock);
7210 		ill_frag_timer_start(ill);
7211 		mutex_exit(&ill->ill_lock);
7212 		goto reass_done;
7213 	}
7214 
7215 	/*
7216 	 * If the packet's flag has changed (it could be coming up
7217 	 * from an interface different than the previous, therefore
7218 	 * possibly different checksum capability), then forget about
7219 	 * any stored checksum states.  Otherwise add the value to
7220 	 * the existing one stored in the fragment header.
7221 	 */
7222 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7223 		sum_val += ipf->ipf_checksum;
7224 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7225 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7226 		ipf->ipf_checksum = sum_val;
7227 	} else if (ipf->ipf_checksum_flags != 0) {
7228 		/* Forget checksum offload from now on */
7229 		ipf->ipf_checksum_flags = 0;
7230 	}
7231 
7232 	/*
7233 	 * We have a new piece of a datagram which is already being
7234 	 * reassembled.  Update the ECN info if all IP fragments
7235 	 * are ECN capable.  If there is one which is not, clear
7236 	 * all the info.  If there is at least one which has CE
7237 	 * code point, IP needs to report that up to transport.
7238 	 */
7239 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7240 		if (ecn_info == IPH_ECN_CE)
7241 			ipf->ipf_ecn = IPH_ECN_CE;
7242 	} else {
7243 		ipf->ipf_ecn = IPH_ECN_NECT;
7244 	}
7245 	if (offset && ipf->ipf_end == offset) {
7246 		/* The new fragment fits at the end */
7247 		ipf->ipf_tail_mp->b_cont = mp;
7248 		/* Update the byte count */
7249 		ipf->ipf_count += msg_len;
7250 		/* Update per ipfb and ill byte counts */
7251 		ipfb->ipfb_count += msg_len;
7252 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7253 		atomic_add_32(&ill->ill_frag_count, msg_len);
7254 		if (frag_offset_flags & IPH_MF) {
7255 			/* More to come. */
7256 			ipf->ipf_end = end;
7257 			ipf->ipf_tail_mp = tail_mp;
7258 			goto reass_done;
7259 		}
7260 	} else {
7261 		/* Go do the hard cases. */
7262 		int ret;
7263 
7264 		if (offset == 0)
7265 			ipf->ipf_nf_hdr_len = hdr_length;
7266 
7267 		/* Save current byte count */
7268 		count = ipf->ipf_count;
7269 		ret = ip_reassemble(mp, ipf,
7270 		    (frag_offset_flags & IPH_OFFSET) << 3,
7271 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7272 		/* Count of bytes added and subtracted (freeb()ed) */
7273 		count = ipf->ipf_count - count;
7274 		if (count) {
7275 			/* Update per ipfb and ill byte counts */
7276 			ipfb->ipfb_count += count;
7277 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7278 			atomic_add_32(&ill->ill_frag_count, count);
7279 		}
7280 		if (ret == IP_REASS_PARTIAL) {
7281 			goto reass_done;
7282 		} else if (ret == IP_REASS_FAILED) {
7283 			/* Reassembly failed. Free up all resources */
7284 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7285 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7286 				IP_REASS_SET_START(t_mp, 0);
7287 				IP_REASS_SET_END(t_mp, 0);
7288 			}
7289 			freemsg(mp);
7290 			goto reass_done;
7291 		}
7292 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7293 	}
7294 	/*
7295 	 * We have completed reassembly.  Unhook the frag header from
7296 	 * the reassembly list.
7297 	 *
7298 	 * Before we free the frag header, record the ECN info
7299 	 * to report back to the transport.
7300 	 */
7301 	ecn_info = ipf->ipf_ecn;
7302 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7303 	ipfp = ipf->ipf_ptphn;
7304 
7305 	/* We need to supply these to caller */
7306 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7307 		sum_val = ipf->ipf_checksum;
7308 	else
7309 		sum_val = 0;
7310 
7311 	mp1 = ipf->ipf_mp;
7312 	count = ipf->ipf_count;
7313 	ipf = ipf->ipf_hash_next;
7314 	if (ipf != NULL)
7315 		ipf->ipf_ptphn = ipfp;
7316 	ipfp[0] = ipf;
7317 	atomic_add_32(&ill->ill_frag_count, -count);
7318 	ASSERT(ipfb->ipfb_count >= count);
7319 	ipfb->ipfb_count -= count;
7320 	ipfb->ipfb_frag_pkts--;
7321 	mutex_exit(&ipfb->ipfb_lock);
7322 	/* Ditch the frag header. */
7323 	mp = mp1->b_cont;
7324 
7325 	freeb(mp1);
7326 
7327 	/* Restore original IP length in header. */
7328 	packet_size = (uint32_t)msgdsize(mp);
7329 	if (packet_size > IP_MAXPACKET) {
7330 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7331 		ip_drop_input("Reassembled packet too large", mp, ill);
7332 		freemsg(mp);
7333 		return (NULL);
7334 	}
7335 
7336 	if (DB_REF(mp) > 1) {
7337 		mblk_t *mp2 = copymsg(mp);
7338 
7339 		if (mp2 == NULL) {
7340 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7341 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7342 			freemsg(mp);
7343 			return (NULL);
7344 		}
7345 		freemsg(mp);
7346 		mp = mp2;
7347 	}
7348 	ipha = (ipha_t *)mp->b_rptr;
7349 
7350 	ipha->ipha_length = htons((uint16_t)packet_size);
7351 	/* We're now complete, zip the frag state */
7352 	ipha->ipha_fragment_offset_and_flags = 0;
7353 	/* Record the ECN info. */
7354 	ipha->ipha_type_of_service &= 0xFC;
7355 	ipha->ipha_type_of_service |= ecn_info;
7356 
7357 	/* Update the receive attributes */
7358 	ira->ira_pktlen = packet_size;
7359 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7360 
7361 	/* Reassembly is successful; set checksum information in packet */
7362 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7363 	DB_CKSUMFLAGS(mp) = sum_flags;
7364 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7365 
7366 	return (mp);
7367 }
7368 
7369 /*
7370  * Pullup function that should be used for IP input in order to
7371  * ensure we do not loose the L2 source address; we need the l2 source
7372  * address for IP_RECVSLLA and for ndp_input.
7373  *
7374  * We return either NULL or b_rptr.
7375  */
7376 void *
7377 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7378 {
7379 	ill_t		*ill = ira->ira_ill;
7380 
7381 	if (ip_rput_pullups++ == 0) {
7382 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7383 		    "ip_pullup: %s forced us to "
7384 		    " pullup pkt, hdr len %ld, hdr addr %p",
7385 		    ill->ill_name, len, (void *)mp->b_rptr);
7386 	}
7387 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7388 		ip_setl2src(mp, ira, ira->ira_rill);
7389 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7390 	if (!pullupmsg(mp, len))
7391 		return (NULL);
7392 	else
7393 		return (mp->b_rptr);
7394 }
7395 
7396 /*
7397  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7398  * When called from the ULP ira_rill will be NULL hence the caller has to
7399  * pass in the ill.
7400  */
7401 /* ARGSUSED */
7402 void
7403 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7404 {
7405 	const uchar_t *addr;
7406 	int alen;
7407 
7408 	if (ira->ira_flags & IRAF_L2SRC_SET)
7409 		return;
7410 
7411 	ASSERT(ill != NULL);
7412 	alen = ill->ill_phys_addr_length;
7413 	ASSERT(alen <= sizeof (ira->ira_l2src));
7414 	if (ira->ira_mhip != NULL &&
7415 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7416 		bcopy(addr, ira->ira_l2src, alen);
7417 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7418 	    (addr = ill->ill_phys_addr) != NULL) {
7419 		bcopy(addr, ira->ira_l2src, alen);
7420 	} else {
7421 		bzero(ira->ira_l2src, alen);
7422 	}
7423 	ira->ira_flags |= IRAF_L2SRC_SET;
7424 }
7425 
7426 /*
7427  * check ip header length and align it.
7428  */
7429 mblk_t *
7430 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7431 {
7432 	ill_t	*ill = ira->ira_ill;
7433 	ssize_t len;
7434 
7435 	len = MBLKL(mp);
7436 
7437 	if (!OK_32PTR(mp->b_rptr))
7438 		IP_STAT(ill->ill_ipst, ip_notaligned);
7439 	else
7440 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7441 
7442 	/* Guard against bogus device drivers */
7443 	if (len < 0) {
7444 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7445 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7446 		freemsg(mp);
7447 		return (NULL);
7448 	}
7449 
7450 	if (len == 0) {
7451 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7452 		mblk_t *mp1 = mp->b_cont;
7453 
7454 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7455 			ip_setl2src(mp, ira, ira->ira_rill);
7456 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7457 
7458 		freeb(mp);
7459 		mp = mp1;
7460 		if (mp == NULL)
7461 			return (NULL);
7462 
7463 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7464 			return (mp);
7465 	}
7466 	if (ip_pullup(mp, min_size, ira) == NULL) {
7467 		if (msgdsize(mp) < min_size) {
7468 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7469 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7470 		} else {
7471 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7472 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7473 		}
7474 		freemsg(mp);
7475 		return (NULL);
7476 	}
7477 	return (mp);
7478 }
7479 
7480 /*
7481  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7482  */
7483 mblk_t *
7484 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7485     uint_t min_size, ip_recv_attr_t *ira)
7486 {
7487 	ill_t	*ill = ira->ira_ill;
7488 
7489 	/*
7490 	 * Make sure we have data length consistent
7491 	 * with the IP header.
7492 	 */
7493 	if (mp->b_cont == NULL) {
7494 		/* pkt_len is based on ipha_len, not the mblk length */
7495 		if (pkt_len < min_size) {
7496 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7497 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7498 			freemsg(mp);
7499 			return (NULL);
7500 		}
7501 		if (len < 0) {
7502 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7503 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7504 			freemsg(mp);
7505 			return (NULL);
7506 		}
7507 		/* Drop any pad */
7508 		mp->b_wptr = rptr + pkt_len;
7509 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7510 		ASSERT(pkt_len >= min_size);
7511 		if (pkt_len < min_size) {
7512 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7513 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7514 			freemsg(mp);
7515 			return (NULL);
7516 		}
7517 		if (len < 0) {
7518 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7519 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7520 			freemsg(mp);
7521 			return (NULL);
7522 		}
7523 		/* Drop any pad */
7524 		(void) adjmsg(mp, -len);
7525 		/*
7526 		 * adjmsg may have freed an mblk from the chain, hence
7527 		 * invalidate any hw checksum here. This will force IP to
7528 		 * calculate the checksum in sw, but only for this packet.
7529 		 */
7530 		DB_CKSUMFLAGS(mp) = 0;
7531 		IP_STAT(ill->ill_ipst, ip_multimblk);
7532 	}
7533 	return (mp);
7534 }
7535 
7536 /*
7537  * Check that the IPv4 opt_len is consistent with the packet and pullup
7538  * the options.
7539  */
7540 mblk_t *
7541 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7542     ip_recv_attr_t *ira)
7543 {
7544 	ill_t	*ill = ira->ira_ill;
7545 	ssize_t len;
7546 
7547 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7548 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7549 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7550 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7551 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7552 		freemsg(mp);
7553 		return (NULL);
7554 	}
7555 
7556 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7557 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7558 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7559 		freemsg(mp);
7560 		return (NULL);
7561 	}
7562 	/*
7563 	 * Recompute complete header length and make sure we
7564 	 * have access to all of it.
7565 	 */
7566 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7567 	if (len > (mp->b_wptr - mp->b_rptr)) {
7568 		if (len > pkt_len) {
7569 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7570 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7571 			freemsg(mp);
7572 			return (NULL);
7573 		}
7574 		if (ip_pullup(mp, len, ira) == NULL) {
7575 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7576 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7577 			freemsg(mp);
7578 			return (NULL);
7579 		}
7580 	}
7581 	return (mp);
7582 }
7583 
7584 /*
7585  * Returns a new ire, or the same ire, or NULL.
7586  * If a different IRE is returned, then it is held; the caller
7587  * needs to release it.
7588  * In no case is there any hold/release on the ire argument.
7589  */
7590 ire_t *
7591 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7592 {
7593 	ire_t		*new_ire;
7594 	ill_t		*ire_ill;
7595 	uint_t		ifindex;
7596 	ip_stack_t	*ipst = ill->ill_ipst;
7597 	boolean_t	strict_check = B_FALSE;
7598 
7599 	/*
7600 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7601 	 * issue (e.g. packet received on an underlying interface matched an
7602 	 * IRE_LOCAL on its associated group interface).
7603 	 */
7604 	ASSERT(ire->ire_ill != NULL);
7605 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7606 		return (ire);
7607 
7608 	/*
7609 	 * Do another ire lookup here, using the ingress ill, to see if the
7610 	 * interface is in a usesrc group.
7611 	 * As long as the ills belong to the same group, we don't consider
7612 	 * them to be arriving on the wrong interface. Thus, if the switch
7613 	 * is doing inbound load spreading, we won't drop packets when the
7614 	 * ip*_strict_dst_multihoming switch is on.
7615 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7616 	 * where the local address may not be unique. In this case we were
7617 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7618 	 * actually returned. The new lookup, which is more specific, should
7619 	 * only find the IRE_LOCAL associated with the ingress ill if one
7620 	 * exists.
7621 	 */
7622 	if (ire->ire_ipversion == IPV4_VERSION) {
7623 		if (ipst->ips_ip_strict_dst_multihoming)
7624 			strict_check = B_TRUE;
7625 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7626 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7627 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7628 	} else {
7629 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7630 		if (ipst->ips_ipv6_strict_dst_multihoming)
7631 			strict_check = B_TRUE;
7632 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7633 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7634 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7635 	}
7636 	/*
7637 	 * If the same ire that was returned in ip_input() is found then this
7638 	 * is an indication that usesrc groups are in use. The packet
7639 	 * arrived on a different ill in the group than the one associated with
7640 	 * the destination address.  If a different ire was found then the same
7641 	 * IP address must be hosted on multiple ills. This is possible with
7642 	 * unnumbered point2point interfaces. We switch to use this new ire in
7643 	 * order to have accurate interface statistics.
7644 	 */
7645 	if (new_ire != NULL) {
7646 		/* Note: held in one case but not the other? Caller handles */
7647 		if (new_ire != ire)
7648 			return (new_ire);
7649 		/* Unchanged */
7650 		ire_refrele(new_ire);
7651 		return (ire);
7652 	}
7653 
7654 	/*
7655 	 * Chase pointers once and store locally.
7656 	 */
7657 	ASSERT(ire->ire_ill != NULL);
7658 	ire_ill = ire->ire_ill;
7659 	ifindex = ill->ill_usesrc_ifindex;
7660 
7661 	/*
7662 	 * Check if it's a legal address on the 'usesrc' interface.
7663 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7664 	 * can just check phyint_ifindex.
7665 	 */
7666 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7667 		return (ire);
7668 	}
7669 
7670 	/*
7671 	 * If the ip*_strict_dst_multihoming switch is on then we can
7672 	 * only accept this packet if the interface is marked as routing.
7673 	 */
7674 	if (!(strict_check))
7675 		return (ire);
7676 
7677 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7678 		return (ire);
7679 	}
7680 	return (NULL);
7681 }
7682 
7683 /*
7684  * This function is used to construct a mac_header_info_s from a
7685  * DL_UNITDATA_IND message.
7686  * The address fields in the mhi structure points into the message,
7687  * thus the caller can't use those fields after freeing the message.
7688  *
7689  * We determine whether the packet received is a non-unicast packet
7690  * and in doing so, determine whether or not it is broadcast vs multicast.
7691  * For it to be a broadcast packet, we must have the appropriate mblk_t
7692  * hanging off the ill_t.  If this is either not present or doesn't match
7693  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7694  * to be multicast.  Thus NICs that have no broadcast address (or no
7695  * capability for one, such as point to point links) cannot return as
7696  * the packet being broadcast.
7697  */
7698 void
7699 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7700 {
7701 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7702 	mblk_t *bmp;
7703 	uint_t extra_offset;
7704 
7705 	bzero(mhip, sizeof (struct mac_header_info_s));
7706 
7707 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7708 
7709 	if (ill->ill_sap_length < 0)
7710 		extra_offset = 0;
7711 	else
7712 		extra_offset = ill->ill_sap_length;
7713 
7714 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7715 	    extra_offset;
7716 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7717 	    extra_offset;
7718 
7719 	if (!ind->dl_group_address)
7720 		return;
7721 
7722 	/* Multicast or broadcast */
7723 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7724 
7725 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7726 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7727 	    (bmp = ill->ill_bcast_mp) != NULL) {
7728 		dl_unitdata_req_t *dlur;
7729 		uint8_t *bphys_addr;
7730 
7731 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7732 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7733 		    extra_offset;
7734 
7735 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7736 		    ind->dl_dest_addr_length) == 0)
7737 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7738 	}
7739 }
7740 
7741 /*
7742  * This function is used to construct a mac_header_info_s from a
7743  * M_DATA fastpath message from a DLPI driver.
7744  * The address fields in the mhi structure points into the message,
7745  * thus the caller can't use those fields after freeing the message.
7746  *
7747  * We determine whether the packet received is a non-unicast packet
7748  * and in doing so, determine whether or not it is broadcast vs multicast.
7749  * For it to be a broadcast packet, we must have the appropriate mblk_t
7750  * hanging off the ill_t.  If this is either not present or doesn't match
7751  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7752  * to be multicast.  Thus NICs that have no broadcast address (or no
7753  * capability for one, such as point to point links) cannot return as
7754  * the packet being broadcast.
7755  */
7756 void
7757 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7758 {
7759 	mblk_t *bmp;
7760 	struct ether_header *pether;
7761 
7762 	bzero(mhip, sizeof (struct mac_header_info_s));
7763 
7764 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7765 
7766 	pether = (struct ether_header *)((char *)mp->b_rptr
7767 	    - sizeof (struct ether_header));
7768 
7769 	/*
7770 	 * Make sure the interface is an ethernet type, since we don't
7771 	 * know the header format for anything but Ethernet. Also make
7772 	 * sure we are pointing correctly above db_base.
7773 	 */
7774 	if (ill->ill_type != IFT_ETHER)
7775 		return;
7776 
7777 retry:
7778 	if ((uchar_t *)pether < mp->b_datap->db_base)
7779 		return;
7780 
7781 	/* Is there a VLAN tag? */
7782 	if (ill->ill_isv6) {
7783 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7784 			pether = (struct ether_header *)((char *)pether - 4);
7785 			goto retry;
7786 		}
7787 	} else {
7788 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7789 			pether = (struct ether_header *)((char *)pether - 4);
7790 			goto retry;
7791 		}
7792 	}
7793 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7794 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7795 
7796 	if (!(mhip->mhi_daddr[0] & 0x01))
7797 		return;
7798 
7799 	/* Multicast or broadcast */
7800 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7801 
7802 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7803 		dl_unitdata_req_t *dlur;
7804 		uint8_t *bphys_addr;
7805 		uint_t	addrlen;
7806 
7807 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7808 		addrlen = dlur->dl_dest_addr_length;
7809 		if (ill->ill_sap_length < 0) {
7810 			bphys_addr = (uchar_t *)dlur +
7811 			    dlur->dl_dest_addr_offset;
7812 			addrlen += ill->ill_sap_length;
7813 		} else {
7814 			bphys_addr = (uchar_t *)dlur +
7815 			    dlur->dl_dest_addr_offset +
7816 			    ill->ill_sap_length;
7817 			addrlen -= ill->ill_sap_length;
7818 		}
7819 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7820 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7821 	}
7822 }
7823 
7824 /*
7825  * Handle anything but M_DATA messages
7826  * We see the DL_UNITDATA_IND which are part
7827  * of the data path, and also the other messages from the driver.
7828  */
7829 void
7830 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7831 {
7832 	mblk_t		*first_mp;
7833 	struct iocblk   *iocp;
7834 	struct mac_header_info_s mhi;
7835 
7836 	switch (DB_TYPE(mp)) {
7837 	case M_PROTO:
7838 	case M_PCPROTO: {
7839 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7840 		    DL_UNITDATA_IND) {
7841 			/* Go handle anything other than data elsewhere. */
7842 			ip_rput_dlpi(ill, mp);
7843 			return;
7844 		}
7845 
7846 		first_mp = mp;
7847 		mp = first_mp->b_cont;
7848 		first_mp->b_cont = NULL;
7849 
7850 		if (mp == NULL) {
7851 			freeb(first_mp);
7852 			return;
7853 		}
7854 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7855 		if (ill->ill_isv6)
7856 			ip_input_v6(ill, NULL, mp, &mhi);
7857 		else
7858 			ip_input(ill, NULL, mp, &mhi);
7859 
7860 		/* Ditch the DLPI header. */
7861 		freeb(first_mp);
7862 		return;
7863 	}
7864 	case M_IOCACK:
7865 		iocp = (struct iocblk *)mp->b_rptr;
7866 		switch (iocp->ioc_cmd) {
7867 		case DL_IOC_HDR_INFO:
7868 			ill_fastpath_ack(ill, mp);
7869 			return;
7870 		default:
7871 			putnext(ill->ill_rq, mp);
7872 			return;
7873 		}
7874 		/* FALLTHRU */
7875 	case M_ERROR:
7876 	case M_HANGUP:
7877 		mutex_enter(&ill->ill_lock);
7878 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7879 			mutex_exit(&ill->ill_lock);
7880 			freemsg(mp);
7881 			return;
7882 		}
7883 		ill_refhold_locked(ill);
7884 		mutex_exit(&ill->ill_lock);
7885 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7886 		    B_FALSE);
7887 		return;
7888 	case M_CTL:
7889 		putnext(ill->ill_rq, mp);
7890 		return;
7891 	case M_IOCNAK:
7892 		ip1dbg(("got iocnak "));
7893 		iocp = (struct iocblk *)mp->b_rptr;
7894 		switch (iocp->ioc_cmd) {
7895 		case DL_IOC_HDR_INFO:
7896 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7897 			return;
7898 		default:
7899 			break;
7900 		}
7901 		/* FALLTHRU */
7902 	default:
7903 		putnext(ill->ill_rq, mp);
7904 		return;
7905 	}
7906 }
7907 
7908 /* Read side put procedure.  Packets coming from the wire arrive here. */
7909 void
7910 ip_rput(queue_t *q, mblk_t *mp)
7911 {
7912 	ill_t	*ill;
7913 	union DL_primitives *dl;
7914 
7915 	ill = (ill_t *)q->q_ptr;
7916 
7917 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
7918 		/*
7919 		 * If things are opening or closing, only accept high-priority
7920 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
7921 		 * created; on close, things hanging off the ill may have been
7922 		 * freed already.)
7923 		 */
7924 		dl = (union DL_primitives *)mp->b_rptr;
7925 		if (DB_TYPE(mp) != M_PCPROTO ||
7926 		    dl->dl_primitive == DL_UNITDATA_IND) {
7927 			inet_freemsg(mp);
7928 			return;
7929 		}
7930 	}
7931 	if (DB_TYPE(mp) == M_DATA) {
7932 		struct mac_header_info_s mhi;
7933 
7934 		ip_mdata_to_mhi(ill, mp, &mhi);
7935 		ip_input(ill, NULL, mp, &mhi);
7936 	} else {
7937 		ip_rput_notdata(ill, mp);
7938 	}
7939 }
7940 
7941 /*
7942  * Move the information to a copy.
7943  */
7944 mblk_t *
7945 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
7946 {
7947 	mblk_t		*mp1;
7948 	ill_t		*ill = ira->ira_ill;
7949 	ip_stack_t	*ipst = ill->ill_ipst;
7950 
7951 	IP_STAT(ipst, ip_db_ref);
7952 
7953 	/* Make sure we have ira_l2src before we loose the original mblk */
7954 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7955 		ip_setl2src(mp, ira, ira->ira_rill);
7956 
7957 	mp1 = copymsg(mp);
7958 	if (mp1 == NULL) {
7959 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7960 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
7961 		freemsg(mp);
7962 		return (NULL);
7963 	}
7964 	/* preserve the hardware checksum flags and data, if present */
7965 	if (DB_CKSUMFLAGS(mp) != 0) {
7966 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
7967 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
7968 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
7969 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
7970 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
7971 	}
7972 	freemsg(mp);
7973 	return (mp1);
7974 }
7975 
7976 static void
7977 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
7978     t_uscalar_t err)
7979 {
7980 	if (dl_err == DL_SYSERR) {
7981 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
7982 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
7983 		    ill->ill_name, dl_primstr(prim), err);
7984 		return;
7985 	}
7986 
7987 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
7988 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
7989 	    dl_errstr(dl_err));
7990 }
7991 
7992 /*
7993  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
7994  * than DL_UNITDATA_IND messages. If we need to process this message
7995  * exclusively, we call qwriter_ip, in which case we also need to call
7996  * ill_refhold before that, since qwriter_ip does an ill_refrele.
7997  */
7998 void
7999 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8000 {
8001 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8002 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8003 	queue_t		*q = ill->ill_rq;
8004 	t_uscalar_t	prim = dloa->dl_primitive;
8005 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8006 
8007 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8008 	    char *, dl_primstr(prim), ill_t *, ill);
8009 	ip1dbg(("ip_rput_dlpi"));
8010 
8011 	/*
8012 	 * If we received an ACK but didn't send a request for it, then it
8013 	 * can't be part of any pending operation; discard up-front.
8014 	 */
8015 	switch (prim) {
8016 	case DL_ERROR_ACK:
8017 		reqprim = dlea->dl_error_primitive;
8018 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8019 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8020 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8021 		    dlea->dl_unix_errno));
8022 		break;
8023 	case DL_OK_ACK:
8024 		reqprim = dloa->dl_correct_primitive;
8025 		break;
8026 	case DL_INFO_ACK:
8027 		reqprim = DL_INFO_REQ;
8028 		break;
8029 	case DL_BIND_ACK:
8030 		reqprim = DL_BIND_REQ;
8031 		break;
8032 	case DL_PHYS_ADDR_ACK:
8033 		reqprim = DL_PHYS_ADDR_REQ;
8034 		break;
8035 	case DL_NOTIFY_ACK:
8036 		reqprim = DL_NOTIFY_REQ;
8037 		break;
8038 	case DL_CAPABILITY_ACK:
8039 		reqprim = DL_CAPABILITY_REQ;
8040 		break;
8041 	}
8042 
8043 	if (prim != DL_NOTIFY_IND) {
8044 		if (reqprim == DL_PRIM_INVAL ||
8045 		    !ill_dlpi_pending(ill, reqprim)) {
8046 			/* Not a DLPI message we support or expected */
8047 			freemsg(mp);
8048 			return;
8049 		}
8050 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8051 		    dl_primstr(reqprim)));
8052 	}
8053 
8054 	switch (reqprim) {
8055 	case DL_UNBIND_REQ:
8056 		/*
8057 		 * NOTE: we mark the unbind as complete even if we got a
8058 		 * DL_ERROR_ACK, since there's not much else we can do.
8059 		 */
8060 		mutex_enter(&ill->ill_lock);
8061 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8062 		cv_signal(&ill->ill_cv);
8063 		mutex_exit(&ill->ill_lock);
8064 		break;
8065 
8066 	case DL_ENABMULTI_REQ:
8067 		if (prim == DL_OK_ACK) {
8068 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8069 				ill->ill_dlpi_multicast_state = IDS_OK;
8070 		}
8071 		break;
8072 	}
8073 
8074 	/*
8075 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8076 	 * need to become writer to continue to process it.  Because an
8077 	 * exclusive operation doesn't complete until replies to all queued
8078 	 * DLPI messages have been received, we know we're in the middle of an
8079 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8080 	 *
8081 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8082 	 * Since this is on the ill stream we unconditionally bump up the
8083 	 * refcount without doing ILL_CAN_LOOKUP().
8084 	 */
8085 	ill_refhold(ill);
8086 	if (prim == DL_NOTIFY_IND)
8087 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8088 	else
8089 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8090 }
8091 
8092 /*
8093  * Handling of DLPI messages that require exclusive access to the ipsq.
8094  *
8095  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8096  * happen here. (along with mi_copy_done)
8097  */
8098 /* ARGSUSED */
8099 static void
8100 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8101 {
8102 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8103 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8104 	int		err = 0;
8105 	ill_t		*ill = (ill_t *)q->q_ptr;
8106 	ipif_t		*ipif = NULL;
8107 	mblk_t		*mp1 = NULL;
8108 	conn_t		*connp = NULL;
8109 	t_uscalar_t	paddrreq;
8110 	mblk_t		*mp_hw;
8111 	boolean_t	success;
8112 	boolean_t	ioctl_aborted = B_FALSE;
8113 	boolean_t	log = B_TRUE;
8114 
8115 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8116 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8117 
8118 	ip1dbg(("ip_rput_dlpi_writer .."));
8119 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8120 	ASSERT(IAM_WRITER_ILL(ill));
8121 
8122 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8123 	/*
8124 	 * The current ioctl could have been aborted by the user and a new
8125 	 * ioctl to bring up another ill could have started. We could still
8126 	 * get a response from the driver later.
8127 	 */
8128 	if (ipif != NULL && ipif->ipif_ill != ill)
8129 		ioctl_aborted = B_TRUE;
8130 
8131 	switch (dloa->dl_primitive) {
8132 	case DL_ERROR_ACK:
8133 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8134 		    dl_primstr(dlea->dl_error_primitive)));
8135 
8136 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8137 		    char *, dl_primstr(dlea->dl_error_primitive),
8138 		    ill_t *, ill);
8139 
8140 		switch (dlea->dl_error_primitive) {
8141 		case DL_DISABMULTI_REQ:
8142 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8143 			break;
8144 		case DL_PROMISCON_REQ:
8145 		case DL_PROMISCOFF_REQ:
8146 		case DL_UNBIND_REQ:
8147 		case DL_ATTACH_REQ:
8148 		case DL_INFO_REQ:
8149 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8150 			break;
8151 		case DL_NOTIFY_REQ:
8152 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8153 			log = B_FALSE;
8154 			break;
8155 		case DL_PHYS_ADDR_REQ:
8156 			/*
8157 			 * For IPv6 only, there are two additional
8158 			 * phys_addr_req's sent to the driver to get the
8159 			 * IPv6 token and lla. This allows IP to acquire
8160 			 * the hardware address format for a given interface
8161 			 * without having built in knowledge of the hardware
8162 			 * address. ill_phys_addr_pend keeps track of the last
8163 			 * DL_PAR sent so we know which response we are
8164 			 * dealing with. ill_dlpi_done will update
8165 			 * ill_phys_addr_pend when it sends the next req.
8166 			 * We don't complete the IOCTL until all three DL_PARs
8167 			 * have been attempted, so set *_len to 0 and break.
8168 			 */
8169 			paddrreq = ill->ill_phys_addr_pend;
8170 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8171 			if (paddrreq == DL_IPV6_TOKEN) {
8172 				ill->ill_token_length = 0;
8173 				log = B_FALSE;
8174 				break;
8175 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8176 				ill->ill_nd_lla_len = 0;
8177 				log = B_FALSE;
8178 				break;
8179 			}
8180 			/*
8181 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8182 			 * We presumably have an IOCTL hanging out waiting
8183 			 * for completion. Find it and complete the IOCTL
8184 			 * with the error noted.
8185 			 * However, ill_dl_phys was called on an ill queue
8186 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8187 			 * set. But the ioctl is known to be pending on ill_wq.
8188 			 */
8189 			if (!ill->ill_ifname_pending)
8190 				break;
8191 			ill->ill_ifname_pending = 0;
8192 			if (!ioctl_aborted)
8193 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8194 			if (mp1 != NULL) {
8195 				/*
8196 				 * This operation (SIOCSLIFNAME) must have
8197 				 * happened on the ill. Assert there is no conn
8198 				 */
8199 				ASSERT(connp == NULL);
8200 				q = ill->ill_wq;
8201 			}
8202 			break;
8203 		case DL_BIND_REQ:
8204 			ill_dlpi_done(ill, DL_BIND_REQ);
8205 			if (ill->ill_ifname_pending)
8206 				break;
8207 			/*
8208 			 * Something went wrong with the bind.  We presumably
8209 			 * have an IOCTL hanging out waiting for completion.
8210 			 * Find it, take down the interface that was coming
8211 			 * up, and complete the IOCTL with the error noted.
8212 			 */
8213 			if (!ioctl_aborted)
8214 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8215 			if (mp1 != NULL) {
8216 				/*
8217 				 * This might be a result of a DL_NOTE_REPLUMB
8218 				 * notification. In that case, connp is NULL.
8219 				 */
8220 				if (connp != NULL)
8221 					q = CONNP_TO_WQ(connp);
8222 
8223 				(void) ipif_down(ipif, NULL, NULL);
8224 				/* error is set below the switch */
8225 			}
8226 			break;
8227 		case DL_ENABMULTI_REQ:
8228 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8229 
8230 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8231 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8232 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8233 
8234 				printf("ip: joining multicasts failed (%d)"
8235 				    " on %s - will use link layer "
8236 				    "broadcasts for multicast\n",
8237 				    dlea->dl_errno, ill->ill_name);
8238 
8239 				/*
8240 				 * Set up for multi_bcast; We are the
8241 				 * writer, so ok to access ill->ill_ipif
8242 				 * without any lock.
8243 				 */
8244 				mutex_enter(&ill->ill_phyint->phyint_lock);
8245 				ill->ill_phyint->phyint_flags |=
8246 				    PHYI_MULTI_BCAST;
8247 				mutex_exit(&ill->ill_phyint->phyint_lock);
8248 
8249 			}
8250 			freemsg(mp);	/* Don't want to pass this up */
8251 			return;
8252 		case DL_CAPABILITY_REQ:
8253 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8254 			    "DL_CAPABILITY REQ\n"));
8255 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8256 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8257 			ill_capability_done(ill);
8258 			freemsg(mp);
8259 			return;
8260 		}
8261 		/*
8262 		 * Note the error for IOCTL completion (mp1 is set when
8263 		 * ready to complete ioctl). If ill_ifname_pending_err is
8264 		 * set, an error occured during plumbing (ill_ifname_pending),
8265 		 * so we want to report that error.
8266 		 *
8267 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8268 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8269 		 * expected to get errack'd if the driver doesn't support
8270 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8271 		 * if these error conditions are encountered.
8272 		 */
8273 		if (mp1 != NULL) {
8274 			if (ill->ill_ifname_pending_err != 0)  {
8275 				err = ill->ill_ifname_pending_err;
8276 				ill->ill_ifname_pending_err = 0;
8277 			} else {
8278 				err = dlea->dl_unix_errno ?
8279 				    dlea->dl_unix_errno : ENXIO;
8280 			}
8281 		/*
8282 		 * If we're plumbing an interface and an error hasn't already
8283 		 * been saved, set ill_ifname_pending_err to the error passed
8284 		 * up. Ignore the error if log is B_FALSE (see comment above).
8285 		 */
8286 		} else if (log && ill->ill_ifname_pending &&
8287 		    ill->ill_ifname_pending_err == 0) {
8288 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8289 			    dlea->dl_unix_errno : ENXIO;
8290 		}
8291 
8292 		if (log)
8293 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8294 			    dlea->dl_errno, dlea->dl_unix_errno);
8295 		break;
8296 	case DL_CAPABILITY_ACK:
8297 		ill_capability_ack(ill, mp);
8298 		/*
8299 		 * The message has been handed off to ill_capability_ack
8300 		 * and must not be freed below
8301 		 */
8302 		mp = NULL;
8303 		break;
8304 
8305 	case DL_INFO_ACK:
8306 		/* Call a routine to handle this one. */
8307 		ill_dlpi_done(ill, DL_INFO_REQ);
8308 		ip_ll_subnet_defaults(ill, mp);
8309 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8310 		return;
8311 	case DL_BIND_ACK:
8312 		/*
8313 		 * We should have an IOCTL waiting on this unless
8314 		 * sent by ill_dl_phys, in which case just return
8315 		 */
8316 		ill_dlpi_done(ill, DL_BIND_REQ);
8317 		if (ill->ill_ifname_pending) {
8318 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8319 			    ill_t *, ill, mblk_t *, mp);
8320 			break;
8321 		}
8322 		if (!ioctl_aborted)
8323 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8324 		if (mp1 == NULL) {
8325 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8326 			break;
8327 		}
8328 		/*
8329 		 * mp1 was added by ill_dl_up(). if that is a result of
8330 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8331 		 */
8332 		if (connp != NULL)
8333 			q = CONNP_TO_WQ(connp);
8334 		/*
8335 		 * We are exclusive. So nothing can change even after
8336 		 * we get the pending mp.
8337 		 */
8338 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8339 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8340 
8341 		mutex_enter(&ill->ill_lock);
8342 		ill->ill_dl_up = 1;
8343 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8344 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8345 		mutex_exit(&ill->ill_lock);
8346 
8347 		/*
8348 		 * Now bring up the resolver; when that is complete, we'll
8349 		 * create IREs.  Note that we intentionally mirror what
8350 		 * ipif_up() would have done, because we got here by way of
8351 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8352 		 */
8353 		if (ill->ill_isv6) {
8354 			/*
8355 			 * v6 interfaces.
8356 			 * Unlike ARP which has to do another bind
8357 			 * and attach, once we get here we are
8358 			 * done with NDP
8359 			 */
8360 			(void) ipif_resolver_up(ipif, Res_act_initial);
8361 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8362 				err = ipif_up_done_v6(ipif);
8363 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8364 			/*
8365 			 * ARP and other v4 external resolvers.
8366 			 * Leave the pending mblk intact so that
8367 			 * the ioctl completes in ip_rput().
8368 			 */
8369 			if (connp != NULL)
8370 				mutex_enter(&connp->conn_lock);
8371 			mutex_enter(&ill->ill_lock);
8372 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8373 			mutex_exit(&ill->ill_lock);
8374 			if (connp != NULL)
8375 				mutex_exit(&connp->conn_lock);
8376 			if (success) {
8377 				err = ipif_resolver_up(ipif, Res_act_initial);
8378 				if (err == EINPROGRESS) {
8379 					freemsg(mp);
8380 					return;
8381 				}
8382 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8383 			} else {
8384 				/* The conn has started closing */
8385 				err = EINTR;
8386 			}
8387 		} else {
8388 			/*
8389 			 * This one is complete. Reply to pending ioctl.
8390 			 */
8391 			(void) ipif_resolver_up(ipif, Res_act_initial);
8392 			err = ipif_up_done(ipif);
8393 		}
8394 
8395 		if ((err == 0) && (ill->ill_up_ipifs)) {
8396 			err = ill_up_ipifs(ill, q, mp1);
8397 			if (err == EINPROGRESS) {
8398 				freemsg(mp);
8399 				return;
8400 			}
8401 		}
8402 
8403 		/*
8404 		 * If we have a moved ipif to bring up, and everything has
8405 		 * succeeded to this point, bring it up on the IPMP ill.
8406 		 * Otherwise, leave it down -- the admin can try to bring it
8407 		 * up by hand if need be.
8408 		 */
8409 		if (ill->ill_move_ipif != NULL) {
8410 			if (err != 0) {
8411 				ill->ill_move_ipif = NULL;
8412 			} else {
8413 				ipif = ill->ill_move_ipif;
8414 				ill->ill_move_ipif = NULL;
8415 				err = ipif_up(ipif, q, mp1);
8416 				if (err == EINPROGRESS) {
8417 					freemsg(mp);
8418 					return;
8419 				}
8420 			}
8421 		}
8422 		break;
8423 
8424 	case DL_NOTIFY_IND: {
8425 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8426 		uint_t orig_mtu;
8427 
8428 		switch (notify->dl_notification) {
8429 		case DL_NOTE_PHYS_ADDR:
8430 			err = ill_set_phys_addr(ill, mp);
8431 			break;
8432 
8433 		case DL_NOTE_REPLUMB:
8434 			/*
8435 			 * Directly return after calling ill_replumb().
8436 			 * Note that we should not free mp as it is reused
8437 			 * in the ill_replumb() function.
8438 			 */
8439 			err = ill_replumb(ill, mp);
8440 			return;
8441 
8442 		case DL_NOTE_FASTPATH_FLUSH:
8443 			nce_flush(ill, B_FALSE);
8444 			break;
8445 
8446 		case DL_NOTE_SDU_SIZE:
8447 			/*
8448 			 * The dce and fragmentation code can cope with
8449 			 * this changing while packets are being sent.
8450 			 * When packets are sent ip_output will discover
8451 			 * a change.
8452 			 *
8453 			 * Change the MTU size of the interface.
8454 			 */
8455 			mutex_enter(&ill->ill_lock);
8456 			ill->ill_current_frag = (uint_t)notify->dl_data;
8457 			if (ill->ill_current_frag > ill->ill_max_frag)
8458 				ill->ill_max_frag = ill->ill_current_frag;
8459 
8460 			orig_mtu = ill->ill_mtu;
8461 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8462 				ill->ill_mtu = ill->ill_current_frag;
8463 
8464 				/*
8465 				 * If ill_user_mtu was set (via
8466 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8467 				 */
8468 				if (ill->ill_user_mtu != 0 &&
8469 				    ill->ill_user_mtu < ill->ill_mtu)
8470 					ill->ill_mtu = ill->ill_user_mtu;
8471 
8472 				if (ill->ill_isv6) {
8473 					if (ill->ill_mtu < IPV6_MIN_MTU)
8474 						ill->ill_mtu = IPV6_MIN_MTU;
8475 				} else {
8476 					if (ill->ill_mtu < IP_MIN_MTU)
8477 						ill->ill_mtu = IP_MIN_MTU;
8478 				}
8479 			}
8480 			mutex_exit(&ill->ill_lock);
8481 			/*
8482 			 * Make sure all dce_generation checks find out
8483 			 * that ill_mtu has changed.
8484 			 */
8485 			if (orig_mtu != ill->ill_mtu) {
8486 				dce_increment_all_generations(ill->ill_isv6,
8487 				    ill->ill_ipst);
8488 			}
8489 
8490 			/*
8491 			 * Refresh IPMP meta-interface MTU if necessary.
8492 			 */
8493 			if (IS_UNDER_IPMP(ill))
8494 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8495 			break;
8496 
8497 		case DL_NOTE_LINK_UP:
8498 		case DL_NOTE_LINK_DOWN: {
8499 			/*
8500 			 * We are writer. ill / phyint / ipsq assocs stable.
8501 			 * The RUNNING flag reflects the state of the link.
8502 			 */
8503 			phyint_t *phyint = ill->ill_phyint;
8504 			uint64_t new_phyint_flags;
8505 			boolean_t changed = B_FALSE;
8506 			boolean_t went_up;
8507 
8508 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8509 			mutex_enter(&phyint->phyint_lock);
8510 
8511 			new_phyint_flags = went_up ?
8512 			    phyint->phyint_flags | PHYI_RUNNING :
8513 			    phyint->phyint_flags & ~PHYI_RUNNING;
8514 
8515 			if (IS_IPMP(ill)) {
8516 				new_phyint_flags = went_up ?
8517 				    new_phyint_flags & ~PHYI_FAILED :
8518 				    new_phyint_flags | PHYI_FAILED;
8519 			}
8520 
8521 			if (new_phyint_flags != phyint->phyint_flags) {
8522 				phyint->phyint_flags = new_phyint_flags;
8523 				changed = B_TRUE;
8524 			}
8525 			mutex_exit(&phyint->phyint_lock);
8526 			/*
8527 			 * ill_restart_dad handles the DAD restart and routing
8528 			 * socket notification logic.
8529 			 */
8530 			if (changed) {
8531 				ill_restart_dad(phyint->phyint_illv4, went_up);
8532 				ill_restart_dad(phyint->phyint_illv6, went_up);
8533 			}
8534 			break;
8535 		}
8536 		case DL_NOTE_PROMISC_ON_PHYS: {
8537 			phyint_t *phyint = ill->ill_phyint;
8538 
8539 			mutex_enter(&phyint->phyint_lock);
8540 			phyint->phyint_flags |= PHYI_PROMISC;
8541 			mutex_exit(&phyint->phyint_lock);
8542 			break;
8543 		}
8544 		case DL_NOTE_PROMISC_OFF_PHYS: {
8545 			phyint_t *phyint = ill->ill_phyint;
8546 
8547 			mutex_enter(&phyint->phyint_lock);
8548 			phyint->phyint_flags &= ~PHYI_PROMISC;
8549 			mutex_exit(&phyint->phyint_lock);
8550 			break;
8551 		}
8552 		case DL_NOTE_CAPAB_RENEG:
8553 			/*
8554 			 * Something changed on the driver side.
8555 			 * It wants us to renegotiate the capabilities
8556 			 * on this ill. One possible cause is the aggregation
8557 			 * interface under us where a port got added or
8558 			 * went away.
8559 			 *
8560 			 * If the capability negotiation is already done
8561 			 * or is in progress, reset the capabilities and
8562 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8563 			 * so that when the ack comes back, we can start
8564 			 * the renegotiation process.
8565 			 *
8566 			 * Note that if ill_capab_reneg is already B_TRUE
8567 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8568 			 * the capability resetting request has been sent
8569 			 * and the renegotiation has not been started yet;
8570 			 * nothing needs to be done in this case.
8571 			 */
8572 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8573 			ill_capability_reset(ill, B_TRUE);
8574 			ipsq_current_finish(ipsq);
8575 			break;
8576 		default:
8577 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8578 			    "type 0x%x for DL_NOTIFY_IND\n",
8579 			    notify->dl_notification));
8580 			break;
8581 		}
8582 
8583 		/*
8584 		 * As this is an asynchronous operation, we
8585 		 * should not call ill_dlpi_done
8586 		 */
8587 		break;
8588 	}
8589 	case DL_NOTIFY_ACK: {
8590 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8591 
8592 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8593 			ill->ill_note_link = 1;
8594 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8595 		break;
8596 	}
8597 	case DL_PHYS_ADDR_ACK: {
8598 		/*
8599 		 * As part of plumbing the interface via SIOCSLIFNAME,
8600 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8601 		 * whose answers we receive here.  As each answer is received,
8602 		 * we call ill_dlpi_done() to dispatch the next request as
8603 		 * we're processing the current one.  Once all answers have
8604 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8605 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8606 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8607 		 * available, but we know the ioctl is pending on ill_wq.)
8608 		 */
8609 		uint_t	paddrlen, paddroff;
8610 		uint8_t	*addr;
8611 
8612 		paddrreq = ill->ill_phys_addr_pend;
8613 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8614 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8615 		addr = mp->b_rptr + paddroff;
8616 
8617 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8618 		if (paddrreq == DL_IPV6_TOKEN) {
8619 			/*
8620 			 * bcopy to low-order bits of ill_token
8621 			 *
8622 			 * XXX Temporary hack - currently, all known tokens
8623 			 * are 64 bits, so I'll cheat for the moment.
8624 			 */
8625 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8626 			ill->ill_token_length = paddrlen;
8627 			break;
8628 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8629 			ASSERT(ill->ill_nd_lla_mp == NULL);
8630 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8631 			mp = NULL;
8632 			break;
8633 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8634 			ASSERT(ill->ill_dest_addr_mp == NULL);
8635 			ill->ill_dest_addr_mp = mp;
8636 			ill->ill_dest_addr = addr;
8637 			mp = NULL;
8638 			if (ill->ill_isv6) {
8639 				ill_setdesttoken(ill);
8640 				ipif_setdestlinklocal(ill->ill_ipif);
8641 			}
8642 			break;
8643 		}
8644 
8645 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8646 		ASSERT(ill->ill_phys_addr_mp == NULL);
8647 		if (!ill->ill_ifname_pending)
8648 			break;
8649 		ill->ill_ifname_pending = 0;
8650 		if (!ioctl_aborted)
8651 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8652 		if (mp1 != NULL) {
8653 			ASSERT(connp == NULL);
8654 			q = ill->ill_wq;
8655 		}
8656 		/*
8657 		 * If any error acks received during the plumbing sequence,
8658 		 * ill_ifname_pending_err will be set. Break out and send up
8659 		 * the error to the pending ioctl.
8660 		 */
8661 		if (ill->ill_ifname_pending_err != 0) {
8662 			err = ill->ill_ifname_pending_err;
8663 			ill->ill_ifname_pending_err = 0;
8664 			break;
8665 		}
8666 
8667 		ill->ill_phys_addr_mp = mp;
8668 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8669 		mp = NULL;
8670 
8671 		/*
8672 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8673 		 * provider doesn't support physical addresses.  We check both
8674 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8675 		 * not have physical addresses, but historically adversises a
8676 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8677 		 * its DL_PHYS_ADDR_ACK.
8678 		 */
8679 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8680 			ill->ill_phys_addr = NULL;
8681 		} else if (paddrlen != ill->ill_phys_addr_length) {
8682 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8683 			    paddrlen, ill->ill_phys_addr_length));
8684 			err = EINVAL;
8685 			break;
8686 		}
8687 
8688 		if (ill->ill_nd_lla_mp == NULL) {
8689 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8690 				err = ENOMEM;
8691 				break;
8692 			}
8693 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8694 		}
8695 
8696 		if (ill->ill_isv6) {
8697 			ill_setdefaulttoken(ill);
8698 			ipif_setlinklocal(ill->ill_ipif);
8699 		}
8700 		break;
8701 	}
8702 	case DL_OK_ACK:
8703 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8704 		    dl_primstr((int)dloa->dl_correct_primitive),
8705 		    dloa->dl_correct_primitive));
8706 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8707 		    char *, dl_primstr(dloa->dl_correct_primitive),
8708 		    ill_t *, ill);
8709 
8710 		switch (dloa->dl_correct_primitive) {
8711 		case DL_ENABMULTI_REQ:
8712 		case DL_DISABMULTI_REQ:
8713 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8714 			break;
8715 		case DL_PROMISCON_REQ:
8716 		case DL_PROMISCOFF_REQ:
8717 		case DL_UNBIND_REQ:
8718 		case DL_ATTACH_REQ:
8719 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8720 			break;
8721 		}
8722 		break;
8723 	default:
8724 		break;
8725 	}
8726 
8727 	freemsg(mp);
8728 	if (mp1 == NULL)
8729 		return;
8730 
8731 	/*
8732 	 * The operation must complete without EINPROGRESS since
8733 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8734 	 * the operation will be stuck forever inside the IPSQ.
8735 	 */
8736 	ASSERT(err != EINPROGRESS);
8737 
8738 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8739 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8740 	    ipif_t *, NULL);
8741 
8742 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8743 	case 0:
8744 		ipsq_current_finish(ipsq);
8745 		break;
8746 
8747 	case SIOCSLIFNAME:
8748 	case IF_UNITSEL: {
8749 		ill_t *ill_other = ILL_OTHER(ill);
8750 
8751 		/*
8752 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8753 		 * ill has a peer which is in an IPMP group, then place ill
8754 		 * into the same group.  One catch: although ifconfig plumbs
8755 		 * the appropriate IPMP meta-interface prior to plumbing this
8756 		 * ill, it is possible for multiple ifconfig applications to
8757 		 * race (or for another application to adjust plumbing), in
8758 		 * which case the IPMP meta-interface we need will be missing.
8759 		 * If so, kick the phyint out of the group.
8760 		 */
8761 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8762 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8763 			ipmp_illgrp_t	*illg;
8764 
8765 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8766 			if (illg == NULL)
8767 				ipmp_phyint_leave_grp(ill->ill_phyint);
8768 			else
8769 				ipmp_ill_join_illgrp(ill, illg);
8770 		}
8771 
8772 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8773 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8774 		else
8775 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8776 		break;
8777 	}
8778 	case SIOCLIFADDIF:
8779 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8780 		break;
8781 
8782 	default:
8783 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8784 		break;
8785 	}
8786 }
8787 
8788 /*
8789  * ip_rput_other is called by ip_rput to handle messages modifying the global
8790  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8791  */
8792 /* ARGSUSED */
8793 void
8794 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8795 {
8796 	ill_t		*ill = q->q_ptr;
8797 	struct iocblk	*iocp;
8798 
8799 	ip1dbg(("ip_rput_other "));
8800 	if (ipsq != NULL) {
8801 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8802 		ASSERT(ipsq->ipsq_xop ==
8803 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8804 	}
8805 
8806 	switch (mp->b_datap->db_type) {
8807 	case M_ERROR:
8808 	case M_HANGUP:
8809 		/*
8810 		 * The device has a problem.  We force the ILL down.  It can
8811 		 * be brought up again manually using SIOCSIFFLAGS (via
8812 		 * ifconfig or equivalent).
8813 		 */
8814 		ASSERT(ipsq != NULL);
8815 		if (mp->b_rptr < mp->b_wptr)
8816 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8817 		if (ill->ill_error == 0)
8818 			ill->ill_error = ENXIO;
8819 		if (!ill_down_start(q, mp))
8820 			return;
8821 		ipif_all_down_tail(ipsq, q, mp, NULL);
8822 		break;
8823 	case M_IOCNAK: {
8824 		iocp = (struct iocblk *)mp->b_rptr;
8825 
8826 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8827 		/*
8828 		 * If this was the first attempt, turn off the fastpath
8829 		 * probing.
8830 		 */
8831 		mutex_enter(&ill->ill_lock);
8832 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8833 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8834 			mutex_exit(&ill->ill_lock);
8835 			/*
8836 			 * don't flush the nce_t entries: we use them
8837 			 * as an index to the ncec itself.
8838 			 */
8839 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8840 			    ill->ill_name));
8841 		} else {
8842 			mutex_exit(&ill->ill_lock);
8843 		}
8844 		freemsg(mp);
8845 		break;
8846 	}
8847 	default:
8848 		ASSERT(0);
8849 		break;
8850 	}
8851 }
8852 
8853 /*
8854  * Update any source route, record route or timestamp options
8855  * When it fails it has consumed the message and BUMPed the MIB.
8856  */
8857 boolean_t
8858 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8859     ip_recv_attr_t *ira)
8860 {
8861 	ipoptp_t	opts;
8862 	uchar_t		*opt;
8863 	uint8_t		optval;
8864 	uint8_t		optlen;
8865 	ipaddr_t	dst;
8866 	ipaddr_t	ifaddr;
8867 	uint32_t	ts;
8868 	timestruc_t	now;
8869 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
8870 
8871 	ip2dbg(("ip_forward_options\n"));
8872 	dst = ipha->ipha_dst;
8873 	for (optval = ipoptp_first(&opts, ipha);
8874 	    optval != IPOPT_EOL;
8875 	    optval = ipoptp_next(&opts)) {
8876 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
8877 		opt = opts.ipoptp_cur;
8878 		optlen = opts.ipoptp_len;
8879 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
8880 		    optval, opts.ipoptp_len));
8881 		switch (optval) {
8882 			uint32_t off;
8883 		case IPOPT_SSRR:
8884 		case IPOPT_LSRR:
8885 			/* Check if adminstratively disabled */
8886 			if (!ipst->ips_ip_forward_src_routed) {
8887 				BUMP_MIB(dst_ill->ill_ip_mib,
8888 				    ipIfStatsForwProhibits);
8889 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
8890 				    mp, dst_ill);
8891 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
8892 				    ira);
8893 				return (B_FALSE);
8894 			}
8895 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8896 				/*
8897 				 * Must be partial since ip_input_options
8898 				 * checked for strict.
8899 				 */
8900 				break;
8901 			}
8902 			off = opt[IPOPT_OFFSET];
8903 			off--;
8904 		redo_srr:
8905 			if (optlen < IP_ADDR_LEN ||
8906 			    off > optlen - IP_ADDR_LEN) {
8907 				/* End of source route */
8908 				ip1dbg((
8909 				    "ip_forward_options: end of SR\n"));
8910 				break;
8911 			}
8912 			/* Pick a reasonable address on the outbound if */
8913 			ASSERT(dst_ill != NULL);
8914 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8915 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8916 			    NULL) != 0) {
8917 				/* No source! Shouldn't happen */
8918 				ifaddr = INADDR_ANY;
8919 			}
8920 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8921 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8922 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
8923 			    ntohl(dst)));
8924 
8925 			/*
8926 			 * Check if our address is present more than
8927 			 * once as consecutive hops in source route.
8928 			 */
8929 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
8930 				off += IP_ADDR_LEN;
8931 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8932 				goto redo_srr;
8933 			}
8934 			ipha->ipha_dst = dst;
8935 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8936 			break;
8937 		case IPOPT_RR:
8938 			off = opt[IPOPT_OFFSET];
8939 			off--;
8940 			if (optlen < IP_ADDR_LEN ||
8941 			    off > optlen - IP_ADDR_LEN) {
8942 				/* No more room - ignore */
8943 				ip1dbg((
8944 				    "ip_forward_options: end of RR\n"));
8945 				break;
8946 			}
8947 			/* Pick a reasonable address on the outbound if */
8948 			ASSERT(dst_ill != NULL);
8949 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8950 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8951 			    NULL) != 0) {
8952 				/* No source! Shouldn't happen */
8953 				ifaddr = INADDR_ANY;
8954 			}
8955 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8956 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8957 			break;
8958 		case IPOPT_TS:
8959 			/* Insert timestamp if there is room */
8960 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
8961 			case IPOPT_TS_TSONLY:
8962 				off = IPOPT_TS_TIMELEN;
8963 				break;
8964 			case IPOPT_TS_PRESPEC:
8965 			case IPOPT_TS_PRESPEC_RFC791:
8966 				/* Verify that the address matched */
8967 				off = opt[IPOPT_OFFSET] - 1;
8968 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8969 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8970 					/* Not for us */
8971 					break;
8972 				}
8973 				/* FALLTHRU */
8974 			case IPOPT_TS_TSANDADDR:
8975 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
8976 				break;
8977 			default:
8978 				/*
8979 				 * ip_*put_options should have already
8980 				 * dropped this packet.
8981 				 */
8982 				cmn_err(CE_PANIC, "ip_forward_options: "
8983 				    "unknown IT - bug in ip_input_options?\n");
8984 				return (B_TRUE);	/* Keep "lint" happy */
8985 			}
8986 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
8987 				/* Increase overflow counter */
8988 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
8989 				opt[IPOPT_POS_OV_FLG] =
8990 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
8991 				    (off << 4));
8992 				break;
8993 			}
8994 			off = opt[IPOPT_OFFSET] - 1;
8995 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
8996 			case IPOPT_TS_PRESPEC:
8997 			case IPOPT_TS_PRESPEC_RFC791:
8998 			case IPOPT_TS_TSANDADDR:
8999 				/* Pick a reasonable addr on the outbound if */
9000 				ASSERT(dst_ill != NULL);
9001 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9002 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9003 				    NULL, NULL) != 0) {
9004 					/* No source! Shouldn't happen */
9005 					ifaddr = INADDR_ANY;
9006 				}
9007 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9008 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9009 				/* FALLTHRU */
9010 			case IPOPT_TS_TSONLY:
9011 				off = opt[IPOPT_OFFSET] - 1;
9012 				/* Compute # of milliseconds since midnight */
9013 				gethrestime(&now);
9014 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9015 				    now.tv_nsec / (NANOSEC / MILLISEC);
9016 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9017 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9018 				break;
9019 			}
9020 			break;
9021 		}
9022 	}
9023 	return (B_TRUE);
9024 }
9025 
9026 /*
9027  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9028  * returns 'true' if there are still fragments left on the queue, in
9029  * which case we restart the timer.
9030  */
9031 void
9032 ill_frag_timer(void *arg)
9033 {
9034 	ill_t	*ill = (ill_t *)arg;
9035 	boolean_t frag_pending;
9036 	ip_stack_t *ipst = ill->ill_ipst;
9037 	time_t	timeout;
9038 
9039 	mutex_enter(&ill->ill_lock);
9040 	ASSERT(!ill->ill_fragtimer_executing);
9041 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9042 		ill->ill_frag_timer_id = 0;
9043 		mutex_exit(&ill->ill_lock);
9044 		return;
9045 	}
9046 	ill->ill_fragtimer_executing = 1;
9047 	mutex_exit(&ill->ill_lock);
9048 
9049 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9050 	    ipst->ips_ip_reassembly_timeout);
9051 
9052 	frag_pending = ill_frag_timeout(ill, timeout);
9053 
9054 	/*
9055 	 * Restart the timer, if we have fragments pending or if someone
9056 	 * wanted us to be scheduled again.
9057 	 */
9058 	mutex_enter(&ill->ill_lock);
9059 	ill->ill_fragtimer_executing = 0;
9060 	ill->ill_frag_timer_id = 0;
9061 	if (frag_pending || ill->ill_fragtimer_needrestart)
9062 		ill_frag_timer_start(ill);
9063 	mutex_exit(&ill->ill_lock);
9064 }
9065 
9066 void
9067 ill_frag_timer_start(ill_t *ill)
9068 {
9069 	ip_stack_t *ipst = ill->ill_ipst;
9070 	clock_t	timeo_ms;
9071 
9072 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9073 
9074 	/* If the ill is closing or opening don't proceed */
9075 	if (ill->ill_state_flags & ILL_CONDEMNED)
9076 		return;
9077 
9078 	if (ill->ill_fragtimer_executing) {
9079 		/*
9080 		 * ill_frag_timer is currently executing. Just record the
9081 		 * the fact that we want the timer to be restarted.
9082 		 * ill_frag_timer will post a timeout before it returns,
9083 		 * ensuring it will be called again.
9084 		 */
9085 		ill->ill_fragtimer_needrestart = 1;
9086 		return;
9087 	}
9088 
9089 	if (ill->ill_frag_timer_id == 0) {
9090 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9091 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9092 
9093 		/*
9094 		 * The timer is neither running nor is the timeout handler
9095 		 * executing. Post a timeout so that ill_frag_timer will be
9096 		 * called
9097 		 */
9098 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9099 		    MSEC_TO_TICK(timeo_ms >> 1));
9100 		ill->ill_fragtimer_needrestart = 0;
9101 	}
9102 }
9103 
9104 /*
9105  * Update any source route, record route or timestamp options.
9106  * Check that we are at end of strict source route.
9107  * The options have already been checked for sanity in ip_input_options().
9108  */
9109 boolean_t
9110 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9111 {
9112 	ipoptp_t	opts;
9113 	uchar_t		*opt;
9114 	uint8_t		optval;
9115 	uint8_t		optlen;
9116 	ipaddr_t	dst;
9117 	ipaddr_t	ifaddr;
9118 	uint32_t	ts;
9119 	timestruc_t	now;
9120 	ill_t		*ill = ira->ira_ill;
9121 	ip_stack_t	*ipst = ill->ill_ipst;
9122 
9123 	ip2dbg(("ip_input_local_options\n"));
9124 
9125 	for (optval = ipoptp_first(&opts, ipha);
9126 	    optval != IPOPT_EOL;
9127 	    optval = ipoptp_next(&opts)) {
9128 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9129 		opt = opts.ipoptp_cur;
9130 		optlen = opts.ipoptp_len;
9131 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9132 		    optval, optlen));
9133 		switch (optval) {
9134 			uint32_t off;
9135 		case IPOPT_SSRR:
9136 		case IPOPT_LSRR:
9137 			off = opt[IPOPT_OFFSET];
9138 			off--;
9139 			if (optlen < IP_ADDR_LEN ||
9140 			    off > optlen - IP_ADDR_LEN) {
9141 				/* End of source route */
9142 				ip1dbg(("ip_input_local_options: end of SR\n"));
9143 				break;
9144 			}
9145 			/*
9146 			 * This will only happen if two consecutive entries
9147 			 * in the source route contains our address or if
9148 			 * it is a packet with a loose source route which
9149 			 * reaches us before consuming the whole source route
9150 			 */
9151 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9152 			if (optval == IPOPT_SSRR) {
9153 				goto bad_src_route;
9154 			}
9155 			/*
9156 			 * Hack: instead of dropping the packet truncate the
9157 			 * source route to what has been used by filling the
9158 			 * rest with IPOPT_NOP.
9159 			 */
9160 			opt[IPOPT_OLEN] = (uint8_t)off;
9161 			while (off < optlen) {
9162 				opt[off++] = IPOPT_NOP;
9163 			}
9164 			break;
9165 		case IPOPT_RR:
9166 			off = opt[IPOPT_OFFSET];
9167 			off--;
9168 			if (optlen < IP_ADDR_LEN ||
9169 			    off > optlen - IP_ADDR_LEN) {
9170 				/* No more room - ignore */
9171 				ip1dbg((
9172 				    "ip_input_local_options: end of RR\n"));
9173 				break;
9174 			}
9175 			/* Pick a reasonable address on the outbound if */
9176 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9177 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9178 			    NULL) != 0) {
9179 				/* No source! Shouldn't happen */
9180 				ifaddr = INADDR_ANY;
9181 			}
9182 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9183 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9184 			break;
9185 		case IPOPT_TS:
9186 			/* Insert timestamp if there is romm */
9187 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9188 			case IPOPT_TS_TSONLY:
9189 				off = IPOPT_TS_TIMELEN;
9190 				break;
9191 			case IPOPT_TS_PRESPEC:
9192 			case IPOPT_TS_PRESPEC_RFC791:
9193 				/* Verify that the address matched */
9194 				off = opt[IPOPT_OFFSET] - 1;
9195 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9196 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9197 					/* Not for us */
9198 					break;
9199 				}
9200 				/* FALLTHRU */
9201 			case IPOPT_TS_TSANDADDR:
9202 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9203 				break;
9204 			default:
9205 				/*
9206 				 * ip_*put_options should have already
9207 				 * dropped this packet.
9208 				 */
9209 				cmn_err(CE_PANIC, "ip_input_local_options: "
9210 				    "unknown IT - bug in ip_input_options?\n");
9211 				return (B_TRUE);	/* Keep "lint" happy */
9212 			}
9213 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9214 				/* Increase overflow counter */
9215 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9216 				opt[IPOPT_POS_OV_FLG] =
9217 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9218 				    (off << 4));
9219 				break;
9220 			}
9221 			off = opt[IPOPT_OFFSET] - 1;
9222 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9223 			case IPOPT_TS_PRESPEC:
9224 			case IPOPT_TS_PRESPEC_RFC791:
9225 			case IPOPT_TS_TSANDADDR:
9226 				/* Pick a reasonable addr on the outbound if */
9227 				if (ip_select_source_v4(ill, INADDR_ANY,
9228 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9229 				    &ifaddr, NULL, NULL) != 0) {
9230 					/* No source! Shouldn't happen */
9231 					ifaddr = INADDR_ANY;
9232 				}
9233 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9234 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9235 				/* FALLTHRU */
9236 			case IPOPT_TS_TSONLY:
9237 				off = opt[IPOPT_OFFSET] - 1;
9238 				/* Compute # of milliseconds since midnight */
9239 				gethrestime(&now);
9240 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9241 				    now.tv_nsec / (NANOSEC / MILLISEC);
9242 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9243 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9244 				break;
9245 			}
9246 			break;
9247 		}
9248 	}
9249 	return (B_TRUE);
9250 
9251 bad_src_route:
9252 	/* make sure we clear any indication of a hardware checksum */
9253 	DB_CKSUMFLAGS(mp) = 0;
9254 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9255 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9256 	return (B_FALSE);
9257 
9258 }
9259 
9260 /*
9261  * Process IP options in an inbound packet.  Always returns the nexthop.
9262  * Normally this is the passed in nexthop, but if there is an option
9263  * that effects the nexthop (such as a source route) that will be returned.
9264  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9265  * and mp freed.
9266  */
9267 ipaddr_t
9268 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9269     ip_recv_attr_t *ira, int *errorp)
9270 {
9271 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9272 	ipoptp_t	opts;
9273 	uchar_t		*opt;
9274 	uint8_t		optval;
9275 	uint8_t		optlen;
9276 	intptr_t	code = 0;
9277 	ire_t		*ire;
9278 
9279 	ip2dbg(("ip_input_options\n"));
9280 	*errorp = 0;
9281 	for (optval = ipoptp_first(&opts, ipha);
9282 	    optval != IPOPT_EOL;
9283 	    optval = ipoptp_next(&opts)) {
9284 		opt = opts.ipoptp_cur;
9285 		optlen = opts.ipoptp_len;
9286 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9287 		    optval, optlen));
9288 		/*
9289 		 * Note: we need to verify the checksum before we
9290 		 * modify anything thus this routine only extracts the next
9291 		 * hop dst from any source route.
9292 		 */
9293 		switch (optval) {
9294 			uint32_t off;
9295 		case IPOPT_SSRR:
9296 		case IPOPT_LSRR:
9297 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9298 				if (optval == IPOPT_SSRR) {
9299 					ip1dbg(("ip_input_options: not next"
9300 					    " strict source route 0x%x\n",
9301 					    ntohl(dst)));
9302 					code = (char *)&ipha->ipha_dst -
9303 					    (char *)ipha;
9304 					goto param_prob; /* RouterReq's */
9305 				}
9306 				ip2dbg(("ip_input_options: "
9307 				    "not next source route 0x%x\n",
9308 				    ntohl(dst)));
9309 				break;
9310 			}
9311 
9312 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9313 				ip1dbg((
9314 				    "ip_input_options: bad option offset\n"));
9315 				code = (char *)&opt[IPOPT_OLEN] -
9316 				    (char *)ipha;
9317 				goto param_prob;
9318 			}
9319 			off = opt[IPOPT_OFFSET];
9320 			off--;
9321 		redo_srr:
9322 			if (optlen < IP_ADDR_LEN ||
9323 			    off > optlen - IP_ADDR_LEN) {
9324 				/* End of source route */
9325 				ip1dbg(("ip_input_options: end of SR\n"));
9326 				break;
9327 			}
9328 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9329 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9330 			    ntohl(dst)));
9331 
9332 			/*
9333 			 * Check if our address is present more than
9334 			 * once as consecutive hops in source route.
9335 			 * XXX verify per-interface ip_forwarding
9336 			 * for source route?
9337 			 */
9338 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9339 				off += IP_ADDR_LEN;
9340 				goto redo_srr;
9341 			}
9342 
9343 			if (dst == htonl(INADDR_LOOPBACK)) {
9344 				ip1dbg(("ip_input_options: loopback addr in "
9345 				    "source route!\n"));
9346 				goto bad_src_route;
9347 			}
9348 			/*
9349 			 * For strict: verify that dst is directly
9350 			 * reachable.
9351 			 */
9352 			if (optval == IPOPT_SSRR) {
9353 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9354 				    IRE_IF_ALL, NULL, ALL_ZONES,
9355 				    ira->ira_tsl,
9356 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9357 				    NULL);
9358 				if (ire == NULL) {
9359 					ip1dbg(("ip_input_options: SSRR not "
9360 					    "directly reachable: 0x%x\n",
9361 					    ntohl(dst)));
9362 					goto bad_src_route;
9363 				}
9364 				ire_refrele(ire);
9365 			}
9366 			/*
9367 			 * Defer update of the offset and the record route
9368 			 * until the packet is forwarded.
9369 			 */
9370 			break;
9371 		case IPOPT_RR:
9372 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9373 				ip1dbg((
9374 				    "ip_input_options: bad option offset\n"));
9375 				code = (char *)&opt[IPOPT_OLEN] -
9376 				    (char *)ipha;
9377 				goto param_prob;
9378 			}
9379 			break;
9380 		case IPOPT_TS:
9381 			/*
9382 			 * Verify that length >= 5 and that there is either
9383 			 * room for another timestamp or that the overflow
9384 			 * counter is not maxed out.
9385 			 */
9386 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9387 			if (optlen < IPOPT_MINLEN_IT) {
9388 				goto param_prob;
9389 			}
9390 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9391 				ip1dbg((
9392 				    "ip_input_options: bad option offset\n"));
9393 				code = (char *)&opt[IPOPT_OFFSET] -
9394 				    (char *)ipha;
9395 				goto param_prob;
9396 			}
9397 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9398 			case IPOPT_TS_TSONLY:
9399 				off = IPOPT_TS_TIMELEN;
9400 				break;
9401 			case IPOPT_TS_TSANDADDR:
9402 			case IPOPT_TS_PRESPEC:
9403 			case IPOPT_TS_PRESPEC_RFC791:
9404 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9405 				break;
9406 			default:
9407 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9408 				    (char *)ipha;
9409 				goto param_prob;
9410 			}
9411 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9412 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9413 				/*
9414 				 * No room and the overflow counter is 15
9415 				 * already.
9416 				 */
9417 				goto param_prob;
9418 			}
9419 			break;
9420 		}
9421 	}
9422 
9423 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9424 		return (dst);
9425 	}
9426 
9427 	ip1dbg(("ip_input_options: error processing IP options."));
9428 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9429 
9430 param_prob:
9431 	/* make sure we clear any indication of a hardware checksum */
9432 	DB_CKSUMFLAGS(mp) = 0;
9433 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9434 	icmp_param_problem(mp, (uint8_t)code, ira);
9435 	*errorp = -1;
9436 	return (dst);
9437 
9438 bad_src_route:
9439 	/* make sure we clear any indication of a hardware checksum */
9440 	DB_CKSUMFLAGS(mp) = 0;
9441 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9442 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9443 	*errorp = -1;
9444 	return (dst);
9445 }
9446 
9447 /*
9448  * IP & ICMP info in >=14 msg's ...
9449  *  - ip fixed part (mib2_ip_t)
9450  *  - icmp fixed part (mib2_icmp_t)
9451  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9452  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9453  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9454  *  - ipRouteAttributeTable (ip 102)	labeled routes
9455  *  - ip multicast membership (ip_member_t)
9456  *  - ip multicast source filtering (ip_grpsrc_t)
9457  *  - igmp fixed part (struct igmpstat)
9458  *  - multicast routing stats (struct mrtstat)
9459  *  - multicast routing vifs (array of struct vifctl)
9460  *  - multicast routing routes (array of struct mfcctl)
9461  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9462  *					One per ill plus one generic
9463  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9464  *					One per ill plus one generic
9465  *  - ipv6RouteEntry			all IPv6 IREs
9466  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9467  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9468  *  - ipv6AddrEntry			all IPv6 ipifs
9469  *  - ipv6 multicast membership (ipv6_member_t)
9470  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9471  *
9472  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9473  * already filled in by the caller.
9474  * Return value of 0 indicates that no messages were sent and caller
9475  * should free mpctl.
9476  */
9477 int
9478 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
9479 {
9480 	ip_stack_t *ipst;
9481 	sctp_stack_t *sctps;
9482 
9483 	if (q->q_next != NULL) {
9484 		ipst = ILLQ_TO_IPST(q);
9485 	} else {
9486 		ipst = CONNQ_TO_IPST(q);
9487 	}
9488 	ASSERT(ipst != NULL);
9489 	sctps = ipst->ips_netstack->netstack_sctp;
9490 
9491 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9492 		return (0);
9493 	}
9494 
9495 	/*
9496 	 * For the purposes of the (broken) packet shell use
9497 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9498 	 * to make TCP and UDP appear first in the list of mib items.
9499 	 * TBD: We could expand this and use it in netstat so that
9500 	 * the kernel doesn't have to produce large tables (connections,
9501 	 * routes, etc) when netstat only wants the statistics or a particular
9502 	 * table.
9503 	 */
9504 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9505 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9506 			return (1);
9507 		}
9508 	}
9509 
9510 	if (level != MIB2_TCP) {
9511 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
9512 			return (1);
9513 		}
9514 	}
9515 
9516 	if (level != MIB2_UDP) {
9517 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
9518 			return (1);
9519 		}
9520 	}
9521 
9522 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9523 	    ipst)) == NULL) {
9524 		return (1);
9525 	}
9526 
9527 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
9528 		return (1);
9529 	}
9530 
9531 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9532 		return (1);
9533 	}
9534 
9535 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9536 		return (1);
9537 	}
9538 
9539 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9540 		return (1);
9541 	}
9542 
9543 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9544 		return (1);
9545 	}
9546 
9547 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
9548 		return (1);
9549 	}
9550 
9551 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
9552 		return (1);
9553 	}
9554 
9555 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9556 		return (1);
9557 	}
9558 
9559 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9560 		return (1);
9561 	}
9562 
9563 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9564 		return (1);
9565 	}
9566 
9567 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9568 		return (1);
9569 	}
9570 
9571 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9572 		return (1);
9573 	}
9574 
9575 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9576 		return (1);
9577 	}
9578 
9579 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9580 	if (mpctl == NULL)
9581 		return (1);
9582 
9583 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9584 	if (mpctl == NULL)
9585 		return (1);
9586 
9587 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9588 		return (1);
9589 	}
9590 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9591 		return (1);
9592 	}
9593 	freemsg(mpctl);
9594 	return (1);
9595 }
9596 
9597 /* Get global (legacy) IPv4 statistics */
9598 static mblk_t *
9599 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9600     ip_stack_t *ipst)
9601 {
9602 	mib2_ip_t		old_ip_mib;
9603 	struct opthdr		*optp;
9604 	mblk_t			*mp2ctl;
9605 
9606 	/*
9607 	 * make a copy of the original message
9608 	 */
9609 	mp2ctl = copymsg(mpctl);
9610 
9611 	/* fixed length IP structure... */
9612 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9613 	optp->level = MIB2_IP;
9614 	optp->name = 0;
9615 	SET_MIB(old_ip_mib.ipForwarding,
9616 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9617 	SET_MIB(old_ip_mib.ipDefaultTTL,
9618 	    (uint32_t)ipst->ips_ip_def_ttl);
9619 	SET_MIB(old_ip_mib.ipReasmTimeout,
9620 	    ipst->ips_ip_reassembly_timeout);
9621 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9622 	    sizeof (mib2_ipAddrEntry_t));
9623 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9624 	    sizeof (mib2_ipRouteEntry_t));
9625 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9626 	    sizeof (mib2_ipNetToMediaEntry_t));
9627 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9628 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9629 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9630 	    sizeof (mib2_ipAttributeEntry_t));
9631 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9632 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9633 
9634 	/*
9635 	 * Grab the statistics from the new IP MIB
9636 	 */
9637 	SET_MIB(old_ip_mib.ipInReceives,
9638 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9639 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9640 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9641 	SET_MIB(old_ip_mib.ipForwDatagrams,
9642 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9643 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9644 	    ipmib->ipIfStatsInUnknownProtos);
9645 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9646 	SET_MIB(old_ip_mib.ipInDelivers,
9647 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9648 	SET_MIB(old_ip_mib.ipOutRequests,
9649 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9650 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9651 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9652 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9653 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9654 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9655 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9656 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9657 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9658 
9659 	/* ipRoutingDiscards is not being used */
9660 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9661 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9662 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9663 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9664 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9665 	    ipmib->ipIfStatsReasmDuplicates);
9666 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9667 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9668 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9669 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9670 	SET_MIB(old_ip_mib.rawipInOverflows,
9671 	    ipmib->rawipIfStatsInOverflows);
9672 
9673 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9674 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9675 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9676 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9677 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9678 	    ipmib->ipIfStatsOutSwitchIPVersion);
9679 
9680 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9681 	    (int)sizeof (old_ip_mib))) {
9682 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9683 		    (uint_t)sizeof (old_ip_mib)));
9684 	}
9685 
9686 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9687 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9688 	    (int)optp->level, (int)optp->name, (int)optp->len));
9689 	qreply(q, mpctl);
9690 	return (mp2ctl);
9691 }
9692 
9693 /* Per interface IPv4 statistics */
9694 static mblk_t *
9695 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9696 {
9697 	struct opthdr		*optp;
9698 	mblk_t			*mp2ctl;
9699 	ill_t			*ill;
9700 	ill_walk_context_t	ctx;
9701 	mblk_t			*mp_tail = NULL;
9702 	mib2_ipIfStatsEntry_t	global_ip_mib;
9703 
9704 	/*
9705 	 * Make a copy of the original message
9706 	 */
9707 	mp2ctl = copymsg(mpctl);
9708 
9709 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9710 	optp->level = MIB2_IP;
9711 	optp->name = MIB2_IP_TRAFFIC_STATS;
9712 	/* Include "unknown interface" ip_mib */
9713 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9714 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9715 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9716 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9717 	    (ipst->ips_ip_forwarding ? 1 : 2));
9718 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9719 	    (uint32_t)ipst->ips_ip_def_ttl);
9720 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9721 	    sizeof (mib2_ipIfStatsEntry_t));
9722 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9723 	    sizeof (mib2_ipAddrEntry_t));
9724 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9725 	    sizeof (mib2_ipRouteEntry_t));
9726 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9727 	    sizeof (mib2_ipNetToMediaEntry_t));
9728 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9729 	    sizeof (ip_member_t));
9730 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9731 	    sizeof (ip_grpsrc_t));
9732 
9733 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9734 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
9735 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9736 		    "failed to allocate %u bytes\n",
9737 		    (uint_t)sizeof (ipst->ips_ip_mib)));
9738 	}
9739 
9740 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9741 
9742 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9743 	ill = ILL_START_WALK_V4(&ctx, ipst);
9744 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9745 		ill->ill_ip_mib->ipIfStatsIfIndex =
9746 		    ill->ill_phyint->phyint_ifindex;
9747 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9748 		    (ipst->ips_ip_forwarding ? 1 : 2));
9749 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9750 		    (uint32_t)ipst->ips_ip_def_ttl);
9751 
9752 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9753 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9754 		    (char *)ill->ill_ip_mib,
9755 		    (int)sizeof (*ill->ill_ip_mib))) {
9756 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9757 			    "failed to allocate %u bytes\n",
9758 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9759 		}
9760 	}
9761 	rw_exit(&ipst->ips_ill_g_lock);
9762 
9763 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9764 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9765 	    "level %d, name %d, len %d\n",
9766 	    (int)optp->level, (int)optp->name, (int)optp->len));
9767 	qreply(q, mpctl);
9768 
9769 	if (mp2ctl == NULL)
9770 		return (NULL);
9771 
9772 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
9773 }
9774 
9775 /* Global IPv4 ICMP statistics */
9776 static mblk_t *
9777 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9778 {
9779 	struct opthdr		*optp;
9780 	mblk_t			*mp2ctl;
9781 
9782 	/*
9783 	 * Make a copy of the original message
9784 	 */
9785 	mp2ctl = copymsg(mpctl);
9786 
9787 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9788 	optp->level = MIB2_ICMP;
9789 	optp->name = 0;
9790 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9791 	    (int)sizeof (ipst->ips_icmp_mib))) {
9792 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9793 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9794 	}
9795 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9796 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9797 	    (int)optp->level, (int)optp->name, (int)optp->len));
9798 	qreply(q, mpctl);
9799 	return (mp2ctl);
9800 }
9801 
9802 /* Global IPv4 IGMP statistics */
9803 static mblk_t *
9804 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9805 {
9806 	struct opthdr		*optp;
9807 	mblk_t			*mp2ctl;
9808 
9809 	/*
9810 	 * make a copy of the original message
9811 	 */
9812 	mp2ctl = copymsg(mpctl);
9813 
9814 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9815 	optp->level = EXPER_IGMP;
9816 	optp->name = 0;
9817 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9818 	    (int)sizeof (ipst->ips_igmpstat))) {
9819 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9820 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9821 	}
9822 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9823 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9824 	    (int)optp->level, (int)optp->name, (int)optp->len));
9825 	qreply(q, mpctl);
9826 	return (mp2ctl);
9827 }
9828 
9829 /* Global IPv4 Multicast Routing statistics */
9830 static mblk_t *
9831 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9832 {
9833 	struct opthdr		*optp;
9834 	mblk_t			*mp2ctl;
9835 
9836 	/*
9837 	 * make a copy of the original message
9838 	 */
9839 	mp2ctl = copymsg(mpctl);
9840 
9841 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9842 	optp->level = EXPER_DVMRP;
9843 	optp->name = 0;
9844 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9845 		ip0dbg(("ip_mroute_stats: failed\n"));
9846 	}
9847 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9848 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9849 	    (int)optp->level, (int)optp->name, (int)optp->len));
9850 	qreply(q, mpctl);
9851 	return (mp2ctl);
9852 }
9853 
9854 /* IPv4 address information */
9855 static mblk_t *
9856 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9857 {
9858 	struct opthdr		*optp;
9859 	mblk_t			*mp2ctl;
9860 	mblk_t			*mp_tail = NULL;
9861 	ill_t			*ill;
9862 	ipif_t			*ipif;
9863 	uint_t			bitval;
9864 	mib2_ipAddrEntry_t	mae;
9865 	zoneid_t		zoneid;
9866 	ill_walk_context_t ctx;
9867 
9868 	/*
9869 	 * make a copy of the original message
9870 	 */
9871 	mp2ctl = copymsg(mpctl);
9872 
9873 	/* ipAddrEntryTable */
9874 
9875 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9876 	optp->level = MIB2_IP;
9877 	optp->name = MIB2_IP_ADDR;
9878 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9879 
9880 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9881 	ill = ILL_START_WALK_V4(&ctx, ipst);
9882 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9883 		for (ipif = ill->ill_ipif; ipif != NULL;
9884 		    ipif = ipif->ipif_next) {
9885 			if (ipif->ipif_zoneid != zoneid &&
9886 			    ipif->ipif_zoneid != ALL_ZONES)
9887 				continue;
9888 			/* Sum of count from dead IRE_LO* and our current */
9889 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9890 			if (ipif->ipif_ire_local != NULL) {
9891 				mae.ipAdEntInfo.ae_ibcnt +=
9892 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9893 			}
9894 			mae.ipAdEntInfo.ae_obcnt = 0;
9895 			mae.ipAdEntInfo.ae_focnt = 0;
9896 
9897 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
9898 			    OCTET_LENGTH);
9899 			mae.ipAdEntIfIndex.o_length =
9900 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
9901 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
9902 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
9903 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
9904 			mae.ipAdEntInfo.ae_subnet_len =
9905 			    ip_mask_to_plen(ipif->ipif_net_mask);
9906 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
9907 			for (bitval = 1;
9908 			    bitval &&
9909 			    !(bitval & ipif->ipif_brd_addr);
9910 			    bitval <<= 1)
9911 				noop;
9912 			mae.ipAdEntBcastAddr = bitval;
9913 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
9914 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
9915 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
9916 			mae.ipAdEntInfo.ae_broadcast_addr =
9917 			    ipif->ipif_brd_addr;
9918 			mae.ipAdEntInfo.ae_pp_dst_addr =
9919 			    ipif->ipif_pp_dst_addr;
9920 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
9921 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
9922 			mae.ipAdEntRetransmitTime =
9923 			    ill->ill_reachable_retrans_time;
9924 
9925 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9926 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
9927 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
9928 				    "allocate %u bytes\n",
9929 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
9930 			}
9931 		}
9932 	}
9933 	rw_exit(&ipst->ips_ill_g_lock);
9934 
9935 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9936 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
9937 	    (int)optp->level, (int)optp->name, (int)optp->len));
9938 	qreply(q, mpctl);
9939 	return (mp2ctl);
9940 }
9941 
9942 /* IPv6 address information */
9943 static mblk_t *
9944 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9945 {
9946 	struct opthdr		*optp;
9947 	mblk_t			*mp2ctl;
9948 	mblk_t			*mp_tail = NULL;
9949 	ill_t			*ill;
9950 	ipif_t			*ipif;
9951 	mib2_ipv6AddrEntry_t	mae6;
9952 	zoneid_t		zoneid;
9953 	ill_walk_context_t	ctx;
9954 
9955 	/*
9956 	 * make a copy of the original message
9957 	 */
9958 	mp2ctl = copymsg(mpctl);
9959 
9960 	/* ipv6AddrEntryTable */
9961 
9962 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9963 	optp->level = MIB2_IP6;
9964 	optp->name = MIB2_IP6_ADDR;
9965 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9966 
9967 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9968 	ill = ILL_START_WALK_V6(&ctx, ipst);
9969 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9970 		for (ipif = ill->ill_ipif; ipif != NULL;
9971 		    ipif = ipif->ipif_next) {
9972 			if (ipif->ipif_zoneid != zoneid &&
9973 			    ipif->ipif_zoneid != ALL_ZONES)
9974 				continue;
9975 			/* Sum of count from dead IRE_LO* and our current */
9976 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9977 			if (ipif->ipif_ire_local != NULL) {
9978 				mae6.ipv6AddrInfo.ae_ibcnt +=
9979 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9980 			}
9981 			mae6.ipv6AddrInfo.ae_obcnt = 0;
9982 			mae6.ipv6AddrInfo.ae_focnt = 0;
9983 
9984 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
9985 			    OCTET_LENGTH);
9986 			mae6.ipv6AddrIfIndex.o_length =
9987 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
9988 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
9989 			mae6.ipv6AddrPfxLength =
9990 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
9991 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
9992 			mae6.ipv6AddrInfo.ae_subnet_len =
9993 			    mae6.ipv6AddrPfxLength;
9994 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
9995 
9996 			/* Type: stateless(1), stateful(2), unknown(3) */
9997 			if (ipif->ipif_flags & IPIF_ADDRCONF)
9998 				mae6.ipv6AddrType = 1;
9999 			else
10000 				mae6.ipv6AddrType = 2;
10001 			/* Anycast: true(1), false(2) */
10002 			if (ipif->ipif_flags & IPIF_ANYCAST)
10003 				mae6.ipv6AddrAnycastFlag = 1;
10004 			else
10005 				mae6.ipv6AddrAnycastFlag = 2;
10006 
10007 			/*
10008 			 * Address status: preferred(1), deprecated(2),
10009 			 * invalid(3), inaccessible(4), unknown(5)
10010 			 */
10011 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10012 				mae6.ipv6AddrStatus = 3;
10013 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10014 				mae6.ipv6AddrStatus = 2;
10015 			else
10016 				mae6.ipv6AddrStatus = 1;
10017 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10018 			mae6.ipv6AddrInfo.ae_metric  =
10019 			    ipif->ipif_ill->ill_metric;
10020 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10021 			    ipif->ipif_v6pp_dst_addr;
10022 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10023 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10024 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10025 			mae6.ipv6AddrIdentifier = ill->ill_token;
10026 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10027 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10028 			mae6.ipv6AddrRetransmitTime =
10029 			    ill->ill_reachable_retrans_time;
10030 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10031 			    (char *)&mae6,
10032 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
10033 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10034 				    "allocate %u bytes\n",
10035 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
10036 			}
10037 		}
10038 	}
10039 	rw_exit(&ipst->ips_ill_g_lock);
10040 
10041 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10042 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10043 	    (int)optp->level, (int)optp->name, (int)optp->len));
10044 	qreply(q, mpctl);
10045 	return (mp2ctl);
10046 }
10047 
10048 /* IPv4 multicast group membership. */
10049 static mblk_t *
10050 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10051 {
10052 	struct opthdr		*optp;
10053 	mblk_t			*mp2ctl;
10054 	ill_t			*ill;
10055 	ipif_t			*ipif;
10056 	ilm_t			*ilm;
10057 	ip_member_t		ipm;
10058 	mblk_t			*mp_tail = NULL;
10059 	ill_walk_context_t	ctx;
10060 	zoneid_t		zoneid;
10061 
10062 	/*
10063 	 * make a copy of the original message
10064 	 */
10065 	mp2ctl = copymsg(mpctl);
10066 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10067 
10068 	/* ipGroupMember table */
10069 	optp = (struct opthdr *)&mpctl->b_rptr[
10070 	    sizeof (struct T_optmgmt_ack)];
10071 	optp->level = MIB2_IP;
10072 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10073 
10074 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10075 	ill = ILL_START_WALK_V4(&ctx, ipst);
10076 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10077 		/* Make sure the ill isn't going away. */
10078 		if (!ill_check_and_refhold(ill))
10079 			continue;
10080 		rw_exit(&ipst->ips_ill_g_lock);
10081 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10082 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10083 			if (ilm->ilm_zoneid != zoneid &&
10084 			    ilm->ilm_zoneid != ALL_ZONES)
10085 				continue;
10086 
10087 			/* Is there an ipif for ilm_ifaddr? */
10088 			for (ipif = ill->ill_ipif; ipif != NULL;
10089 			    ipif = ipif->ipif_next) {
10090 				if (!IPIF_IS_CONDEMNED(ipif) &&
10091 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10092 				    ilm->ilm_ifaddr != INADDR_ANY)
10093 					break;
10094 			}
10095 			if (ipif != NULL) {
10096 				ipif_get_name(ipif,
10097 				    ipm.ipGroupMemberIfIndex.o_bytes,
10098 				    OCTET_LENGTH);
10099 			} else {
10100 				ill_get_name(ill,
10101 				    ipm.ipGroupMemberIfIndex.o_bytes,
10102 				    OCTET_LENGTH);
10103 			}
10104 			ipm.ipGroupMemberIfIndex.o_length =
10105 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10106 
10107 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10108 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10109 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10110 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10111 			    (char *)&ipm, (int)sizeof (ipm))) {
10112 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10113 				    "failed to allocate %u bytes\n",
10114 				    (uint_t)sizeof (ipm)));
10115 			}
10116 		}
10117 		rw_exit(&ill->ill_mcast_lock);
10118 		ill_refrele(ill);
10119 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10120 	}
10121 	rw_exit(&ipst->ips_ill_g_lock);
10122 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10123 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10124 	    (int)optp->level, (int)optp->name, (int)optp->len));
10125 	qreply(q, mpctl);
10126 	return (mp2ctl);
10127 }
10128 
10129 /* IPv6 multicast group membership. */
10130 static mblk_t *
10131 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10132 {
10133 	struct opthdr		*optp;
10134 	mblk_t			*mp2ctl;
10135 	ill_t			*ill;
10136 	ilm_t			*ilm;
10137 	ipv6_member_t		ipm6;
10138 	mblk_t			*mp_tail = NULL;
10139 	ill_walk_context_t	ctx;
10140 	zoneid_t		zoneid;
10141 
10142 	/*
10143 	 * make a copy of the original message
10144 	 */
10145 	mp2ctl = copymsg(mpctl);
10146 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10147 
10148 	/* ip6GroupMember table */
10149 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10150 	optp->level = MIB2_IP6;
10151 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10152 
10153 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10154 	ill = ILL_START_WALK_V6(&ctx, ipst);
10155 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10156 		/* Make sure the ill isn't going away. */
10157 		if (!ill_check_and_refhold(ill))
10158 			continue;
10159 		rw_exit(&ipst->ips_ill_g_lock);
10160 		/*
10161 		 * Normally we don't have any members on under IPMP interfaces.
10162 		 * We report them as a debugging aid.
10163 		 */
10164 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10165 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10166 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10167 			if (ilm->ilm_zoneid != zoneid &&
10168 			    ilm->ilm_zoneid != ALL_ZONES)
10169 				continue;	/* not this zone */
10170 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10171 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10172 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10173 			if (!snmp_append_data2(mpctl->b_cont,
10174 			    &mp_tail,
10175 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10176 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10177 				    "failed to allocate %u bytes\n",
10178 				    (uint_t)sizeof (ipm6)));
10179 			}
10180 		}
10181 		rw_exit(&ill->ill_mcast_lock);
10182 		ill_refrele(ill);
10183 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10184 	}
10185 	rw_exit(&ipst->ips_ill_g_lock);
10186 
10187 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10188 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10189 	    (int)optp->level, (int)optp->name, (int)optp->len));
10190 	qreply(q, mpctl);
10191 	return (mp2ctl);
10192 }
10193 
10194 /* IP multicast filtered sources */
10195 static mblk_t *
10196 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10197 {
10198 	struct opthdr		*optp;
10199 	mblk_t			*mp2ctl;
10200 	ill_t			*ill;
10201 	ipif_t			*ipif;
10202 	ilm_t			*ilm;
10203 	ip_grpsrc_t		ips;
10204 	mblk_t			*mp_tail = NULL;
10205 	ill_walk_context_t	ctx;
10206 	zoneid_t		zoneid;
10207 	int			i;
10208 	slist_t			*sl;
10209 
10210 	/*
10211 	 * make a copy of the original message
10212 	 */
10213 	mp2ctl = copymsg(mpctl);
10214 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10215 
10216 	/* ipGroupSource table */
10217 	optp = (struct opthdr *)&mpctl->b_rptr[
10218 	    sizeof (struct T_optmgmt_ack)];
10219 	optp->level = MIB2_IP;
10220 	optp->name = EXPER_IP_GROUP_SOURCES;
10221 
10222 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10223 	ill = ILL_START_WALK_V4(&ctx, ipst);
10224 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10225 		/* Make sure the ill isn't going away. */
10226 		if (!ill_check_and_refhold(ill))
10227 			continue;
10228 		rw_exit(&ipst->ips_ill_g_lock);
10229 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10230 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10231 			sl = ilm->ilm_filter;
10232 			if (ilm->ilm_zoneid != zoneid &&
10233 			    ilm->ilm_zoneid != ALL_ZONES)
10234 				continue;
10235 			if (SLIST_IS_EMPTY(sl))
10236 				continue;
10237 
10238 			/* Is there an ipif for ilm_ifaddr? */
10239 			for (ipif = ill->ill_ipif; ipif != NULL;
10240 			    ipif = ipif->ipif_next) {
10241 				if (!IPIF_IS_CONDEMNED(ipif) &&
10242 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10243 				    ilm->ilm_ifaddr != INADDR_ANY)
10244 					break;
10245 			}
10246 			if (ipif != NULL) {
10247 				ipif_get_name(ipif,
10248 				    ips.ipGroupSourceIfIndex.o_bytes,
10249 				    OCTET_LENGTH);
10250 			} else {
10251 				ill_get_name(ill,
10252 				    ips.ipGroupSourceIfIndex.o_bytes,
10253 				    OCTET_LENGTH);
10254 			}
10255 			ips.ipGroupSourceIfIndex.o_length =
10256 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10257 
10258 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10259 			for (i = 0; i < sl->sl_numsrc; i++) {
10260 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10261 					continue;
10262 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10263 				    ips.ipGroupSourceAddress);
10264 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10265 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10266 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10267 					    " failed to allocate %u bytes\n",
10268 					    (uint_t)sizeof (ips)));
10269 				}
10270 			}
10271 		}
10272 		rw_exit(&ill->ill_mcast_lock);
10273 		ill_refrele(ill);
10274 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10275 	}
10276 	rw_exit(&ipst->ips_ill_g_lock);
10277 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10278 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10279 	    (int)optp->level, (int)optp->name, (int)optp->len));
10280 	qreply(q, mpctl);
10281 	return (mp2ctl);
10282 }
10283 
10284 /* IPv6 multicast filtered sources. */
10285 static mblk_t *
10286 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10287 {
10288 	struct opthdr		*optp;
10289 	mblk_t			*mp2ctl;
10290 	ill_t			*ill;
10291 	ilm_t			*ilm;
10292 	ipv6_grpsrc_t		ips6;
10293 	mblk_t			*mp_tail = NULL;
10294 	ill_walk_context_t	ctx;
10295 	zoneid_t		zoneid;
10296 	int			i;
10297 	slist_t			*sl;
10298 
10299 	/*
10300 	 * make a copy of the original message
10301 	 */
10302 	mp2ctl = copymsg(mpctl);
10303 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10304 
10305 	/* ip6GroupMember table */
10306 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10307 	optp->level = MIB2_IP6;
10308 	optp->name = EXPER_IP6_GROUP_SOURCES;
10309 
10310 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10311 	ill = ILL_START_WALK_V6(&ctx, ipst);
10312 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10313 		/* Make sure the ill isn't going away. */
10314 		if (!ill_check_and_refhold(ill))
10315 			continue;
10316 		rw_exit(&ipst->ips_ill_g_lock);
10317 		/*
10318 		 * Normally we don't have any members on under IPMP interfaces.
10319 		 * We report them as a debugging aid.
10320 		 */
10321 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10322 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10323 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10324 			sl = ilm->ilm_filter;
10325 			if (ilm->ilm_zoneid != zoneid &&
10326 			    ilm->ilm_zoneid != ALL_ZONES)
10327 				continue;
10328 			if (SLIST_IS_EMPTY(sl))
10329 				continue;
10330 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10331 			for (i = 0; i < sl->sl_numsrc; i++) {
10332 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10333 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10334 				    (char *)&ips6, (int)sizeof (ips6))) {
10335 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10336 					    "group_src: failed to allocate "
10337 					    "%u bytes\n",
10338 					    (uint_t)sizeof (ips6)));
10339 				}
10340 			}
10341 		}
10342 		rw_exit(&ill->ill_mcast_lock);
10343 		ill_refrele(ill);
10344 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10345 	}
10346 	rw_exit(&ipst->ips_ill_g_lock);
10347 
10348 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10349 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10350 	    (int)optp->level, (int)optp->name, (int)optp->len));
10351 	qreply(q, mpctl);
10352 	return (mp2ctl);
10353 }
10354 
10355 /* Multicast routing virtual interface table. */
10356 static mblk_t *
10357 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10358 {
10359 	struct opthdr		*optp;
10360 	mblk_t			*mp2ctl;
10361 
10362 	/*
10363 	 * make a copy of the original message
10364 	 */
10365 	mp2ctl = copymsg(mpctl);
10366 
10367 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10368 	optp->level = EXPER_DVMRP;
10369 	optp->name = EXPER_DVMRP_VIF;
10370 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10371 		ip0dbg(("ip_mroute_vif: failed\n"));
10372 	}
10373 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10374 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10375 	    (int)optp->level, (int)optp->name, (int)optp->len));
10376 	qreply(q, mpctl);
10377 	return (mp2ctl);
10378 }
10379 
10380 /* Multicast routing table. */
10381 static mblk_t *
10382 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10383 {
10384 	struct opthdr		*optp;
10385 	mblk_t			*mp2ctl;
10386 
10387 	/*
10388 	 * make a copy of the original message
10389 	 */
10390 	mp2ctl = copymsg(mpctl);
10391 
10392 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10393 	optp->level = EXPER_DVMRP;
10394 	optp->name = EXPER_DVMRP_MRT;
10395 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10396 		ip0dbg(("ip_mroute_mrt: failed\n"));
10397 	}
10398 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10399 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10400 	    (int)optp->level, (int)optp->name, (int)optp->len));
10401 	qreply(q, mpctl);
10402 	return (mp2ctl);
10403 }
10404 
10405 /*
10406  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10407  * in one IRE walk.
10408  */
10409 static mblk_t *
10410 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10411     ip_stack_t *ipst)
10412 {
10413 	struct opthdr	*optp;
10414 	mblk_t		*mp2ctl;	/* Returned */
10415 	mblk_t		*mp3ctl;	/* nettomedia */
10416 	mblk_t		*mp4ctl;	/* routeattrs */
10417 	iproutedata_t	ird;
10418 	zoneid_t	zoneid;
10419 
10420 	/*
10421 	 * make copies of the original message
10422 	 *	- mp2ctl is returned unchanged to the caller for his use
10423 	 *	- mpctl is sent upstream as ipRouteEntryTable
10424 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10425 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10426 	 */
10427 	mp2ctl = copymsg(mpctl);
10428 	mp3ctl = copymsg(mpctl);
10429 	mp4ctl = copymsg(mpctl);
10430 	if (mp3ctl == NULL || mp4ctl == NULL) {
10431 		freemsg(mp4ctl);
10432 		freemsg(mp3ctl);
10433 		freemsg(mp2ctl);
10434 		freemsg(mpctl);
10435 		return (NULL);
10436 	}
10437 
10438 	bzero(&ird, sizeof (ird));
10439 
10440 	ird.ird_route.lp_head = mpctl->b_cont;
10441 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10442 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10443 	/*
10444 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10445 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10446 	 * intended a temporary solution until a proper MIB API is provided
10447 	 * that provides complete filtering/caller-opt-in.
10448 	 */
10449 	if (level == EXPER_IP_AND_ALL_IRES)
10450 		ird.ird_flags |= IRD_REPORT_ALL;
10451 
10452 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10453 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10454 
10455 	/* ipRouteEntryTable in mpctl */
10456 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10457 	optp->level = MIB2_IP;
10458 	optp->name = MIB2_IP_ROUTE;
10459 	optp->len = msgdsize(ird.ird_route.lp_head);
10460 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10461 	    (int)optp->level, (int)optp->name, (int)optp->len));
10462 	qreply(q, mpctl);
10463 
10464 	/* ipNetToMediaEntryTable in mp3ctl */
10465 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10466 
10467 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10468 	optp->level = MIB2_IP;
10469 	optp->name = MIB2_IP_MEDIA;
10470 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10471 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10472 	    (int)optp->level, (int)optp->name, (int)optp->len));
10473 	qreply(q, mp3ctl);
10474 
10475 	/* ipRouteAttributeTable in mp4ctl */
10476 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10477 	optp->level = MIB2_IP;
10478 	optp->name = EXPER_IP_RTATTR;
10479 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10480 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10481 	    (int)optp->level, (int)optp->name, (int)optp->len));
10482 	if (optp->len == 0)
10483 		freemsg(mp4ctl);
10484 	else
10485 		qreply(q, mp4ctl);
10486 
10487 	return (mp2ctl);
10488 }
10489 
10490 /*
10491  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10492  * ipv6NetToMediaEntryTable in an NDP walk.
10493  */
10494 static mblk_t *
10495 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10496     ip_stack_t *ipst)
10497 {
10498 	struct opthdr	*optp;
10499 	mblk_t		*mp2ctl;	/* Returned */
10500 	mblk_t		*mp3ctl;	/* nettomedia */
10501 	mblk_t		*mp4ctl;	/* routeattrs */
10502 	iproutedata_t	ird;
10503 	zoneid_t	zoneid;
10504 
10505 	/*
10506 	 * make copies of the original message
10507 	 *	- mp2ctl is returned unchanged to the caller for his use
10508 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10509 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10510 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10511 	 */
10512 	mp2ctl = copymsg(mpctl);
10513 	mp3ctl = copymsg(mpctl);
10514 	mp4ctl = copymsg(mpctl);
10515 	if (mp3ctl == NULL || mp4ctl == NULL) {
10516 		freemsg(mp4ctl);
10517 		freemsg(mp3ctl);
10518 		freemsg(mp2ctl);
10519 		freemsg(mpctl);
10520 		return (NULL);
10521 	}
10522 
10523 	bzero(&ird, sizeof (ird));
10524 
10525 	ird.ird_route.lp_head = mpctl->b_cont;
10526 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10527 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10528 	/*
10529 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10530 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10531 	 * intended a temporary solution until a proper MIB API is provided
10532 	 * that provides complete filtering/caller-opt-in.
10533 	 */
10534 	if (level == EXPER_IP_AND_ALL_IRES)
10535 		ird.ird_flags |= IRD_REPORT_ALL;
10536 
10537 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10538 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10539 
10540 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10541 	optp->level = MIB2_IP6;
10542 	optp->name = MIB2_IP6_ROUTE;
10543 	optp->len = msgdsize(ird.ird_route.lp_head);
10544 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10545 	    (int)optp->level, (int)optp->name, (int)optp->len));
10546 	qreply(q, mpctl);
10547 
10548 	/* ipv6NetToMediaEntryTable in mp3ctl */
10549 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10550 
10551 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10552 	optp->level = MIB2_IP6;
10553 	optp->name = MIB2_IP6_MEDIA;
10554 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10555 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10556 	    (int)optp->level, (int)optp->name, (int)optp->len));
10557 	qreply(q, mp3ctl);
10558 
10559 	/* ipv6RouteAttributeTable in mp4ctl */
10560 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10561 	optp->level = MIB2_IP6;
10562 	optp->name = EXPER_IP_RTATTR;
10563 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10564 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10565 	    (int)optp->level, (int)optp->name, (int)optp->len));
10566 	if (optp->len == 0)
10567 		freemsg(mp4ctl);
10568 	else
10569 		qreply(q, mp4ctl);
10570 
10571 	return (mp2ctl);
10572 }
10573 
10574 /*
10575  * IPv6 mib: One per ill
10576  */
10577 static mblk_t *
10578 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10579 {
10580 	struct opthdr		*optp;
10581 	mblk_t			*mp2ctl;
10582 	ill_t			*ill;
10583 	ill_walk_context_t	ctx;
10584 	mblk_t			*mp_tail = NULL;
10585 
10586 	/*
10587 	 * Make a copy of the original message
10588 	 */
10589 	mp2ctl = copymsg(mpctl);
10590 
10591 	/* fixed length IPv6 structure ... */
10592 
10593 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10594 	optp->level = MIB2_IP6;
10595 	optp->name = 0;
10596 	/* Include "unknown interface" ip6_mib */
10597 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10598 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10599 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10600 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10601 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10602 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10603 	    ipst->ips_ipv6_def_hops);
10604 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10605 	    sizeof (mib2_ipIfStatsEntry_t));
10606 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10607 	    sizeof (mib2_ipv6AddrEntry_t));
10608 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10609 	    sizeof (mib2_ipv6RouteEntry_t));
10610 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10611 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10612 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10613 	    sizeof (ipv6_member_t));
10614 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10615 	    sizeof (ipv6_grpsrc_t));
10616 
10617 	/*
10618 	 * Synchronize 64- and 32-bit counters
10619 	 */
10620 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10621 	    ipIfStatsHCInReceives);
10622 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10623 	    ipIfStatsHCInDelivers);
10624 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10625 	    ipIfStatsHCOutRequests);
10626 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10627 	    ipIfStatsHCOutForwDatagrams);
10628 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10629 	    ipIfStatsHCOutMcastPkts);
10630 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10631 	    ipIfStatsHCInMcastPkts);
10632 
10633 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10634 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
10635 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10636 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
10637 	}
10638 
10639 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10640 	ill = ILL_START_WALK_V6(&ctx, ipst);
10641 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10642 		ill->ill_ip_mib->ipIfStatsIfIndex =
10643 		    ill->ill_phyint->phyint_ifindex;
10644 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10645 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10646 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10647 		    ill->ill_max_hops);
10648 
10649 		/*
10650 		 * Synchronize 64- and 32-bit counters
10651 		 */
10652 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10653 		    ipIfStatsHCInReceives);
10654 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10655 		    ipIfStatsHCInDelivers);
10656 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10657 		    ipIfStatsHCOutRequests);
10658 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10659 		    ipIfStatsHCOutForwDatagrams);
10660 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10661 		    ipIfStatsHCOutMcastPkts);
10662 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10663 		    ipIfStatsHCInMcastPkts);
10664 
10665 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10666 		    (char *)ill->ill_ip_mib,
10667 		    (int)sizeof (*ill->ill_ip_mib))) {
10668 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10669 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
10670 		}
10671 	}
10672 	rw_exit(&ipst->ips_ill_g_lock);
10673 
10674 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10675 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10676 	    (int)optp->level, (int)optp->name, (int)optp->len));
10677 	qreply(q, mpctl);
10678 	return (mp2ctl);
10679 }
10680 
10681 /*
10682  * ICMPv6 mib: One per ill
10683  */
10684 static mblk_t *
10685 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10686 {
10687 	struct opthdr		*optp;
10688 	mblk_t			*mp2ctl;
10689 	ill_t			*ill;
10690 	ill_walk_context_t	ctx;
10691 	mblk_t			*mp_tail = NULL;
10692 	/*
10693 	 * Make a copy of the original message
10694 	 */
10695 	mp2ctl = copymsg(mpctl);
10696 
10697 	/* fixed length ICMPv6 structure ... */
10698 
10699 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10700 	optp->level = MIB2_ICMP6;
10701 	optp->name = 0;
10702 	/* Include "unknown interface" icmp6_mib */
10703 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10704 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10705 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10706 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10707 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10708 	    (char *)&ipst->ips_icmp6_mib,
10709 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10710 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10711 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10712 	}
10713 
10714 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10715 	ill = ILL_START_WALK_V6(&ctx, ipst);
10716 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10717 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10718 		    ill->ill_phyint->phyint_ifindex;
10719 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10720 		    (char *)ill->ill_icmp6_mib,
10721 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10722 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10723 			    "%u bytes\n",
10724 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10725 		}
10726 	}
10727 	rw_exit(&ipst->ips_ill_g_lock);
10728 
10729 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10730 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10731 	    (int)optp->level, (int)optp->name, (int)optp->len));
10732 	qreply(q, mpctl);
10733 	return (mp2ctl);
10734 }
10735 
10736 /*
10737  * ire_walk routine to create both ipRouteEntryTable and
10738  * ipRouteAttributeTable in one IRE walk
10739  */
10740 static void
10741 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10742 {
10743 	ill_t				*ill;
10744 	mib2_ipRouteEntry_t		*re;
10745 	mib2_ipAttributeEntry_t		iaes;
10746 	tsol_ire_gw_secattr_t		*attrp;
10747 	tsol_gc_t			*gc = NULL;
10748 	tsol_gcgrp_t			*gcgrp = NULL;
10749 	ip_stack_t			*ipst = ire->ire_ipst;
10750 
10751 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10752 
10753 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10754 		if (ire->ire_testhidden)
10755 			return;
10756 		if (ire->ire_type & IRE_IF_CLONE)
10757 			return;
10758 	}
10759 
10760 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10761 		return;
10762 
10763 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10764 		mutex_enter(&attrp->igsa_lock);
10765 		if ((gc = attrp->igsa_gc) != NULL) {
10766 			gcgrp = gc->gc_grp;
10767 			ASSERT(gcgrp != NULL);
10768 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10769 		}
10770 		mutex_exit(&attrp->igsa_lock);
10771 	}
10772 	/*
10773 	 * Return all IRE types for route table... let caller pick and choose
10774 	 */
10775 	re->ipRouteDest = ire->ire_addr;
10776 	ill = ire->ire_ill;
10777 	re->ipRouteIfIndex.o_length = 0;
10778 	if (ill != NULL) {
10779 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10780 		re->ipRouteIfIndex.o_length =
10781 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10782 	}
10783 	re->ipRouteMetric1 = -1;
10784 	re->ipRouteMetric2 = -1;
10785 	re->ipRouteMetric3 = -1;
10786 	re->ipRouteMetric4 = -1;
10787 
10788 	re->ipRouteNextHop = ire->ire_gateway_addr;
10789 	/* indirect(4), direct(3), or invalid(2) */
10790 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10791 		re->ipRouteType = 2;
10792 	else if (ire->ire_type & IRE_ONLINK)
10793 		re->ipRouteType = 3;
10794 	else
10795 		re->ipRouteType = 4;
10796 
10797 	re->ipRouteProto = -1;
10798 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10799 	re->ipRouteMask = ire->ire_mask;
10800 	re->ipRouteMetric5 = -1;
10801 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10802 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10803 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10804 
10805 	re->ipRouteInfo.re_frag_flag	= 0;
10806 	re->ipRouteInfo.re_rtt		= 0;
10807 	re->ipRouteInfo.re_src_addr	= 0;
10808 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
10809 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10810 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10811 	re->ipRouteInfo.re_flags	= ire->ire_flags;
10812 
10813 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10814 	if (ire->ire_type & IRE_INTERFACE) {
10815 		ire_t *child;
10816 
10817 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10818 		child = ire->ire_dep_children;
10819 		while (child != NULL) {
10820 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10821 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10822 			child = child->ire_dep_sib_next;
10823 		}
10824 		rw_exit(&ipst->ips_ire_dep_lock);
10825 	}
10826 
10827 	if (ire->ire_flags & RTF_DYNAMIC) {
10828 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10829 	} else {
10830 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
10831 	}
10832 
10833 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10834 	    (char *)re, (int)sizeof (*re))) {
10835 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
10836 		    (uint_t)sizeof (*re)));
10837 	}
10838 
10839 	if (gc != NULL) {
10840 		iaes.iae_routeidx = ird->ird_idx;
10841 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10842 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10843 
10844 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10845 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10846 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
10847 			    "bytes\n", (uint_t)sizeof (iaes)));
10848 		}
10849 	}
10850 
10851 	/* bump route index for next pass */
10852 	ird->ird_idx++;
10853 
10854 	kmem_free(re, sizeof (*re));
10855 	if (gcgrp != NULL)
10856 		rw_exit(&gcgrp->gcgrp_rwlock);
10857 }
10858 
10859 /*
10860  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
10861  */
10862 static void
10863 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
10864 {
10865 	ill_t				*ill;
10866 	mib2_ipv6RouteEntry_t		*re;
10867 	mib2_ipAttributeEntry_t		iaes;
10868 	tsol_ire_gw_secattr_t		*attrp;
10869 	tsol_gc_t			*gc = NULL;
10870 	tsol_gcgrp_t			*gcgrp = NULL;
10871 	ip_stack_t			*ipst = ire->ire_ipst;
10872 
10873 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
10874 
10875 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10876 		if (ire->ire_testhidden)
10877 			return;
10878 		if (ire->ire_type & IRE_IF_CLONE)
10879 			return;
10880 	}
10881 
10882 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10883 		return;
10884 
10885 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10886 		mutex_enter(&attrp->igsa_lock);
10887 		if ((gc = attrp->igsa_gc) != NULL) {
10888 			gcgrp = gc->gc_grp;
10889 			ASSERT(gcgrp != NULL);
10890 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10891 		}
10892 		mutex_exit(&attrp->igsa_lock);
10893 	}
10894 	/*
10895 	 * Return all IRE types for route table... let caller pick and choose
10896 	 */
10897 	re->ipv6RouteDest = ire->ire_addr_v6;
10898 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
10899 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
10900 	re->ipv6RouteIfIndex.o_length = 0;
10901 	ill = ire->ire_ill;
10902 	if (ill != NULL) {
10903 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
10904 		re->ipv6RouteIfIndex.o_length =
10905 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
10906 	}
10907 
10908 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
10909 
10910 	mutex_enter(&ire->ire_lock);
10911 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
10912 	mutex_exit(&ire->ire_lock);
10913 
10914 	/* remote(4), local(3), or discard(2) */
10915 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10916 		re->ipv6RouteType = 2;
10917 	else if (ire->ire_type & IRE_ONLINK)
10918 		re->ipv6RouteType = 3;
10919 	else
10920 		re->ipv6RouteType = 4;
10921 
10922 	re->ipv6RouteProtocol	= -1;
10923 	re->ipv6RoutePolicy	= 0;
10924 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
10925 	re->ipv6RouteNextHopRDI	= 0;
10926 	re->ipv6RouteWeight	= 0;
10927 	re->ipv6RouteMetric	= 0;
10928 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10929 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
10930 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10931 
10932 	re->ipv6RouteInfo.re_frag_flag	= 0;
10933 	re->ipv6RouteInfo.re_rtt	= 0;
10934 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
10935 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10936 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10937 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
10938 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
10939 
10940 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10941 	if (ire->ire_type & IRE_INTERFACE) {
10942 		ire_t *child;
10943 
10944 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10945 		child = ire->ire_dep_children;
10946 		while (child != NULL) {
10947 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
10948 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10949 			child = child->ire_dep_sib_next;
10950 		}
10951 		rw_exit(&ipst->ips_ire_dep_lock);
10952 	}
10953 	if (ire->ire_flags & RTF_DYNAMIC) {
10954 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10955 	} else {
10956 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
10957 	}
10958 
10959 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10960 	    (char *)re, (int)sizeof (*re))) {
10961 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
10962 		    (uint_t)sizeof (*re)));
10963 	}
10964 
10965 	if (gc != NULL) {
10966 		iaes.iae_routeidx = ird->ird_idx;
10967 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10968 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10969 
10970 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10971 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10972 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
10973 			    "bytes\n", (uint_t)sizeof (iaes)));
10974 		}
10975 	}
10976 
10977 	/* bump route index for next pass */
10978 	ird->ird_idx++;
10979 
10980 	kmem_free(re, sizeof (*re));
10981 	if (gcgrp != NULL)
10982 		rw_exit(&gcgrp->gcgrp_rwlock);
10983 }
10984 
10985 /*
10986  * ncec_walk routine to create ipv6NetToMediaEntryTable
10987  */
10988 static int
10989 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
10990 {
10991 	ill_t				*ill;
10992 	mib2_ipv6NetToMediaEntry_t	ntme;
10993 
10994 	ill = ncec->ncec_ill;
10995 	/* skip arpce entries, and loopback ncec entries */
10996 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
10997 		return (0);
10998 	/*
10999 	 * Neighbor cache entry attached to IRE with on-link
11000 	 * destination.
11001 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11002 	 */
11003 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11004 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11005 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11006 	if (ncec->ncec_lladdr != NULL) {
11007 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11008 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11009 	}
11010 	/*
11011 	 * Note: Returns ND_* states. Should be:
11012 	 * reachable(1), stale(2), delay(3), probe(4),
11013 	 * invalid(5), unknown(6)
11014 	 */
11015 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11016 	ntme.ipv6NetToMediaLastUpdated = 0;
11017 
11018 	/* other(1), dynamic(2), static(3), local(4) */
11019 	if (NCE_MYADDR(ncec)) {
11020 		ntme.ipv6NetToMediaType = 4;
11021 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11022 		ntme.ipv6NetToMediaType = 1; /* proxy */
11023 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11024 		ntme.ipv6NetToMediaType = 3;
11025 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11026 		ntme.ipv6NetToMediaType = 1;
11027 	} else {
11028 		ntme.ipv6NetToMediaType = 2;
11029 	}
11030 
11031 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11032 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11033 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11034 		    (uint_t)sizeof (ntme)));
11035 	}
11036 	return (0);
11037 }
11038 
11039 int
11040 nce2ace(ncec_t *ncec)
11041 {
11042 	int flags = 0;
11043 
11044 	if (NCE_ISREACHABLE(ncec))
11045 		flags |= ACE_F_RESOLVED;
11046 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11047 		flags |= ACE_F_AUTHORITY;
11048 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11049 		flags |= ACE_F_PUBLISH;
11050 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11051 		flags |= ACE_F_PERMANENT;
11052 	if (NCE_MYADDR(ncec))
11053 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11054 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11055 		flags |= ACE_F_UNVERIFIED;
11056 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11057 		flags |= ACE_F_AUTHORITY;
11058 	if (ncec->ncec_flags & NCE_F_DELAYED)
11059 		flags |= ACE_F_DELAYED;
11060 	return (flags);
11061 }
11062 
11063 /*
11064  * ncec_walk routine to create ipNetToMediaEntryTable
11065  */
11066 static int
11067 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11068 {
11069 	ill_t				*ill;
11070 	mib2_ipNetToMediaEntry_t	ntme;
11071 	const char			*name = "unknown";
11072 	ipaddr_t			ncec_addr;
11073 
11074 	ill = ncec->ncec_ill;
11075 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11076 	    ill->ill_net_type == IRE_LOOPBACK)
11077 		return (0);
11078 
11079 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11080 	name = ill->ill_name;
11081 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11082 	if (NCE_MYADDR(ncec)) {
11083 		ntme.ipNetToMediaType = 4;
11084 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11085 		ntme.ipNetToMediaType = 1;
11086 	} else {
11087 		ntme.ipNetToMediaType = 3;
11088 	}
11089 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11090 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11091 	    ntme.ipNetToMediaIfIndex.o_length);
11092 
11093 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11094 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11095 
11096 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11097 	ncec_addr = INADDR_BROADCAST;
11098 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11099 	    sizeof (ncec_addr));
11100 	/*
11101 	 * map all the flags to the ACE counterpart.
11102 	 */
11103 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11104 
11105 	ntme.ipNetToMediaPhysAddress.o_length =
11106 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11107 
11108 	if (!NCE_ISREACHABLE(ncec))
11109 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11110 	else {
11111 		if (ncec->ncec_lladdr != NULL) {
11112 			bcopy(ncec->ncec_lladdr,
11113 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11114 			    ntme.ipNetToMediaPhysAddress.o_length);
11115 		}
11116 	}
11117 
11118 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11119 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11120 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11121 		    (uint_t)sizeof (ntme)));
11122 	}
11123 	return (0);
11124 }
11125 
11126 /*
11127  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11128  */
11129 /* ARGSUSED */
11130 int
11131 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11132 {
11133 	switch (level) {
11134 	case MIB2_IP:
11135 	case MIB2_ICMP:
11136 		switch (name) {
11137 		default:
11138 			break;
11139 		}
11140 		return (1);
11141 	default:
11142 		return (1);
11143 	}
11144 }
11145 
11146 /*
11147  * When there exists both a 64- and 32-bit counter of a particular type
11148  * (i.e., InReceives), only the 64-bit counters are added.
11149  */
11150 void
11151 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11152 {
11153 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11154 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11155 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11156 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11157 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11158 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11159 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11160 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11161 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11162 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11163 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11164 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11165 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11166 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11167 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11168 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11169 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11170 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11171 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11172 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11173 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11174 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11175 	    o2->ipIfStatsInWrongIPVersion);
11176 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11177 	    o2->ipIfStatsInWrongIPVersion);
11178 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11179 	    o2->ipIfStatsOutSwitchIPVersion);
11180 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11181 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11182 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11183 	    o2->ipIfStatsHCInForwDatagrams);
11184 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11185 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11186 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11187 	    o2->ipIfStatsHCOutForwDatagrams);
11188 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11189 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11190 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11191 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11192 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11193 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11194 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11195 	    o2->ipIfStatsHCOutMcastOctets);
11196 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11197 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11198 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11199 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11200 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11201 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11202 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11203 }
11204 
11205 void
11206 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11207 {
11208 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11209 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11210 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11211 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11212 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11213 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11214 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11215 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11216 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11217 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11218 	    o2->ipv6IfIcmpInRouterSolicits);
11219 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11220 	    o2->ipv6IfIcmpInRouterAdvertisements);
11221 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11222 	    o2->ipv6IfIcmpInNeighborSolicits);
11223 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11224 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11225 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11226 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11227 	    o2->ipv6IfIcmpInGroupMembQueries);
11228 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11229 	    o2->ipv6IfIcmpInGroupMembResponses);
11230 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11231 	    o2->ipv6IfIcmpInGroupMembReductions);
11232 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11233 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11234 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11235 	    o2->ipv6IfIcmpOutDestUnreachs);
11236 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11237 	    o2->ipv6IfIcmpOutAdminProhibs);
11238 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11239 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11240 	    o2->ipv6IfIcmpOutParmProblems);
11241 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11242 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11243 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11244 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11245 	    o2->ipv6IfIcmpOutRouterSolicits);
11246 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11247 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11248 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11249 	    o2->ipv6IfIcmpOutNeighborSolicits);
11250 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11251 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11252 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11253 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11254 	    o2->ipv6IfIcmpOutGroupMembQueries);
11255 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11256 	    o2->ipv6IfIcmpOutGroupMembResponses);
11257 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11258 	    o2->ipv6IfIcmpOutGroupMembReductions);
11259 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11260 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11261 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11262 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11263 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11264 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11265 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11266 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11267 	    o2->ipv6IfIcmpInGroupMembTotal);
11268 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11269 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11270 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11271 	    o2->ipv6IfIcmpInGroupMembBadReports);
11272 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11273 	    o2->ipv6IfIcmpInGroupMembOurReports);
11274 }
11275 
11276 /*
11277  * Called before the options are updated to check if this packet will
11278  * be source routed from here.
11279  * This routine assumes that the options are well formed i.e. that they
11280  * have already been checked.
11281  */
11282 boolean_t
11283 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11284 {
11285 	ipoptp_t	opts;
11286 	uchar_t		*opt;
11287 	uint8_t		optval;
11288 	uint8_t		optlen;
11289 	ipaddr_t	dst;
11290 
11291 	if (IS_SIMPLE_IPH(ipha)) {
11292 		ip2dbg(("not source routed\n"));
11293 		return (B_FALSE);
11294 	}
11295 	dst = ipha->ipha_dst;
11296 	for (optval = ipoptp_first(&opts, ipha);
11297 	    optval != IPOPT_EOL;
11298 	    optval = ipoptp_next(&opts)) {
11299 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11300 		opt = opts.ipoptp_cur;
11301 		optlen = opts.ipoptp_len;
11302 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11303 		    optval, optlen));
11304 		switch (optval) {
11305 			uint32_t off;
11306 		case IPOPT_SSRR:
11307 		case IPOPT_LSRR:
11308 			/*
11309 			 * If dst is one of our addresses and there are some
11310 			 * entries left in the source route return (true).
11311 			 */
11312 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11313 				ip2dbg(("ip_source_routed: not next"
11314 				    " source route 0x%x\n",
11315 				    ntohl(dst)));
11316 				return (B_FALSE);
11317 			}
11318 			off = opt[IPOPT_OFFSET];
11319 			off--;
11320 			if (optlen < IP_ADDR_LEN ||
11321 			    off > optlen - IP_ADDR_LEN) {
11322 				/* End of source route */
11323 				ip1dbg(("ip_source_routed: end of SR\n"));
11324 				return (B_FALSE);
11325 			}
11326 			return (B_TRUE);
11327 		}
11328 	}
11329 	ip2dbg(("not source routed\n"));
11330 	return (B_FALSE);
11331 }
11332 
11333 /*
11334  * ip_unbind is called by the transports to remove a conn from
11335  * the fanout table.
11336  */
11337 void
11338 ip_unbind(conn_t *connp)
11339 {
11340 
11341 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11342 
11343 	if (is_system_labeled() && connp->conn_anon_port) {
11344 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11345 		    connp->conn_mlp_type, connp->conn_proto,
11346 		    ntohs(connp->conn_lport), B_FALSE);
11347 		connp->conn_anon_port = 0;
11348 	}
11349 	connp->conn_mlp_type = mlptSingle;
11350 
11351 	ipcl_hash_remove(connp);
11352 }
11353 
11354 /*
11355  * Used for deciding the MSS size for the upper layer. Thus
11356  * we need to check the outbound policy values in the conn.
11357  */
11358 int
11359 conn_ipsec_length(conn_t *connp)
11360 {
11361 	ipsec_latch_t *ipl;
11362 
11363 	ipl = connp->conn_latch;
11364 	if (ipl == NULL)
11365 		return (0);
11366 
11367 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11368 		return (0);
11369 
11370 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11371 }
11372 
11373 /*
11374  * Returns an estimate of the IPsec headers size. This is used if
11375  * we don't want to call into IPsec to get the exact size.
11376  */
11377 int
11378 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11379 {
11380 	ipsec_action_t *a;
11381 
11382 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11383 		return (0);
11384 
11385 	a = ixa->ixa_ipsec_action;
11386 	if (a == NULL) {
11387 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11388 		a = ixa->ixa_ipsec_policy->ipsp_act;
11389 	}
11390 	ASSERT(a != NULL);
11391 
11392 	return (a->ipa_ovhd);
11393 }
11394 
11395 /*
11396  * If there are any source route options, return the true final
11397  * destination. Otherwise, return the destination.
11398  */
11399 ipaddr_t
11400 ip_get_dst(ipha_t *ipha)
11401 {
11402 	ipoptp_t	opts;
11403 	uchar_t		*opt;
11404 	uint8_t		optval;
11405 	uint8_t		optlen;
11406 	ipaddr_t	dst;
11407 	uint32_t off;
11408 
11409 	dst = ipha->ipha_dst;
11410 
11411 	if (IS_SIMPLE_IPH(ipha))
11412 		return (dst);
11413 
11414 	for (optval = ipoptp_first(&opts, ipha);
11415 	    optval != IPOPT_EOL;
11416 	    optval = ipoptp_next(&opts)) {
11417 		opt = opts.ipoptp_cur;
11418 		optlen = opts.ipoptp_len;
11419 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11420 		switch (optval) {
11421 		case IPOPT_SSRR:
11422 		case IPOPT_LSRR:
11423 			off = opt[IPOPT_OFFSET];
11424 			/*
11425 			 * If one of the conditions is true, it means
11426 			 * end of options and dst already has the right
11427 			 * value.
11428 			 */
11429 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11430 				off = optlen - IP_ADDR_LEN;
11431 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11432 			}
11433 			return (dst);
11434 		default:
11435 			break;
11436 		}
11437 	}
11438 
11439 	return (dst);
11440 }
11441 
11442 /*
11443  * Outbound IP fragmentation routine.
11444  * Assumes the caller has checked whether or not fragmentation should
11445  * be allowed. Here we copy the DF bit from the header to all the generated
11446  * fragments.
11447  */
11448 int
11449 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11450     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11451     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11452 {
11453 	int		i1;
11454 	int		hdr_len;
11455 	mblk_t		*hdr_mp;
11456 	ipha_t		*ipha;
11457 	int		ip_data_end;
11458 	int		len;
11459 	mblk_t		*mp = mp_orig;
11460 	int		offset;
11461 	ill_t		*ill = nce->nce_ill;
11462 	ip_stack_t	*ipst = ill->ill_ipst;
11463 	mblk_t		*carve_mp;
11464 	uint32_t	frag_flag;
11465 	uint_t		priority = mp->b_band;
11466 	int		error = 0;
11467 
11468 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11469 
11470 	if (pkt_len != msgdsize(mp)) {
11471 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11472 		    pkt_len, msgdsize(mp)));
11473 		freemsg(mp);
11474 		return (EINVAL);
11475 	}
11476 
11477 	if (max_frag == 0) {
11478 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11479 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11480 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11481 		freemsg(mp);
11482 		return (EINVAL);
11483 	}
11484 
11485 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11486 	ipha = (ipha_t *)mp->b_rptr;
11487 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11488 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11489 
11490 	/*
11491 	 * Establish the starting offset.  May not be zero if we are fragging
11492 	 * a fragment that is being forwarded.
11493 	 */
11494 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11495 
11496 	/* TODO why is this test needed? */
11497 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11498 		/* TODO: notify ulp somehow */
11499 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11500 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11501 		freemsg(mp);
11502 		return (EINVAL);
11503 	}
11504 
11505 	hdr_len = IPH_HDR_LENGTH(ipha);
11506 	ipha->ipha_hdr_checksum = 0;
11507 
11508 	/*
11509 	 * Establish the number of bytes maximum per frag, after putting
11510 	 * in the header.
11511 	 */
11512 	len = (max_frag - hdr_len) & ~7;
11513 
11514 	/* Get a copy of the header for the trailing frags */
11515 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11516 	    mp);
11517 	if (hdr_mp == NULL) {
11518 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11519 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11520 		freemsg(mp);
11521 		return (ENOBUFS);
11522 	}
11523 
11524 	/* Store the starting offset, with the MoreFrags flag. */
11525 	i1 = offset | IPH_MF | frag_flag;
11526 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11527 
11528 	/* Establish the ending byte offset, based on the starting offset. */
11529 	offset <<= 3;
11530 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11531 
11532 	/* Store the length of the first fragment in the IP header. */
11533 	i1 = len + hdr_len;
11534 	ASSERT(i1 <= IP_MAXPACKET);
11535 	ipha->ipha_length = htons((uint16_t)i1);
11536 
11537 	/*
11538 	 * Compute the IP header checksum for the first frag.  We have to
11539 	 * watch out that we stop at the end of the header.
11540 	 */
11541 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11542 
11543 	/*
11544 	 * Now carve off the first frag.  Note that this will include the
11545 	 * original IP header.
11546 	 */
11547 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11548 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11549 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11550 		freeb(hdr_mp);
11551 		freemsg(mp_orig);
11552 		return (ENOBUFS);
11553 	}
11554 
11555 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11556 
11557 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11558 	    ixa_cookie);
11559 	if (error != 0 && error != EWOULDBLOCK) {
11560 		/* No point in sending the other fragments */
11561 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11562 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11563 		freeb(hdr_mp);
11564 		freemsg(mp_orig);
11565 		return (error);
11566 	}
11567 
11568 	/* No need to redo state machine in loop */
11569 	ixaflags &= ~IXAF_REACH_CONF;
11570 
11571 	/* Advance the offset to the second frag starting point. */
11572 	offset += len;
11573 	/*
11574 	 * Update hdr_len from the copied header - there might be less options
11575 	 * in the later fragments.
11576 	 */
11577 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11578 	/* Loop until done. */
11579 	for (;;) {
11580 		uint16_t	offset_and_flags;
11581 		uint16_t	ip_len;
11582 
11583 		if (ip_data_end - offset > len) {
11584 			/*
11585 			 * Carve off the appropriate amount from the original
11586 			 * datagram.
11587 			 */
11588 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11589 				mp = NULL;
11590 				break;
11591 			}
11592 			/*
11593 			 * More frags after this one.  Get another copy
11594 			 * of the header.
11595 			 */
11596 			if (carve_mp->b_datap->db_ref == 1 &&
11597 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11598 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11599 				/* Inline IP header */
11600 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11601 				    hdr_mp->b_rptr;
11602 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11603 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11604 				mp = carve_mp;
11605 			} else {
11606 				if (!(mp = copyb(hdr_mp))) {
11607 					freemsg(carve_mp);
11608 					break;
11609 				}
11610 				/* Get priority marking, if any. */
11611 				mp->b_band = priority;
11612 				mp->b_cont = carve_mp;
11613 			}
11614 			ipha = (ipha_t *)mp->b_rptr;
11615 			offset_and_flags = IPH_MF;
11616 		} else {
11617 			/*
11618 			 * Last frag.  Consume the header. Set len to
11619 			 * the length of this last piece.
11620 			 */
11621 			len = ip_data_end - offset;
11622 
11623 			/*
11624 			 * Carve off the appropriate amount from the original
11625 			 * datagram.
11626 			 */
11627 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11628 				mp = NULL;
11629 				break;
11630 			}
11631 			if (carve_mp->b_datap->db_ref == 1 &&
11632 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11633 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11634 				/* Inline IP header */
11635 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11636 				    hdr_mp->b_rptr;
11637 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11638 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11639 				mp = carve_mp;
11640 				freeb(hdr_mp);
11641 				hdr_mp = mp;
11642 			} else {
11643 				mp = hdr_mp;
11644 				/* Get priority marking, if any. */
11645 				mp->b_band = priority;
11646 				mp->b_cont = carve_mp;
11647 			}
11648 			ipha = (ipha_t *)mp->b_rptr;
11649 			/* A frag of a frag might have IPH_MF non-zero */
11650 			offset_and_flags =
11651 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11652 			    IPH_MF;
11653 		}
11654 		offset_and_flags |= (uint16_t)(offset >> 3);
11655 		offset_and_flags |= (uint16_t)frag_flag;
11656 		/* Store the offset and flags in the IP header. */
11657 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11658 
11659 		/* Store the length in the IP header. */
11660 		ip_len = (uint16_t)(len + hdr_len);
11661 		ipha->ipha_length = htons(ip_len);
11662 
11663 		/*
11664 		 * Set the IP header checksum.	Note that mp is just
11665 		 * the header, so this is easy to pass to ip_csum.
11666 		 */
11667 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11668 
11669 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11670 
11671 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11672 		    nolzid, ixa_cookie);
11673 		/* All done if we just consumed the hdr_mp. */
11674 		if (mp == hdr_mp) {
11675 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11676 			return (error);
11677 		}
11678 		if (error != 0 && error != EWOULDBLOCK) {
11679 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11680 			    mblk_t *, hdr_mp);
11681 			/* No point in sending the other fragments */
11682 			break;
11683 		}
11684 
11685 		/* Otherwise, advance and loop. */
11686 		offset += len;
11687 	}
11688 	/* Clean up following allocation failure. */
11689 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11690 	ip_drop_output("FragFails: loop ended", NULL, ill);
11691 	if (mp != hdr_mp)
11692 		freeb(hdr_mp);
11693 	if (mp != mp_orig)
11694 		freemsg(mp_orig);
11695 	return (error);
11696 }
11697 
11698 /*
11699  * Copy the header plus those options which have the copy bit set
11700  */
11701 static mblk_t *
11702 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11703     mblk_t *src)
11704 {
11705 	mblk_t	*mp;
11706 	uchar_t	*up;
11707 
11708 	/*
11709 	 * Quick check if we need to look for options without the copy bit
11710 	 * set
11711 	 */
11712 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11713 	if (!mp)
11714 		return (mp);
11715 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11716 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11717 		bcopy(rptr, mp->b_rptr, hdr_len);
11718 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11719 		return (mp);
11720 	}
11721 	up  = mp->b_rptr;
11722 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11723 	up += IP_SIMPLE_HDR_LENGTH;
11724 	rptr += IP_SIMPLE_HDR_LENGTH;
11725 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11726 	while (hdr_len > 0) {
11727 		uint32_t optval;
11728 		uint32_t optlen;
11729 
11730 		optval = *rptr;
11731 		if (optval == IPOPT_EOL)
11732 			break;
11733 		if (optval == IPOPT_NOP)
11734 			optlen = 1;
11735 		else
11736 			optlen = rptr[1];
11737 		if (optval & IPOPT_COPY) {
11738 			bcopy(rptr, up, optlen);
11739 			up += optlen;
11740 		}
11741 		rptr += optlen;
11742 		hdr_len -= optlen;
11743 	}
11744 	/*
11745 	 * Make sure that we drop an even number of words by filling
11746 	 * with EOL to the next word boundary.
11747 	 */
11748 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11749 	    hdr_len & 0x3; hdr_len++)
11750 		*up++ = IPOPT_EOL;
11751 	mp->b_wptr = up;
11752 	/* Update header length */
11753 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11754 	return (mp);
11755 }
11756 
11757 /*
11758  * Update any source route, record route, or timestamp options when
11759  * sending a packet back to ourselves.
11760  * Check that we are at end of strict source route.
11761  * The options have been sanity checked by ip_output_options().
11762  */
11763 void
11764 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11765 {
11766 	ipoptp_t	opts;
11767 	uchar_t		*opt;
11768 	uint8_t		optval;
11769 	uint8_t		optlen;
11770 	ipaddr_t	dst;
11771 	uint32_t	ts;
11772 	timestruc_t	now;
11773 
11774 	for (optval = ipoptp_first(&opts, ipha);
11775 	    optval != IPOPT_EOL;
11776 	    optval = ipoptp_next(&opts)) {
11777 		opt = opts.ipoptp_cur;
11778 		optlen = opts.ipoptp_len;
11779 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11780 		switch (optval) {
11781 			uint32_t off;
11782 		case IPOPT_SSRR:
11783 		case IPOPT_LSRR:
11784 			off = opt[IPOPT_OFFSET];
11785 			off--;
11786 			if (optlen < IP_ADDR_LEN ||
11787 			    off > optlen - IP_ADDR_LEN) {
11788 				/* End of source route */
11789 				break;
11790 			}
11791 			/*
11792 			 * This will only happen if two consecutive entries
11793 			 * in the source route contains our address or if
11794 			 * it is a packet with a loose source route which
11795 			 * reaches us before consuming the whole source route
11796 			 */
11797 
11798 			if (optval == IPOPT_SSRR) {
11799 				return;
11800 			}
11801 			/*
11802 			 * Hack: instead of dropping the packet truncate the
11803 			 * source route to what has been used by filling the
11804 			 * rest with IPOPT_NOP.
11805 			 */
11806 			opt[IPOPT_OLEN] = (uint8_t)off;
11807 			while (off < optlen) {
11808 				opt[off++] = IPOPT_NOP;
11809 			}
11810 			break;
11811 		case IPOPT_RR:
11812 			off = opt[IPOPT_OFFSET];
11813 			off--;
11814 			if (optlen < IP_ADDR_LEN ||
11815 			    off > optlen - IP_ADDR_LEN) {
11816 				/* No more room - ignore */
11817 				ip1dbg((
11818 				    "ip_output_local_options: end of RR\n"));
11819 				break;
11820 			}
11821 			dst = htonl(INADDR_LOOPBACK);
11822 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11823 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11824 			break;
11825 		case IPOPT_TS:
11826 			/* Insert timestamp if there is romm */
11827 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11828 			case IPOPT_TS_TSONLY:
11829 				off = IPOPT_TS_TIMELEN;
11830 				break;
11831 			case IPOPT_TS_PRESPEC:
11832 			case IPOPT_TS_PRESPEC_RFC791:
11833 				/* Verify that the address matched */
11834 				off = opt[IPOPT_OFFSET] - 1;
11835 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
11836 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11837 					/* Not for us */
11838 					break;
11839 				}
11840 				/* FALLTHRU */
11841 			case IPOPT_TS_TSANDADDR:
11842 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
11843 				break;
11844 			default:
11845 				/*
11846 				 * ip_*put_options should have already
11847 				 * dropped this packet.
11848 				 */
11849 				cmn_err(CE_PANIC, "ip_output_local_options: "
11850 				    "unknown IT - bug in ip_output_options?\n");
11851 				return;	/* Keep "lint" happy */
11852 			}
11853 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
11854 				/* Increase overflow counter */
11855 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
11856 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
11857 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
11858 				    (off << 4);
11859 				break;
11860 			}
11861 			off = opt[IPOPT_OFFSET] - 1;
11862 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11863 			case IPOPT_TS_PRESPEC:
11864 			case IPOPT_TS_PRESPEC_RFC791:
11865 			case IPOPT_TS_TSANDADDR:
11866 				dst = htonl(INADDR_LOOPBACK);
11867 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11868 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11869 				/* FALLTHRU */
11870 			case IPOPT_TS_TSONLY:
11871 				off = opt[IPOPT_OFFSET] - 1;
11872 				/* Compute # of milliseconds since midnight */
11873 				gethrestime(&now);
11874 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
11875 				    now.tv_nsec / (NANOSEC / MILLISEC);
11876 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
11877 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
11878 				break;
11879 			}
11880 			break;
11881 		}
11882 	}
11883 }
11884 
11885 /*
11886  * Prepend an M_DATA fastpath header, and if none present prepend a
11887  * DL_UNITDATA_REQ. Frees the mblk on failure.
11888  *
11889  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
11890  * If there is a change to them, the nce will be deleted (condemned) and
11891  * a new nce_t will be created when packets are sent. Thus we need no locks
11892  * to access those fields.
11893  *
11894  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
11895  * we place b_band in dl_priority.dl_max.
11896  */
11897 static mblk_t *
11898 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
11899 {
11900 	uint_t	hlen;
11901 	mblk_t *mp1;
11902 	uint_t	priority;
11903 	uchar_t *rptr;
11904 
11905 	rptr = mp->b_rptr;
11906 
11907 	ASSERT(DB_TYPE(mp) == M_DATA);
11908 	priority = mp->b_band;
11909 
11910 	ASSERT(nce != NULL);
11911 	if ((mp1 = nce->nce_fp_mp) != NULL) {
11912 		hlen = MBLKL(mp1);
11913 		/*
11914 		 * Check if we have enough room to prepend fastpath
11915 		 * header
11916 		 */
11917 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
11918 			rptr -= hlen;
11919 			bcopy(mp1->b_rptr, rptr, hlen);
11920 			/*
11921 			 * Set the b_rptr to the start of the link layer
11922 			 * header
11923 			 */
11924 			mp->b_rptr = rptr;
11925 			return (mp);
11926 		}
11927 		mp1 = copyb(mp1);
11928 		if (mp1 == NULL) {
11929 			ill_t *ill = nce->nce_ill;
11930 
11931 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
11932 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
11933 			freemsg(mp);
11934 			return (NULL);
11935 		}
11936 		mp1->b_band = priority;
11937 		mp1->b_cont = mp;
11938 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
11939 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
11940 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
11941 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
11942 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
11943 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
11944 		/*
11945 		 * XXX disable ICK_VALID and compute checksum
11946 		 * here; can happen if nce_fp_mp changes and
11947 		 * it can't be copied now due to insufficient
11948 		 * space. (unlikely, fp mp can change, but it
11949 		 * does not increase in length)
11950 		 */
11951 		return (mp1);
11952 	}
11953 	mp1 = copyb(nce->nce_dlur_mp);
11954 
11955 	if (mp1 == NULL) {
11956 		ill_t *ill = nce->nce_ill;
11957 
11958 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
11959 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
11960 		freemsg(mp);
11961 		return (NULL);
11962 	}
11963 	mp1->b_cont = mp;
11964 	if (priority != 0) {
11965 		mp1->b_band = priority;
11966 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
11967 		    priority;
11968 	}
11969 	return (mp1);
11970 #undef rptr
11971 }
11972 
11973 /*
11974  * Finish the outbound IPsec processing. This function is called from
11975  * ipsec_out_process() if the IPsec packet was processed
11976  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
11977  * asynchronously.
11978  *
11979  * This is common to IPv4 and IPv6.
11980  */
11981 int
11982 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
11983 {
11984 	iaflags_t	ixaflags = ixa->ixa_flags;
11985 	uint_t		pktlen;
11986 
11987 
11988 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
11989 	if (ixaflags & IXAF_IS_IPV4) {
11990 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
11991 
11992 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11993 		pktlen = ntohs(ipha->ipha_length);
11994 	} else {
11995 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
11996 
11997 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
11998 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
11999 	}
12000 
12001 	/*
12002 	 * We release any hard reference on the SAs here to make
12003 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12004 	 * on the SAs.
12005 	 * If in the future we want the hard latching of the SAs in the
12006 	 * ip_xmit_attr_t then we should remove this.
12007 	 */
12008 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12009 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12010 		ixa->ixa_ipsec_esp_sa = NULL;
12011 	}
12012 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12013 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12014 		ixa->ixa_ipsec_ah_sa = NULL;
12015 	}
12016 
12017 	/* Do we need to fragment? */
12018 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12019 	    pktlen > ixa->ixa_fragsize) {
12020 		if (ixaflags & IXAF_IS_IPV4) {
12021 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12022 			/*
12023 			 * We check for the DF case in ipsec_out_process
12024 			 * hence this only handles the non-DF case.
12025 			 */
12026 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12027 			    pktlen, ixa->ixa_fragsize,
12028 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12029 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12030 			    &ixa->ixa_cookie));
12031 		} else {
12032 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12033 			if (mp == NULL) {
12034 				/* MIB and ip_drop_output already done */
12035 				return (ENOMEM);
12036 			}
12037 			pktlen += sizeof (ip6_frag_t);
12038 			if (pktlen > ixa->ixa_fragsize) {
12039 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12040 				    ixa->ixa_flags, pktlen,
12041 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12042 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12043 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12044 			}
12045 		}
12046 	}
12047 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12048 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12049 	    ixa->ixa_no_loop_zoneid, NULL));
12050 }
12051 
12052 /*
12053  * Finish the inbound IPsec processing. This function is called from
12054  * ipsec_out_process() if the IPsec packet was processed
12055  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12056  * asynchronously.
12057  *
12058  * This is common to IPv4 and IPv6.
12059  */
12060 void
12061 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12062 {
12063 	iaflags_t	iraflags = ira->ira_flags;
12064 
12065 	/* Length might have changed */
12066 	if (iraflags & IRAF_IS_IPV4) {
12067 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12068 
12069 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12070 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12071 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12072 		ira->ira_protocol = ipha->ipha_protocol;
12073 
12074 		ip_fanout_v4(mp, ipha, ira);
12075 	} else {
12076 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12077 		uint8_t		*nexthdrp;
12078 
12079 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12080 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12081 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12082 		    &nexthdrp)) {
12083 			/* Malformed packet */
12084 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12085 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12086 			freemsg(mp);
12087 			return;
12088 		}
12089 		ira->ira_protocol = *nexthdrp;
12090 		ip_fanout_v6(mp, ip6h, ira);
12091 	}
12092 }
12093 
12094 /*
12095  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12096  *
12097  * If this function returns B_TRUE, the requested SA's have been filled
12098  * into the ixa_ipsec_*_sa pointers.
12099  *
12100  * If the function returns B_FALSE, the packet has been "consumed", most
12101  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12102  *
12103  * The SA references created by the protocol-specific "select"
12104  * function will be released in ip_output_post_ipsec.
12105  */
12106 static boolean_t
12107 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12108 {
12109 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12110 	ipsec_policy_t *pp;
12111 	ipsec_action_t *ap;
12112 
12113 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12114 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12115 	    (ixa->ixa_ipsec_action != NULL));
12116 
12117 	ap = ixa->ixa_ipsec_action;
12118 	if (ap == NULL) {
12119 		pp = ixa->ixa_ipsec_policy;
12120 		ASSERT(pp != NULL);
12121 		ap = pp->ipsp_act;
12122 		ASSERT(ap != NULL);
12123 	}
12124 
12125 	/*
12126 	 * We have an action.  now, let's select SA's.
12127 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12128 	 * be cached in the conn_t.
12129 	 */
12130 	if (ap->ipa_want_esp) {
12131 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12132 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12133 			    IPPROTO_ESP);
12134 		}
12135 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12136 	}
12137 
12138 	if (ap->ipa_want_ah) {
12139 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12140 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12141 			    IPPROTO_AH);
12142 		}
12143 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12144 		/*
12145 		 * The ESP and AH processing order needs to be preserved
12146 		 * when both protocols are required (ESP should be applied
12147 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12148 		 * when both ESP and AH are required, and an AH ACQUIRE
12149 		 * is needed.
12150 		 */
12151 		if (ap->ipa_want_esp && need_ah_acquire)
12152 			need_esp_acquire = B_TRUE;
12153 	}
12154 
12155 	/*
12156 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12157 	 * Release SAs that got referenced, but will not be used until we
12158 	 * acquire _all_ of the SAs we need.
12159 	 */
12160 	if (need_ah_acquire || need_esp_acquire) {
12161 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12162 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12163 			ixa->ixa_ipsec_ah_sa = NULL;
12164 		}
12165 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12166 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12167 			ixa->ixa_ipsec_esp_sa = NULL;
12168 		}
12169 
12170 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12171 		return (B_FALSE);
12172 	}
12173 
12174 	return (B_TRUE);
12175 }
12176 
12177 /*
12178  * Handle IPsec output processing.
12179  * This function is only entered once for a given packet.
12180  * We try to do things synchronously, but if we need to have user-level
12181  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12182  * will be completed
12183  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12184  *  - when asynchronous ESP is done it will do AH
12185  *
12186  * In all cases we come back in ip_output_post_ipsec() to fragment and
12187  * send out the packet.
12188  */
12189 int
12190 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12191 {
12192 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12193 	ip_stack_t	*ipst = ixa->ixa_ipst;
12194 	ipsec_stack_t	*ipss;
12195 	ipsec_policy_t	*pp;
12196 	ipsec_action_t	*ap;
12197 
12198 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12199 
12200 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12201 	    (ixa->ixa_ipsec_action != NULL));
12202 
12203 	ipss = ipst->ips_netstack->netstack_ipsec;
12204 	if (!ipsec_loaded(ipss)) {
12205 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12206 		ip_drop_packet(mp, B_TRUE, ill,
12207 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12208 		    &ipss->ipsec_dropper);
12209 		return (ENOTSUP);
12210 	}
12211 
12212 	ap = ixa->ixa_ipsec_action;
12213 	if (ap == NULL) {
12214 		pp = ixa->ixa_ipsec_policy;
12215 		ASSERT(pp != NULL);
12216 		ap = pp->ipsp_act;
12217 		ASSERT(ap != NULL);
12218 	}
12219 
12220 	/* Handle explicit drop action and bypass. */
12221 	switch (ap->ipa_act.ipa_type) {
12222 	case IPSEC_ACT_DISCARD:
12223 	case IPSEC_ACT_REJECT:
12224 		ip_drop_packet(mp, B_FALSE, ill,
12225 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12226 		return (EHOSTUNREACH);	/* IPsec policy failure */
12227 	case IPSEC_ACT_BYPASS:
12228 		return (ip_output_post_ipsec(mp, ixa));
12229 	}
12230 
12231 	/*
12232 	 * The order of processing is first insert a IP header if needed.
12233 	 * Then insert the ESP header and then the AH header.
12234 	 */
12235 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12236 		/*
12237 		 * First get the outer IP header before sending
12238 		 * it to ESP.
12239 		 */
12240 		ipha_t *oipha, *iipha;
12241 		mblk_t *outer_mp, *inner_mp;
12242 
12243 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12244 			(void) mi_strlog(ill->ill_rq, 0,
12245 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12246 			    "ipsec_out_process: "
12247 			    "Self-Encapsulation failed: Out of memory\n");
12248 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12249 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12250 			freemsg(mp);
12251 			return (ENOBUFS);
12252 		}
12253 		inner_mp = mp;
12254 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12255 		oipha = (ipha_t *)outer_mp->b_rptr;
12256 		iipha = (ipha_t *)inner_mp->b_rptr;
12257 		*oipha = *iipha;
12258 		outer_mp->b_wptr += sizeof (ipha_t);
12259 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12260 		    sizeof (ipha_t));
12261 		oipha->ipha_protocol = IPPROTO_ENCAP;
12262 		oipha->ipha_version_and_hdr_length =
12263 		    IP_SIMPLE_HDR_VERSION;
12264 		oipha->ipha_hdr_checksum = 0;
12265 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12266 		outer_mp->b_cont = inner_mp;
12267 		mp = outer_mp;
12268 
12269 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12270 	}
12271 
12272 	/* If we need to wait for a SA then we can't return any errno */
12273 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12274 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12275 	    !ipsec_out_select_sa(mp, ixa))
12276 		return (0);
12277 
12278 	/*
12279 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12280 	 * to do the heavy lifting.
12281 	 */
12282 	if (ap->ipa_want_esp) {
12283 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12284 
12285 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12286 		if (mp == NULL) {
12287 			/*
12288 			 * Either it failed or is pending. In the former case
12289 			 * ipIfStatsInDiscards was increased.
12290 			 */
12291 			return (0);
12292 		}
12293 	}
12294 
12295 	if (ap->ipa_want_ah) {
12296 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12297 
12298 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12299 		if (mp == NULL) {
12300 			/*
12301 			 * Either it failed or is pending. In the former case
12302 			 * ipIfStatsInDiscards was increased.
12303 			 */
12304 			return (0);
12305 		}
12306 	}
12307 	/*
12308 	 * We are done with IPsec processing. Send it over
12309 	 * the wire.
12310 	 */
12311 	return (ip_output_post_ipsec(mp, ixa));
12312 }
12313 
12314 /*
12315  * ioctls that go through a down/up sequence may need to wait for the down
12316  * to complete. This involves waiting for the ire and ipif refcnts to go down
12317  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12318  */
12319 /* ARGSUSED */
12320 void
12321 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12322 {
12323 	struct iocblk *iocp;
12324 	mblk_t *mp1;
12325 	ip_ioctl_cmd_t *ipip;
12326 	int err;
12327 	sin_t	*sin;
12328 	struct lifreq *lifr;
12329 	struct ifreq *ifr;
12330 
12331 	iocp = (struct iocblk *)mp->b_rptr;
12332 	ASSERT(ipsq != NULL);
12333 	/* Existence of mp1 verified in ip_wput_nondata */
12334 	mp1 = mp->b_cont->b_cont;
12335 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12336 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12337 		/*
12338 		 * Special case where ipx_current_ipif is not set:
12339 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12340 		 * We are here as were not able to complete the operation in
12341 		 * ipif_set_values because we could not become exclusive on
12342 		 * the new ipsq.
12343 		 */
12344 		ill_t *ill = q->q_ptr;
12345 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12346 	}
12347 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12348 
12349 	if (ipip->ipi_cmd_type == IF_CMD) {
12350 		/* This a old style SIOC[GS]IF* command */
12351 		ifr = (struct ifreq *)mp1->b_rptr;
12352 		sin = (sin_t *)&ifr->ifr_addr;
12353 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12354 		/* This a new style SIOC[GS]LIF* command */
12355 		lifr = (struct lifreq *)mp1->b_rptr;
12356 		sin = (sin_t *)&lifr->lifr_addr;
12357 	} else {
12358 		sin = NULL;
12359 	}
12360 
12361 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12362 	    q, mp, ipip, mp1->b_rptr);
12363 
12364 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12365 	    int, ipip->ipi_cmd,
12366 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12367 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12368 
12369 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12370 }
12371 
12372 /*
12373  * ioctl processing
12374  *
12375  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12376  * the ioctl command in the ioctl tables, determines the copyin data size
12377  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12378  *
12379  * ioctl processing then continues when the M_IOCDATA makes its way down to
12380  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12381  * associated 'conn' is refheld till the end of the ioctl and the general
12382  * ioctl processing function ip_process_ioctl() is called to extract the
12383  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12384  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12385  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12386  * is used to extract the ioctl's arguments.
12387  *
12388  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12389  * so goes thru the serialization primitive ipsq_try_enter. Then the
12390  * appropriate function to handle the ioctl is called based on the entry in
12391  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12392  * which also refreleases the 'conn' that was refheld at the start of the
12393  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12394  *
12395  * Many exclusive ioctls go thru an internal down up sequence as part of
12396  * the operation. For example an attempt to change the IP address of an
12397  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12398  * does all the cleanup such as deleting all ires that use this address.
12399  * Then we need to wait till all references to the interface go away.
12400  */
12401 void
12402 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12403 {
12404 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12405 	ip_ioctl_cmd_t *ipip = arg;
12406 	ip_extract_func_t *extract_funcp;
12407 	cmd_info_t ci;
12408 	int err;
12409 	boolean_t entered_ipsq = B_FALSE;
12410 
12411 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12412 
12413 	if (ipip == NULL)
12414 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12415 
12416 	/*
12417 	 * SIOCLIFADDIF needs to go thru a special path since the
12418 	 * ill may not exist yet. This happens in the case of lo0
12419 	 * which is created using this ioctl.
12420 	 */
12421 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12422 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12423 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12424 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12425 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12426 		return;
12427 	}
12428 
12429 	ci.ci_ipif = NULL;
12430 	switch (ipip->ipi_cmd_type) {
12431 	case MISC_CMD:
12432 	case MSFILT_CMD:
12433 		/*
12434 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12435 		 */
12436 		if (ipip->ipi_cmd == IF_UNITSEL) {
12437 			/* ioctl comes down the ill */
12438 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12439 			ipif_refhold(ci.ci_ipif);
12440 		}
12441 		err = 0;
12442 		ci.ci_sin = NULL;
12443 		ci.ci_sin6 = NULL;
12444 		ci.ci_lifr = NULL;
12445 		extract_funcp = NULL;
12446 		break;
12447 
12448 	case IF_CMD:
12449 	case LIF_CMD:
12450 		extract_funcp = ip_extract_lifreq;
12451 		break;
12452 
12453 	case ARP_CMD:
12454 	case XARP_CMD:
12455 		extract_funcp = ip_extract_arpreq;
12456 		break;
12457 
12458 	default:
12459 		ASSERT(0);
12460 	}
12461 
12462 	if (extract_funcp != NULL) {
12463 		err = (*extract_funcp)(q, mp, ipip, &ci);
12464 		if (err != 0) {
12465 			DTRACE_PROBE4(ipif__ioctl,
12466 			    char *, "ip_process_ioctl finish err",
12467 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12468 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12469 			return;
12470 		}
12471 
12472 		/*
12473 		 * All of the extraction functions return a refheld ipif.
12474 		 */
12475 		ASSERT(ci.ci_ipif != NULL);
12476 	}
12477 
12478 	if (!(ipip->ipi_flags & IPI_WR)) {
12479 		/*
12480 		 * A return value of EINPROGRESS means the ioctl is
12481 		 * either queued and waiting for some reason or has
12482 		 * already completed.
12483 		 */
12484 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12485 		    ci.ci_lifr);
12486 		if (ci.ci_ipif != NULL) {
12487 			DTRACE_PROBE4(ipif__ioctl,
12488 			    char *, "ip_process_ioctl finish RD",
12489 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12490 			    ipif_t *, ci.ci_ipif);
12491 			ipif_refrele(ci.ci_ipif);
12492 		} else {
12493 			DTRACE_PROBE4(ipif__ioctl,
12494 			    char *, "ip_process_ioctl finish RD",
12495 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12496 		}
12497 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12498 		return;
12499 	}
12500 
12501 	ASSERT(ci.ci_ipif != NULL);
12502 
12503 	/*
12504 	 * If ipsq is non-NULL, we are already being called exclusively
12505 	 */
12506 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12507 	if (ipsq == NULL) {
12508 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12509 		    NEW_OP, B_TRUE);
12510 		if (ipsq == NULL) {
12511 			ipif_refrele(ci.ci_ipif);
12512 			return;
12513 		}
12514 		entered_ipsq = B_TRUE;
12515 	}
12516 	/*
12517 	 * Release the ipif so that ipif_down and friends that wait for
12518 	 * references to go away are not misled about the current ipif_refcnt
12519 	 * values. We are writer so we can access the ipif even after releasing
12520 	 * the ipif.
12521 	 */
12522 	ipif_refrele(ci.ci_ipif);
12523 
12524 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12525 
12526 	/*
12527 	 * A return value of EINPROGRESS means the ioctl is
12528 	 * either queued and waiting for some reason or has
12529 	 * already completed.
12530 	 */
12531 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12532 
12533 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12534 	    int, ipip->ipi_cmd,
12535 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12536 	    ipif_t *, ci.ci_ipif);
12537 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12538 
12539 	if (entered_ipsq)
12540 		ipsq_exit(ipsq);
12541 }
12542 
12543 /*
12544  * Complete the ioctl. Typically ioctls use the mi package and need to
12545  * do mi_copyout/mi_copy_done.
12546  */
12547 void
12548 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12549 {
12550 	conn_t	*connp = NULL;
12551 
12552 	if (err == EINPROGRESS)
12553 		return;
12554 
12555 	if (CONN_Q(q)) {
12556 		connp = Q_TO_CONN(q);
12557 		ASSERT(connp->conn_ref >= 2);
12558 	}
12559 
12560 	switch (mode) {
12561 	case COPYOUT:
12562 		if (err == 0)
12563 			mi_copyout(q, mp);
12564 		else
12565 			mi_copy_done(q, mp, err);
12566 		break;
12567 
12568 	case NO_COPYOUT:
12569 		mi_copy_done(q, mp, err);
12570 		break;
12571 
12572 	default:
12573 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12574 		break;
12575 	}
12576 
12577 	/*
12578 	 * The conn refhold and ioctlref placed on the conn at the start of the
12579 	 * ioctl are released here.
12580 	 */
12581 	if (connp != NULL) {
12582 		CONN_DEC_IOCTLREF(connp);
12583 		CONN_OPER_PENDING_DONE(connp);
12584 	}
12585 
12586 	if (ipsq != NULL)
12587 		ipsq_current_finish(ipsq);
12588 }
12589 
12590 /* Handles all non data messages */
12591 void
12592 ip_wput_nondata(queue_t *q, mblk_t *mp)
12593 {
12594 	mblk_t		*mp1;
12595 	struct iocblk	*iocp;
12596 	ip_ioctl_cmd_t	*ipip;
12597 	conn_t		*connp;
12598 	cred_t		*cr;
12599 	char		*proto_str;
12600 
12601 	if (CONN_Q(q))
12602 		connp = Q_TO_CONN(q);
12603 	else
12604 		connp = NULL;
12605 
12606 	switch (DB_TYPE(mp)) {
12607 	case M_IOCTL:
12608 		/*
12609 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12610 		 * will arrange to copy in associated control structures.
12611 		 */
12612 		ip_sioctl_copyin_setup(q, mp);
12613 		return;
12614 	case M_IOCDATA:
12615 		/*
12616 		 * Ensure that this is associated with one of our trans-
12617 		 * parent ioctls.  If it's not ours, discard it if we're
12618 		 * running as a driver, or pass it on if we're a module.
12619 		 */
12620 		iocp = (struct iocblk *)mp->b_rptr;
12621 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12622 		if (ipip == NULL) {
12623 			if (q->q_next == NULL) {
12624 				goto nak;
12625 			} else {
12626 				putnext(q, mp);
12627 			}
12628 			return;
12629 		}
12630 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12631 			/*
12632 			 * The ioctl is one we recognise, but is not consumed
12633 			 * by IP as a module and we are a module, so we drop
12634 			 */
12635 			goto nak;
12636 		}
12637 
12638 		/* IOCTL continuation following copyin or copyout. */
12639 		if (mi_copy_state(q, mp, NULL) == -1) {
12640 			/*
12641 			 * The copy operation failed.  mi_copy_state already
12642 			 * cleaned up, so we're out of here.
12643 			 */
12644 			return;
12645 		}
12646 		/*
12647 		 * If we just completed a copy in, we become writer and
12648 		 * continue processing in ip_sioctl_copyin_done.  If it
12649 		 * was a copy out, we call mi_copyout again.  If there is
12650 		 * nothing more to copy out, it will complete the IOCTL.
12651 		 */
12652 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12653 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12654 				mi_copy_done(q, mp, EPROTO);
12655 				return;
12656 			}
12657 			/*
12658 			 * Check for cases that need more copying.  A return
12659 			 * value of 0 means a second copyin has been started,
12660 			 * so we return; a return value of 1 means no more
12661 			 * copying is needed, so we continue.
12662 			 */
12663 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12664 			    MI_COPY_COUNT(mp) == 1) {
12665 				if (ip_copyin_msfilter(q, mp) == 0)
12666 					return;
12667 			}
12668 			/*
12669 			 * Refhold the conn, till the ioctl completes. This is
12670 			 * needed in case the ioctl ends up in the pending mp
12671 			 * list. Every mp in the ipx_pending_mp list must have
12672 			 * a refhold on the conn to resume processing. The
12673 			 * refhold is released when the ioctl completes
12674 			 * (whether normally or abnormally). An ioctlref is also
12675 			 * placed on the conn to prevent TCP from removing the
12676 			 * queue needed to send the ioctl reply back.
12677 			 * In all cases ip_ioctl_finish is called to finish
12678 			 * the ioctl and release the refholds.
12679 			 */
12680 			if (connp != NULL) {
12681 				/* This is not a reentry */
12682 				CONN_INC_REF(connp);
12683 				CONN_INC_IOCTLREF(connp);
12684 			} else {
12685 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12686 					mi_copy_done(q, mp, EINVAL);
12687 					return;
12688 				}
12689 			}
12690 
12691 			ip_process_ioctl(NULL, q, mp, ipip);
12692 
12693 		} else {
12694 			mi_copyout(q, mp);
12695 		}
12696 		return;
12697 
12698 	case M_IOCNAK:
12699 		/*
12700 		 * The only way we could get here is if a resolver didn't like
12701 		 * an IOCTL we sent it.	 This shouldn't happen.
12702 		 */
12703 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12704 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12705 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12706 		freemsg(mp);
12707 		return;
12708 	case M_IOCACK:
12709 		/* /dev/ip shouldn't see this */
12710 		goto nak;
12711 	case M_FLUSH:
12712 		if (*mp->b_rptr & FLUSHW)
12713 			flushq(q, FLUSHALL);
12714 		if (q->q_next) {
12715 			putnext(q, mp);
12716 			return;
12717 		}
12718 		if (*mp->b_rptr & FLUSHR) {
12719 			*mp->b_rptr &= ~FLUSHW;
12720 			qreply(q, mp);
12721 			return;
12722 		}
12723 		freemsg(mp);
12724 		return;
12725 	case M_CTL:
12726 		break;
12727 	case M_PROTO:
12728 	case M_PCPROTO:
12729 		/*
12730 		 * The only PROTO messages we expect are SNMP-related.
12731 		 */
12732 		switch (((union T_primitives *)mp->b_rptr)->type) {
12733 		case T_SVR4_OPTMGMT_REQ:
12734 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12735 			    "flags %x\n",
12736 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12737 
12738 			if (connp == NULL) {
12739 				proto_str = "T_SVR4_OPTMGMT_REQ";
12740 				goto protonak;
12741 			}
12742 
12743 			/*
12744 			 * All Solaris components should pass a db_credp
12745 			 * for this TPI message, hence we ASSERT.
12746 			 * But in case there is some other M_PROTO that looks
12747 			 * like a TPI message sent by some other kernel
12748 			 * component, we check and return an error.
12749 			 */
12750 			cr = msg_getcred(mp, NULL);
12751 			ASSERT(cr != NULL);
12752 			if (cr == NULL) {
12753 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12754 				if (mp != NULL)
12755 					qreply(q, mp);
12756 				return;
12757 			}
12758 
12759 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12760 				proto_str = "Bad SNMPCOM request?";
12761 				goto protonak;
12762 			}
12763 			return;
12764 		default:
12765 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12766 			    (int)*(uint_t *)mp->b_rptr));
12767 			freemsg(mp);
12768 			return;
12769 		}
12770 	default:
12771 		break;
12772 	}
12773 	if (q->q_next) {
12774 		putnext(q, mp);
12775 	} else
12776 		freemsg(mp);
12777 	return;
12778 
12779 nak:
12780 	iocp->ioc_error = EINVAL;
12781 	mp->b_datap->db_type = M_IOCNAK;
12782 	iocp->ioc_count = 0;
12783 	qreply(q, mp);
12784 	return;
12785 
12786 protonak:
12787 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12788 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12789 		qreply(q, mp);
12790 }
12791 
12792 /*
12793  * Process IP options in an outbound packet.  Verify that the nexthop in a
12794  * strict source route is onlink.
12795  * Returns non-zero if something fails in which case an ICMP error has been
12796  * sent and mp freed.
12797  *
12798  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12799  */
12800 int
12801 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12802 {
12803 	ipoptp_t	opts;
12804 	uchar_t		*opt;
12805 	uint8_t		optval;
12806 	uint8_t		optlen;
12807 	ipaddr_t	dst;
12808 	intptr_t	code = 0;
12809 	ire_t		*ire;
12810 	ip_stack_t	*ipst = ixa->ixa_ipst;
12811 	ip_recv_attr_t	iras;
12812 
12813 	ip2dbg(("ip_output_options\n"));
12814 
12815 	dst = ipha->ipha_dst;
12816 	for (optval = ipoptp_first(&opts, ipha);
12817 	    optval != IPOPT_EOL;
12818 	    optval = ipoptp_next(&opts)) {
12819 		opt = opts.ipoptp_cur;
12820 		optlen = opts.ipoptp_len;
12821 		ip2dbg(("ip_output_options: opt %d, len %d\n",
12822 		    optval, optlen));
12823 		switch (optval) {
12824 			uint32_t off;
12825 		case IPOPT_SSRR:
12826 		case IPOPT_LSRR:
12827 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12828 				ip1dbg((
12829 				    "ip_output_options: bad option offset\n"));
12830 				code = (char *)&opt[IPOPT_OLEN] -
12831 				    (char *)ipha;
12832 				goto param_prob;
12833 			}
12834 			off = opt[IPOPT_OFFSET];
12835 			ip1dbg(("ip_output_options: next hop 0x%x\n",
12836 			    ntohl(dst)));
12837 			/*
12838 			 * For strict: verify that dst is directly
12839 			 * reachable.
12840 			 */
12841 			if (optval == IPOPT_SSRR) {
12842 				ire = ire_ftable_lookup_v4(dst, 0, 0,
12843 				    IRE_IF_ALL, NULL, ALL_ZONES, ixa->ixa_tsl,
12844 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
12845 				    NULL);
12846 				if (ire == NULL) {
12847 					ip1dbg(("ip_output_options: SSRR not"
12848 					    " directly reachable: 0x%x\n",
12849 					    ntohl(dst)));
12850 					goto bad_src_route;
12851 				}
12852 				ire_refrele(ire);
12853 			}
12854 			break;
12855 		case IPOPT_RR:
12856 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12857 				ip1dbg((
12858 				    "ip_output_options: bad option offset\n"));
12859 				code = (char *)&opt[IPOPT_OLEN] -
12860 				    (char *)ipha;
12861 				goto param_prob;
12862 			}
12863 			break;
12864 		case IPOPT_TS:
12865 			/*
12866 			 * Verify that length >=5 and that there is either
12867 			 * room for another timestamp or that the overflow
12868 			 * counter is not maxed out.
12869 			 */
12870 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
12871 			if (optlen < IPOPT_MINLEN_IT) {
12872 				goto param_prob;
12873 			}
12874 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12875 				ip1dbg((
12876 				    "ip_output_options: bad option offset\n"));
12877 				code = (char *)&opt[IPOPT_OFFSET] -
12878 				    (char *)ipha;
12879 				goto param_prob;
12880 			}
12881 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12882 			case IPOPT_TS_TSONLY:
12883 				off = IPOPT_TS_TIMELEN;
12884 				break;
12885 			case IPOPT_TS_TSANDADDR:
12886 			case IPOPT_TS_PRESPEC:
12887 			case IPOPT_TS_PRESPEC_RFC791:
12888 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12889 				break;
12890 			default:
12891 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
12892 				    (char *)ipha;
12893 				goto param_prob;
12894 			}
12895 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
12896 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
12897 				/*
12898 				 * No room and the overflow counter is 15
12899 				 * already.
12900 				 */
12901 				goto param_prob;
12902 			}
12903 			break;
12904 		}
12905 	}
12906 
12907 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
12908 		return (0);
12909 
12910 	ip1dbg(("ip_output_options: error processing IP options."));
12911 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
12912 
12913 param_prob:
12914 	bzero(&iras, sizeof (iras));
12915 	iras.ira_ill = iras.ira_rill = ill;
12916 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12917 	iras.ira_rifindex = iras.ira_ruifindex;
12918 	iras.ira_flags = IRAF_IS_IPV4;
12919 
12920 	ip_drop_output("ip_output_options", mp, ill);
12921 	icmp_param_problem(mp, (uint8_t)code, &iras);
12922 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12923 	return (-1);
12924 
12925 bad_src_route:
12926 	bzero(&iras, sizeof (iras));
12927 	iras.ira_ill = iras.ira_rill = ill;
12928 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12929 	iras.ira_rifindex = iras.ira_ruifindex;
12930 	iras.ira_flags = IRAF_IS_IPV4;
12931 
12932 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
12933 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
12934 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12935 	return (-1);
12936 }
12937 
12938 /*
12939  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
12940  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
12941  * thru /etc/system.
12942  */
12943 #define	CONN_MAXDRAINCNT	64
12944 
12945 static void
12946 conn_drain_init(ip_stack_t *ipst)
12947 {
12948 	int i, j;
12949 	idl_tx_list_t *itl_tx;
12950 
12951 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
12952 
12953 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
12954 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
12955 		/*
12956 		 * Default value of the number of drainers is the
12957 		 * number of cpus, subject to maximum of 8 drainers.
12958 		 */
12959 		if (boot_max_ncpus != -1)
12960 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
12961 		else
12962 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
12963 	}
12964 
12965 	ipst->ips_idl_tx_list =
12966 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
12967 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
12968 		itl_tx =  &ipst->ips_idl_tx_list[i];
12969 		itl_tx->txl_drain_list =
12970 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
12971 		    sizeof (idl_t), KM_SLEEP);
12972 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
12973 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
12974 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
12975 			    MUTEX_DEFAULT, NULL);
12976 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
12977 		}
12978 	}
12979 }
12980 
12981 static void
12982 conn_drain_fini(ip_stack_t *ipst)
12983 {
12984 	int i;
12985 	idl_tx_list_t *itl_tx;
12986 
12987 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
12988 		itl_tx =  &ipst->ips_idl_tx_list[i];
12989 		kmem_free(itl_tx->txl_drain_list,
12990 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
12991 	}
12992 	kmem_free(ipst->ips_idl_tx_list,
12993 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
12994 	ipst->ips_idl_tx_list = NULL;
12995 }
12996 
12997 /*
12998  * Flow control has blocked us from proceeding.  Insert the given conn in one
12999  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13000  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13001  * will call conn_walk_drain().  See the flow control notes at the top of this
13002  * file for more details.
13003  */
13004 void
13005 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13006 {
13007 	idl_t	*idl = tx_list->txl_drain_list;
13008 	uint_t	index;
13009 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13010 
13011 	mutex_enter(&connp->conn_lock);
13012 	if (connp->conn_state_flags & CONN_CLOSING) {
13013 		/*
13014 		 * The conn is closing as a result of which CONN_CLOSING
13015 		 * is set. Return.
13016 		 */
13017 		mutex_exit(&connp->conn_lock);
13018 		return;
13019 	} else if (connp->conn_idl == NULL) {
13020 		/*
13021 		 * Assign the next drain list round robin. We dont' use
13022 		 * a lock, and thus it may not be strictly round robin.
13023 		 * Atomicity of load/stores is enough to make sure that
13024 		 * conn_drain_list_index is always within bounds.
13025 		 */
13026 		index = tx_list->txl_drain_index;
13027 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13028 		connp->conn_idl = &tx_list->txl_drain_list[index];
13029 		index++;
13030 		if (index == ipst->ips_conn_drain_list_cnt)
13031 			index = 0;
13032 		tx_list->txl_drain_index = index;
13033 	} else {
13034 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13035 	}
13036 	mutex_exit(&connp->conn_lock);
13037 
13038 	idl = connp->conn_idl;
13039 	mutex_enter(&idl->idl_lock);
13040 	if ((connp->conn_drain_prev != NULL) ||
13041 	    (connp->conn_state_flags & CONN_CLOSING)) {
13042 		/*
13043 		 * The conn is either already in the drain list or closing.
13044 		 * (We needed to check for CONN_CLOSING again since close can
13045 		 * sneak in between dropping conn_lock and acquiring idl_lock.)
13046 		 */
13047 		mutex_exit(&idl->idl_lock);
13048 		return;
13049 	}
13050 
13051 	/*
13052 	 * The conn is not in the drain list. Insert it at the
13053 	 * tail of the drain list. The drain list is circular
13054 	 * and doubly linked. idl_conn points to the 1st element
13055 	 * in the list.
13056 	 */
13057 	if (idl->idl_conn == NULL) {
13058 		idl->idl_conn = connp;
13059 		connp->conn_drain_next = connp;
13060 		connp->conn_drain_prev = connp;
13061 	} else {
13062 		conn_t *head = idl->idl_conn;
13063 
13064 		connp->conn_drain_next = head;
13065 		connp->conn_drain_prev = head->conn_drain_prev;
13066 		head->conn_drain_prev->conn_drain_next = connp;
13067 		head->conn_drain_prev = connp;
13068 	}
13069 	/*
13070 	 * For non streams based sockets assert flow control.
13071 	 */
13072 	conn_setqfull(connp, NULL);
13073 	mutex_exit(&idl->idl_lock);
13074 }
13075 
13076 static void
13077 conn_drain_remove(conn_t *connp)
13078 {
13079 	idl_t *idl = connp->conn_idl;
13080 
13081 	if (idl != NULL) {
13082 		/*
13083 		 * Remove ourself from the drain list.
13084 		 */
13085 		if (connp->conn_drain_next == connp) {
13086 			/* Singleton in the list */
13087 			ASSERT(connp->conn_drain_prev == connp);
13088 			idl->idl_conn = NULL;
13089 		} else {
13090 			connp->conn_drain_prev->conn_drain_next =
13091 			    connp->conn_drain_next;
13092 			connp->conn_drain_next->conn_drain_prev =
13093 			    connp->conn_drain_prev;
13094 			if (idl->idl_conn == connp)
13095 				idl->idl_conn = connp->conn_drain_next;
13096 		}
13097 
13098 		/*
13099 		 * NOTE: because conn_idl is associated with a specific drain
13100 		 * list which in turn is tied to the index the TX ring
13101 		 * (txl_cookie) hashes to, and because the TX ring can change
13102 		 * over the lifetime of the conn_t, we must clear conn_idl so
13103 		 * a subsequent conn_drain_insert() will set conn_idl again
13104 		 * based on the latest txl_cookie.
13105 		 */
13106 		connp->conn_idl = NULL;
13107 	}
13108 	connp->conn_drain_next = NULL;
13109 	connp->conn_drain_prev = NULL;
13110 
13111 	conn_clrqfull(connp, NULL);
13112 	/*
13113 	 * For streams based sockets open up flow control.
13114 	 */
13115 	if (!IPCL_IS_NONSTR(connp))
13116 		enableok(connp->conn_wq);
13117 }
13118 
13119 /*
13120  * This conn is closing, and we are called from ip_close. OR
13121  * this conn is draining because flow-control on the ill has been relieved.
13122  *
13123  * We must also need to remove conn's on this idl from the list, and also
13124  * inform the sockfs upcalls about the change in flow-control.
13125  */
13126 static void
13127 conn_drain(conn_t *connp, boolean_t closing)
13128 {
13129 	idl_t *idl;
13130 	conn_t *next_connp;
13131 
13132 	/*
13133 	 * connp->conn_idl is stable at this point, and no lock is needed
13134 	 * to check it. If we are called from ip_close, close has already
13135 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13136 	 * called us only because conn_idl is non-null. If we are called thru
13137 	 * service, conn_idl could be null, but it cannot change because
13138 	 * service is single-threaded per queue, and there cannot be another
13139 	 * instance of service trying to call conn_drain_insert on this conn
13140 	 * now.
13141 	 */
13142 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13143 
13144 	/*
13145 	 * If the conn doesn't exist or is not on a drain list, bail.
13146 	 */
13147 	if (connp == NULL || connp->conn_idl == NULL ||
13148 	    connp->conn_drain_prev == NULL) {
13149 		return;
13150 	}
13151 
13152 	idl = connp->conn_idl;
13153 	ASSERT(MUTEX_HELD(&idl->idl_lock));
13154 
13155 	if (!closing) {
13156 		next_connp = connp->conn_drain_next;
13157 		while (next_connp != connp) {
13158 			conn_t *delconnp = next_connp;
13159 
13160 			next_connp = next_connp->conn_drain_next;
13161 			conn_drain_remove(delconnp);
13162 		}
13163 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13164 	}
13165 	conn_drain_remove(connp);
13166 }
13167 
13168 /*
13169  * Write service routine. Shared perimeter entry point.
13170  * The device queue's messages has fallen below the low water mark and STREAMS
13171  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13172  * each waiting conn.
13173  */
13174 void
13175 ip_wsrv(queue_t *q)
13176 {
13177 	ill_t	*ill;
13178 
13179 	ill = (ill_t *)q->q_ptr;
13180 	if (ill->ill_state_flags == 0) {
13181 		ip_stack_t *ipst = ill->ill_ipst;
13182 
13183 		/*
13184 		 * The device flow control has opened up.
13185 		 * Walk through conn drain lists and qenable the
13186 		 * first conn in each list. This makes sense only
13187 		 * if the stream is fully plumbed and setup.
13188 		 * Hence the ill_state_flags check above.
13189 		 */
13190 		ip1dbg(("ip_wsrv: walking\n"));
13191 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13192 		enableok(ill->ill_wq);
13193 	}
13194 }
13195 
13196 /*
13197  * Callback to disable flow control in IP.
13198  *
13199  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13200  * is enabled.
13201  *
13202  * When MAC_TX() is not able to send any more packets, dld sets its queue
13203  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13204  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13205  * function and wakes up corresponding mac worker threads, which in turn
13206  * calls this callback function, and disables flow control.
13207  */
13208 void
13209 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13210 {
13211 	ill_t *ill = (ill_t *)arg;
13212 	ip_stack_t *ipst = ill->ill_ipst;
13213 	idl_tx_list_t *idl_txl;
13214 
13215 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13216 	mutex_enter(&idl_txl->txl_lock);
13217 	/* add code to to set a flag to indicate idl_txl is enabled */
13218 	conn_walk_drain(ipst, idl_txl);
13219 	mutex_exit(&idl_txl->txl_lock);
13220 }
13221 
13222 /*
13223  * Flow control has been relieved and STREAMS has backenabled us; drain
13224  * all the conn lists on `tx_list'.
13225  */
13226 static void
13227 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13228 {
13229 	int i;
13230 	idl_t *idl;
13231 
13232 	IP_STAT(ipst, ip_conn_walk_drain);
13233 
13234 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13235 		idl = &tx_list->txl_drain_list[i];
13236 		mutex_enter(&idl->idl_lock);
13237 		conn_drain(idl->idl_conn, B_FALSE);
13238 		mutex_exit(&idl->idl_lock);
13239 	}
13240 }
13241 
13242 /*
13243  * Determine if the ill and multicast aspects of that packets
13244  * "matches" the conn.
13245  */
13246 boolean_t
13247 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13248 {
13249 	ill_t		*ill = ira->ira_rill;
13250 	zoneid_t	zoneid = ira->ira_zoneid;
13251 	uint_t		in_ifindex;
13252 	ipaddr_t	dst, src;
13253 
13254 	dst = ipha->ipha_dst;
13255 	src = ipha->ipha_src;
13256 
13257 	/*
13258 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13259 	 * unicast, broadcast and multicast reception to
13260 	 * conn_incoming_ifindex.
13261 	 * conn_wantpacket is called for unicast, broadcast and
13262 	 * multicast packets.
13263 	 */
13264 	in_ifindex = connp->conn_incoming_ifindex;
13265 
13266 	/* mpathd can bind to the under IPMP interface, which we allow */
13267 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13268 		if (!IS_UNDER_IPMP(ill))
13269 			return (B_FALSE);
13270 
13271 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13272 			return (B_FALSE);
13273 	}
13274 
13275 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13276 		return (B_FALSE);
13277 
13278 	if (!(ira->ira_flags & IRAF_MULTICAST))
13279 		return (B_TRUE);
13280 
13281 	if (connp->conn_multi_router) {
13282 		/* multicast packet and multicast router socket: send up */
13283 		return (B_TRUE);
13284 	}
13285 
13286 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13287 	    ipha->ipha_protocol == IPPROTO_RSVP)
13288 		return (B_TRUE);
13289 
13290 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13291 }
13292 
13293 void
13294 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13295 {
13296 	if (IPCL_IS_NONSTR(connp)) {
13297 		(*connp->conn_upcalls->su_txq_full)
13298 		    (connp->conn_upper_handle, B_TRUE);
13299 		if (flow_stopped != NULL)
13300 			*flow_stopped = B_TRUE;
13301 	} else {
13302 		queue_t *q = connp->conn_wq;
13303 
13304 		ASSERT(q != NULL);
13305 		if (!(q->q_flag & QFULL)) {
13306 			mutex_enter(QLOCK(q));
13307 			if (!(q->q_flag & QFULL)) {
13308 				/* still need to set QFULL */
13309 				q->q_flag |= QFULL;
13310 				/* set flow_stopped to true under QLOCK */
13311 				if (flow_stopped != NULL)
13312 					*flow_stopped = B_TRUE;
13313 				mutex_exit(QLOCK(q));
13314 			} else {
13315 				/* flow_stopped is left unchanged */
13316 				mutex_exit(QLOCK(q));
13317 			}
13318 		}
13319 	}
13320 }
13321 
13322 void
13323 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13324 {
13325 	if (IPCL_IS_NONSTR(connp)) {
13326 		(*connp->conn_upcalls->su_txq_full)
13327 		    (connp->conn_upper_handle, B_FALSE);
13328 		if (flow_stopped != NULL)
13329 			*flow_stopped = B_FALSE;
13330 	} else {
13331 		queue_t *q = connp->conn_wq;
13332 
13333 		ASSERT(q != NULL);
13334 		if (q->q_flag & QFULL) {
13335 			mutex_enter(QLOCK(q));
13336 			if (q->q_flag & QFULL) {
13337 				q->q_flag &= ~QFULL;
13338 				/* set flow_stopped to false under QLOCK */
13339 				if (flow_stopped != NULL)
13340 					*flow_stopped = B_FALSE;
13341 				mutex_exit(QLOCK(q));
13342 				if (q->q_flag & QWANTW)
13343 					qbackenable(q, 0);
13344 			} else {
13345 				/* flow_stopped is left unchanged */
13346 				mutex_exit(QLOCK(q));
13347 			}
13348 		}
13349 	}
13350 
13351 	mutex_enter(&connp->conn_lock);
13352 	connp->conn_blocked = B_FALSE;
13353 	mutex_exit(&connp->conn_lock);
13354 }
13355 
13356 /*
13357  * Return the length in bytes of the IPv4 headers (base header, label, and
13358  * other IP options) that will be needed based on the
13359  * ip_pkt_t structure passed by the caller.
13360  *
13361  * The returned length does not include the length of the upper level
13362  * protocol (ULP) header.
13363  * The caller needs to check that the length doesn't exceed the max for IPv4.
13364  */
13365 int
13366 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13367 {
13368 	int len;
13369 
13370 	len = IP_SIMPLE_HDR_LENGTH;
13371 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13372 		ASSERT(ipp->ipp_label_len_v4 != 0);
13373 		/* We need to round up here */
13374 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13375 	}
13376 
13377 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13378 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13379 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13380 		len += ipp->ipp_ipv4_options_len;
13381 	}
13382 	return (len);
13383 }
13384 
13385 /*
13386  * All-purpose routine to build an IPv4 header with options based
13387  * on the abstract ip_pkt_t.
13388  *
13389  * The caller has to set the source and destination address as well as
13390  * ipha_length. The caller has to massage any source route and compensate
13391  * for the ULP pseudo-header checksum due to the source route.
13392  */
13393 void
13394 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13395     uint8_t protocol)
13396 {
13397 	ipha_t	*ipha = (ipha_t *)buf;
13398 	uint8_t *cp;
13399 
13400 	/* Initialize IPv4 header */
13401 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13402 	ipha->ipha_length = 0;	/* Caller will set later */
13403 	ipha->ipha_ident = 0;
13404 	ipha->ipha_fragment_offset_and_flags = 0;
13405 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13406 	ipha->ipha_protocol = protocol;
13407 	ipha->ipha_hdr_checksum = 0;
13408 
13409 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13410 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13411 		ipha->ipha_src = ipp->ipp_addr_v4;
13412 
13413 	cp = (uint8_t *)&ipha[1];
13414 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13415 		ASSERT(ipp->ipp_label_len_v4 != 0);
13416 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13417 		cp += ipp->ipp_label_len_v4;
13418 		/* We need to round up here */
13419 		while ((uintptr_t)cp & 0x3) {
13420 			*cp++ = IPOPT_NOP;
13421 		}
13422 	}
13423 
13424 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13425 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13426 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13427 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13428 		cp += ipp->ipp_ipv4_options_len;
13429 	}
13430 	ipha->ipha_version_and_hdr_length =
13431 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13432 
13433 	ASSERT((int)(cp - buf) == buf_len);
13434 }
13435 
13436 /* Allocate the private structure */
13437 static int
13438 ip_priv_alloc(void **bufp)
13439 {
13440 	void	*buf;
13441 
13442 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13443 		return (ENOMEM);
13444 
13445 	*bufp = buf;
13446 	return (0);
13447 }
13448 
13449 /* Function to delete the private structure */
13450 void
13451 ip_priv_free(void *buf)
13452 {
13453 	ASSERT(buf != NULL);
13454 	kmem_free(buf, sizeof (ip_priv_t));
13455 }
13456 
13457 /*
13458  * The entry point for IPPF processing.
13459  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13460  * routine just returns.
13461  *
13462  * When called, ip_process generates an ipp_packet_t structure
13463  * which holds the state information for this packet and invokes the
13464  * the classifier (via ipp_packet_process). The classification, depending on
13465  * configured filters, results in a list of actions for this packet. Invoking
13466  * an action may cause the packet to be dropped, in which case we return NULL.
13467  * proc indicates the callout position for
13468  * this packet and ill is the interface this packet arrived on or will leave
13469  * on (inbound and outbound resp.).
13470  *
13471  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13472  * on the ill corrsponding to the destination IP address.
13473  */
13474 mblk_t *
13475 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13476 {
13477 	ip_priv_t	*priv;
13478 	ipp_action_id_t	aid;
13479 	int		rc = 0;
13480 	ipp_packet_t	*pp;
13481 
13482 	/* If the classifier is not loaded, return  */
13483 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13484 		return (mp);
13485 	}
13486 
13487 	ASSERT(mp != NULL);
13488 
13489 	/* Allocate the packet structure */
13490 	rc = ipp_packet_alloc(&pp, "ip", aid);
13491 	if (rc != 0)
13492 		goto drop;
13493 
13494 	/* Allocate the private structure */
13495 	rc = ip_priv_alloc((void **)&priv);
13496 	if (rc != 0) {
13497 		ipp_packet_free(pp);
13498 		goto drop;
13499 	}
13500 	priv->proc = proc;
13501 	priv->ill_index = ill_get_upper_ifindex(rill);
13502 
13503 	ipp_packet_set_private(pp, priv, ip_priv_free);
13504 	ipp_packet_set_data(pp, mp);
13505 
13506 	/* Invoke the classifier */
13507 	rc = ipp_packet_process(&pp);
13508 	if (pp != NULL) {
13509 		mp = ipp_packet_get_data(pp);
13510 		ipp_packet_free(pp);
13511 		if (rc != 0)
13512 			goto drop;
13513 		return (mp);
13514 	} else {
13515 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13516 		mp = NULL;
13517 	}
13518 drop:
13519 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13520 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13521 		ip_drop_input("ip_process", mp, ill);
13522 	} else {
13523 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13524 		ip_drop_output("ip_process", mp, ill);
13525 	}
13526 	freemsg(mp);
13527 	return (NULL);
13528 }
13529 
13530 /*
13531  * Propagate a multicast group membership operation (add/drop) on
13532  * all the interfaces crossed by the related multirt routes.
13533  * The call is considered successful if the operation succeeds
13534  * on at least one interface.
13535  *
13536  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13537  * multicast addresses with the ire argument being the first one.
13538  * We walk the bucket to find all the of those.
13539  *
13540  * Common to IPv4 and IPv6.
13541  */
13542 static int
13543 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13544     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13545     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13546     mcast_record_t fmode, const in6_addr_t *v6src)
13547 {
13548 	ire_t		*ire_gw;
13549 	irb_t		*irb;
13550 	int		ifindex;
13551 	int		error = 0;
13552 	int		result;
13553 	ip_stack_t	*ipst = ire->ire_ipst;
13554 	ipaddr_t	group;
13555 	boolean_t	isv6;
13556 	int		match_flags;
13557 
13558 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13559 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13560 		isv6 = B_FALSE;
13561 	} else {
13562 		isv6 = B_TRUE;
13563 	}
13564 
13565 	irb = ire->ire_bucket;
13566 	ASSERT(irb != NULL);
13567 
13568 	result = 0;
13569 	irb_refhold(irb);
13570 	for (; ire != NULL; ire = ire->ire_next) {
13571 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13572 			continue;
13573 
13574 		/* We handle -ifp routes by matching on the ill if set */
13575 		match_flags = MATCH_IRE_TYPE;
13576 		if (ire->ire_ill != NULL)
13577 			match_flags |= MATCH_IRE_ILL;
13578 
13579 		if (isv6) {
13580 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13581 				continue;
13582 
13583 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13584 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13585 			    match_flags, 0, ipst, NULL);
13586 		} else {
13587 			if (ire->ire_addr != group)
13588 				continue;
13589 
13590 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13591 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13592 			    match_flags, 0, ipst, NULL);
13593 		}
13594 		/* No interface route exists for the gateway; skip this ire. */
13595 		if (ire_gw == NULL)
13596 			continue;
13597 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13598 			ire_refrele(ire_gw);
13599 			continue;
13600 		}
13601 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13602 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13603 
13604 		/*
13605 		 * The operation is considered a success if
13606 		 * it succeeds at least once on any one interface.
13607 		 */
13608 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13609 		    fmode, v6src);
13610 		if (error == 0)
13611 			result = CGTP_MCAST_SUCCESS;
13612 
13613 		ire_refrele(ire_gw);
13614 	}
13615 	irb_refrele(irb);
13616 	/*
13617 	 * Consider the call as successful if we succeeded on at least
13618 	 * one interface. Otherwise, return the last encountered error.
13619 	 */
13620 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13621 }
13622 
13623 /*
13624  * Return the expected CGTP hooks version number.
13625  */
13626 int
13627 ip_cgtp_filter_supported(void)
13628 {
13629 	return (ip_cgtp_filter_rev);
13630 }
13631 
13632 /*
13633  * CGTP hooks can be registered by invoking this function.
13634  * Checks that the version number matches.
13635  */
13636 int
13637 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13638 {
13639 	netstack_t *ns;
13640 	ip_stack_t *ipst;
13641 
13642 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13643 		return (ENOTSUP);
13644 
13645 	ns = netstack_find_by_stackid(stackid);
13646 	if (ns == NULL)
13647 		return (EINVAL);
13648 	ipst = ns->netstack_ip;
13649 	ASSERT(ipst != NULL);
13650 
13651 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13652 		netstack_rele(ns);
13653 		return (EALREADY);
13654 	}
13655 
13656 	ipst->ips_ip_cgtp_filter_ops = ops;
13657 
13658 	ill_set_inputfn_all(ipst);
13659 
13660 	netstack_rele(ns);
13661 	return (0);
13662 }
13663 
13664 /*
13665  * CGTP hooks can be unregistered by invoking this function.
13666  * Returns ENXIO if there was no registration.
13667  * Returns EBUSY if the ndd variable has not been turned off.
13668  */
13669 int
13670 ip_cgtp_filter_unregister(netstackid_t stackid)
13671 {
13672 	netstack_t *ns;
13673 	ip_stack_t *ipst;
13674 
13675 	ns = netstack_find_by_stackid(stackid);
13676 	if (ns == NULL)
13677 		return (EINVAL);
13678 	ipst = ns->netstack_ip;
13679 	ASSERT(ipst != NULL);
13680 
13681 	if (ipst->ips_ip_cgtp_filter) {
13682 		netstack_rele(ns);
13683 		return (EBUSY);
13684 	}
13685 
13686 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13687 		netstack_rele(ns);
13688 		return (ENXIO);
13689 	}
13690 	ipst->ips_ip_cgtp_filter_ops = NULL;
13691 
13692 	ill_set_inputfn_all(ipst);
13693 
13694 	netstack_rele(ns);
13695 	return (0);
13696 }
13697 
13698 /*
13699  * Check whether there is a CGTP filter registration.
13700  * Returns non-zero if there is a registration, otherwise returns zero.
13701  * Note: returns zero if bad stackid.
13702  */
13703 int
13704 ip_cgtp_filter_is_registered(netstackid_t stackid)
13705 {
13706 	netstack_t *ns;
13707 	ip_stack_t *ipst;
13708 	int ret;
13709 
13710 	ns = netstack_find_by_stackid(stackid);
13711 	if (ns == NULL)
13712 		return (0);
13713 	ipst = ns->netstack_ip;
13714 	ASSERT(ipst != NULL);
13715 
13716 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13717 		ret = 1;
13718 	else
13719 		ret = 0;
13720 
13721 	netstack_rele(ns);
13722 	return (ret);
13723 }
13724 
13725 static int
13726 ip_squeue_switch(int val)
13727 {
13728 	int rval;
13729 
13730 	switch (val) {
13731 	case IP_SQUEUE_ENTER_NODRAIN:
13732 		rval = SQ_NODRAIN;
13733 		break;
13734 	case IP_SQUEUE_ENTER:
13735 		rval = SQ_PROCESS;
13736 		break;
13737 	case IP_SQUEUE_FILL:
13738 	default:
13739 		rval = SQ_FILL;
13740 		break;
13741 	}
13742 	return (rval);
13743 }
13744 
13745 static void *
13746 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13747 {
13748 	kstat_t *ksp;
13749 
13750 	ip_stat_t template = {
13751 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
13752 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
13753 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
13754 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13755 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13756 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13757 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13758 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13759 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13760 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13761 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13762 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13763 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13764 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13765 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13766 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13767 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13768 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13769 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13770 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13771 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13772 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13773 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13774 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13775 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13776 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13777 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13778 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13779 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13780 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13781 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
13782 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
13783 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
13784 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
13785 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
13786 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
13787 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
13788 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
13789 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
13790 	};
13791 
13792 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13793 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13794 	    KSTAT_FLAG_VIRTUAL, stackid);
13795 
13796 	if (ksp == NULL)
13797 		return (NULL);
13798 
13799 	bcopy(&template, ip_statisticsp, sizeof (template));
13800 	ksp->ks_data = (void *)ip_statisticsp;
13801 	ksp->ks_private = (void *)(uintptr_t)stackid;
13802 
13803 	kstat_install(ksp);
13804 	return (ksp);
13805 }
13806 
13807 static void
13808 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13809 {
13810 	if (ksp != NULL) {
13811 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13812 		kstat_delete_netstack(ksp, stackid);
13813 	}
13814 }
13815 
13816 static void *
13817 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13818 {
13819 	kstat_t	*ksp;
13820 
13821 	ip_named_kstat_t template = {
13822 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
13823 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
13824 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
13825 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
13826 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
13827 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
13828 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
13829 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
13830 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
13831 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
13832 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
13833 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
13834 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
13835 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
13836 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
13837 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
13838 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
13839 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
13840 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
13841 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
13842 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
13843 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
13844 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
13845 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
13846 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
13847 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
13848 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
13849 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
13850 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
13851 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
13852 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
13853 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
13854 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
13855 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
13856 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
13857 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
13858 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
13859 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
13860 	};
13861 
13862 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
13863 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
13864 	if (ksp == NULL || ksp->ks_data == NULL)
13865 		return (NULL);
13866 
13867 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
13868 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
13869 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
13870 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
13871 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
13872 
13873 	template.netToMediaEntrySize.value.i32 =
13874 	    sizeof (mib2_ipNetToMediaEntry_t);
13875 
13876 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
13877 
13878 	bcopy(&template, ksp->ks_data, sizeof (template));
13879 	ksp->ks_update = ip_kstat_update;
13880 	ksp->ks_private = (void *)(uintptr_t)stackid;
13881 
13882 	kstat_install(ksp);
13883 	return (ksp);
13884 }
13885 
13886 static void
13887 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
13888 {
13889 	if (ksp != NULL) {
13890 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13891 		kstat_delete_netstack(ksp, stackid);
13892 	}
13893 }
13894 
13895 static int
13896 ip_kstat_update(kstat_t *kp, int rw)
13897 {
13898 	ip_named_kstat_t *ipkp;
13899 	mib2_ipIfStatsEntry_t ipmib;
13900 	ill_walk_context_t ctx;
13901 	ill_t *ill;
13902 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
13903 	netstack_t	*ns;
13904 	ip_stack_t	*ipst;
13905 
13906 	if (kp == NULL || kp->ks_data == NULL)
13907 		return (EIO);
13908 
13909 	if (rw == KSTAT_WRITE)
13910 		return (EACCES);
13911 
13912 	ns = netstack_find_by_stackid(stackid);
13913 	if (ns == NULL)
13914 		return (-1);
13915 	ipst = ns->netstack_ip;
13916 	if (ipst == NULL) {
13917 		netstack_rele(ns);
13918 		return (-1);
13919 	}
13920 	ipkp = (ip_named_kstat_t *)kp->ks_data;
13921 
13922 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
13923 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
13924 	ill = ILL_START_WALK_V4(&ctx, ipst);
13925 	for (; ill != NULL; ill = ill_next(&ctx, ill))
13926 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
13927 	rw_exit(&ipst->ips_ill_g_lock);
13928 
13929 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
13930 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
13931 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
13932 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
13933 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
13934 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
13935 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
13936 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
13937 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
13938 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
13939 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
13940 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
13941 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
13942 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
13943 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
13944 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
13945 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
13946 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
13947 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
13948 
13949 	ipkp->routingDiscards.value.ui32 =	0;
13950 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
13951 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
13952 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
13953 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
13954 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
13955 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
13956 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
13957 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
13958 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
13959 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
13960 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
13961 
13962 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
13963 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
13964 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
13965 
13966 	netstack_rele(ns);
13967 
13968 	return (0);
13969 }
13970 
13971 static void *
13972 icmp_kstat_init(netstackid_t stackid)
13973 {
13974 	kstat_t	*ksp;
13975 
13976 	icmp_named_kstat_t template = {
13977 		{ "inMsgs",		KSTAT_DATA_UINT32 },
13978 		{ "inErrors",		KSTAT_DATA_UINT32 },
13979 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
13980 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
13981 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
13982 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
13983 		{ "inRedirects",	KSTAT_DATA_UINT32 },
13984 		{ "inEchos",		KSTAT_DATA_UINT32 },
13985 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
13986 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
13987 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
13988 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
13989 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
13990 		{ "outMsgs",		KSTAT_DATA_UINT32 },
13991 		{ "outErrors",		KSTAT_DATA_UINT32 },
13992 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
13993 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
13994 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
13995 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
13996 		{ "outRedirects",	KSTAT_DATA_UINT32 },
13997 		{ "outEchos",		KSTAT_DATA_UINT32 },
13998 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
13999 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14000 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14001 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14002 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14003 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14004 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14005 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14006 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14007 		{ "outDrops",		KSTAT_DATA_UINT32 },
14008 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14009 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14010 	};
14011 
14012 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14013 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14014 	if (ksp == NULL || ksp->ks_data == NULL)
14015 		return (NULL);
14016 
14017 	bcopy(&template, ksp->ks_data, sizeof (template));
14018 
14019 	ksp->ks_update = icmp_kstat_update;
14020 	ksp->ks_private = (void *)(uintptr_t)stackid;
14021 
14022 	kstat_install(ksp);
14023 	return (ksp);
14024 }
14025 
14026 static void
14027 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14028 {
14029 	if (ksp != NULL) {
14030 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14031 		kstat_delete_netstack(ksp, stackid);
14032 	}
14033 }
14034 
14035 static int
14036 icmp_kstat_update(kstat_t *kp, int rw)
14037 {
14038 	icmp_named_kstat_t *icmpkp;
14039 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14040 	netstack_t	*ns;
14041 	ip_stack_t	*ipst;
14042 
14043 	if ((kp == NULL) || (kp->ks_data == NULL))
14044 		return (EIO);
14045 
14046 	if (rw == KSTAT_WRITE)
14047 		return (EACCES);
14048 
14049 	ns = netstack_find_by_stackid(stackid);
14050 	if (ns == NULL)
14051 		return (-1);
14052 	ipst = ns->netstack_ip;
14053 	if (ipst == NULL) {
14054 		netstack_rele(ns);
14055 		return (-1);
14056 	}
14057 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14058 
14059 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14060 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14061 	icmpkp->inDestUnreachs.value.ui32 =
14062 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14063 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14064 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14065 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14066 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14067 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14068 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14069 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14070 	icmpkp->inTimestampReps.value.ui32 =
14071 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14072 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14073 	icmpkp->inAddrMaskReps.value.ui32 =
14074 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14075 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14076 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14077 	icmpkp->outDestUnreachs.value.ui32 =
14078 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14079 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14080 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14081 	icmpkp->outSrcQuenchs.value.ui32 =
14082 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14083 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14084 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14085 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14086 	icmpkp->outTimestamps.value.ui32 =
14087 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14088 	icmpkp->outTimestampReps.value.ui32 =
14089 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14090 	icmpkp->outAddrMasks.value.ui32 =
14091 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14092 	icmpkp->outAddrMaskReps.value.ui32 =
14093 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14094 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14095 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14096 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14097 	icmpkp->outFragNeeded.value.ui32 =
14098 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14099 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14100 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14101 	icmpkp->inBadRedirects.value.ui32 =
14102 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14103 
14104 	netstack_rele(ns);
14105 	return (0);
14106 }
14107 
14108 /*
14109  * This is the fanout function for raw socket opened for SCTP.  Note
14110  * that it is called after SCTP checks that there is no socket which
14111  * wants a packet.  Then before SCTP handles this out of the blue packet,
14112  * this function is called to see if there is any raw socket for SCTP.
14113  * If there is and it is bound to the correct address, the packet will
14114  * be sent to that socket.  Note that only one raw socket can be bound to
14115  * a port.  This is assured in ipcl_sctp_hash_insert();
14116  */
14117 void
14118 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14119     ip_recv_attr_t *ira)
14120 {
14121 	conn_t		*connp;
14122 	queue_t		*rq;
14123 	boolean_t	secure;
14124 	ill_t		*ill = ira->ira_ill;
14125 	ip_stack_t	*ipst = ill->ill_ipst;
14126 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14127 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14128 	iaflags_t	iraflags = ira->ira_flags;
14129 	ill_t		*rill = ira->ira_rill;
14130 
14131 	secure = iraflags & IRAF_IPSEC_SECURE;
14132 
14133 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14134 	    ira, ipst);
14135 	if (connp == NULL) {
14136 		/*
14137 		 * Although raw sctp is not summed, OOB chunks must be.
14138 		 * Drop the packet here if the sctp checksum failed.
14139 		 */
14140 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14141 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
14142 			freemsg(mp);
14143 			return;
14144 		}
14145 		ira->ira_ill = ira->ira_rill = NULL;
14146 		sctp_ootb_input(mp, ira, ipst);
14147 		ira->ira_ill = ill;
14148 		ira->ira_rill = rill;
14149 		return;
14150 	}
14151 	rq = connp->conn_rq;
14152 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14153 		CONN_DEC_REF(connp);
14154 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14155 		freemsg(mp);
14156 		return;
14157 	}
14158 	if (((iraflags & IRAF_IS_IPV4) ?
14159 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14160 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14161 	    secure) {
14162 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14163 		    ip6h, ira);
14164 		if (mp == NULL) {
14165 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14166 			/* Note that mp is NULL */
14167 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14168 			CONN_DEC_REF(connp);
14169 			return;
14170 		}
14171 	}
14172 
14173 	if (iraflags & IRAF_ICMP_ERROR) {
14174 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14175 	} else {
14176 		ill_t *rill = ira->ira_rill;
14177 
14178 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14179 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14180 		ira->ira_ill = ira->ira_rill = NULL;
14181 		(connp->conn_recv)(connp, mp, NULL, ira);
14182 		ira->ira_ill = ill;
14183 		ira->ira_rill = rill;
14184 	}
14185 	CONN_DEC_REF(connp);
14186 }
14187 
14188 /*
14189  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14190  * header before the ip payload.
14191  */
14192 static void
14193 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14194 {
14195 	int len = (mp->b_wptr - mp->b_rptr);
14196 	mblk_t *ip_mp;
14197 
14198 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14199 	if (is_fp_mp || len != fp_mp_len) {
14200 		if (len > fp_mp_len) {
14201 			/*
14202 			 * fastpath header and ip header in the first mblk
14203 			 */
14204 			mp->b_rptr += fp_mp_len;
14205 		} else {
14206 			/*
14207 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14208 			 * attach the fastpath header before ip header.
14209 			 */
14210 			ip_mp = mp->b_cont;
14211 			freeb(mp);
14212 			mp = ip_mp;
14213 			mp->b_rptr += (fp_mp_len - len);
14214 		}
14215 	} else {
14216 		ip_mp = mp->b_cont;
14217 		freeb(mp);
14218 		mp = ip_mp;
14219 	}
14220 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14221 	freemsg(mp);
14222 }
14223 
14224 /*
14225  * Normal post fragmentation function.
14226  *
14227  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14228  * using the same state machine.
14229  *
14230  * We return an error on failure. In particular we return EWOULDBLOCK
14231  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14232  * (currently by canputnext failure resulting in backenabling from GLD.)
14233  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14234  * indication that they can flow control until ip_wsrv() tells then to restart.
14235  *
14236  * If the nce passed by caller is incomplete, this function
14237  * queues the packet and if necessary, sends ARP request and bails.
14238  * If the Neighbor Cache passed is fully resolved, we simply prepend
14239  * the link-layer header to the packet, do ipsec hw acceleration
14240  * work if necessary, and send the packet out on the wire.
14241  */
14242 /* ARGSUSED6 */
14243 int
14244 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14245     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14246 {
14247 	queue_t		*wq;
14248 	ill_t		*ill = nce->nce_ill;
14249 	ip_stack_t	*ipst = ill->ill_ipst;
14250 	uint64_t	delta;
14251 	boolean_t	isv6 = ill->ill_isv6;
14252 	boolean_t	fp_mp;
14253 	ncec_t		*ncec = nce->nce_common;
14254 	int64_t		now = LBOLT_FASTPATH64;
14255 	boolean_t	is_probe;
14256 
14257 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14258 
14259 	ASSERT(mp != NULL);
14260 	ASSERT(mp->b_datap->db_type == M_DATA);
14261 	ASSERT(pkt_len == msgdsize(mp));
14262 
14263 	/*
14264 	 * If we have already been here and are coming back after ARP/ND.
14265 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14266 	 * in that case since they have seen the packet when it came here
14267 	 * the first time.
14268 	 */
14269 	if (ixaflags & IXAF_NO_TRACE)
14270 		goto sendit;
14271 
14272 	if (ixaflags & IXAF_IS_IPV4) {
14273 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14274 
14275 		ASSERT(!isv6);
14276 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14277 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14278 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14279 			int	error;
14280 
14281 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14282 			    ipst->ips_ipv4firewall_physical_out,
14283 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14284 			DTRACE_PROBE1(ip4__physical__out__end,
14285 			    mblk_t *, mp);
14286 			if (mp == NULL)
14287 				return (error);
14288 
14289 			/* The length could have changed */
14290 			pkt_len = msgdsize(mp);
14291 		}
14292 		if (ipst->ips_ip4_observe.he_interested) {
14293 			/*
14294 			 * Note that for TX the zoneid is the sending
14295 			 * zone, whether or not MLP is in play.
14296 			 * Since the szone argument is the IP zoneid (i.e.,
14297 			 * zero for exclusive-IP zones) and ipobs wants
14298 			 * the system zoneid, we map it here.
14299 			 */
14300 			szone = IP_REAL_ZONEID(szone, ipst);
14301 
14302 			/*
14303 			 * On the outbound path the destination zone will be
14304 			 * unknown as we're sending this packet out on the
14305 			 * wire.
14306 			 */
14307 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14308 			    ill, ipst);
14309 		}
14310 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14311 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14312 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14313 	} else {
14314 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14315 
14316 		ASSERT(isv6);
14317 		ASSERT(pkt_len ==
14318 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14319 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14320 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14321 			int	error;
14322 
14323 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14324 			    ipst->ips_ipv6firewall_physical_out,
14325 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14326 			DTRACE_PROBE1(ip6__physical__out__end,
14327 			    mblk_t *, mp);
14328 			if (mp == NULL)
14329 				return (error);
14330 
14331 			/* The length could have changed */
14332 			pkt_len = msgdsize(mp);
14333 		}
14334 		if (ipst->ips_ip6_observe.he_interested) {
14335 			/* See above */
14336 			szone = IP_REAL_ZONEID(szone, ipst);
14337 
14338 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14339 			    ill, ipst);
14340 		}
14341 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14342 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14343 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14344 	}
14345 
14346 sendit:
14347 	/*
14348 	 * We check the state without a lock because the state can never
14349 	 * move "backwards" to initial or incomplete.
14350 	 */
14351 	switch (ncec->ncec_state) {
14352 	case ND_REACHABLE:
14353 	case ND_STALE:
14354 	case ND_DELAY:
14355 	case ND_PROBE:
14356 		mp = ip_xmit_attach_llhdr(mp, nce);
14357 		if (mp == NULL) {
14358 			/*
14359 			 * ip_xmit_attach_llhdr has increased
14360 			 * ipIfStatsOutDiscards and called ip_drop_output()
14361 			 */
14362 			return (ENOBUFS);
14363 		}
14364 		/*
14365 		 * check if nce_fastpath completed and we tagged on a
14366 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14367 		 */
14368 		fp_mp = (mp->b_datap->db_type == M_DATA);
14369 
14370 		if (fp_mp &&
14371 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14372 			ill_dld_direct_t *idd;
14373 
14374 			idd = &ill->ill_dld_capab->idc_direct;
14375 			/*
14376 			 * Send the packet directly to DLD, where it
14377 			 * may be queued depending on the availability
14378 			 * of transmit resources at the media layer.
14379 			 * Return value should be taken into
14380 			 * account and flow control the TCP.
14381 			 */
14382 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14383 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14384 			    pkt_len);
14385 
14386 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14387 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14388 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14389 			} else {
14390 				uintptr_t cookie;
14391 
14392 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14393 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14394 					if (ixacookie != NULL)
14395 						*ixacookie = cookie;
14396 					return (EWOULDBLOCK);
14397 				}
14398 			}
14399 		} else {
14400 			wq = ill->ill_wq;
14401 
14402 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14403 			    !canputnext(wq)) {
14404 				if (ixacookie != NULL)
14405 					*ixacookie = 0;
14406 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14407 				    nce->nce_fp_mp != NULL ?
14408 				    MBLKL(nce->nce_fp_mp) : 0);
14409 				return (EWOULDBLOCK);
14410 			}
14411 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14412 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14413 			    pkt_len);
14414 			putnext(wq, mp);
14415 		}
14416 
14417 		/*
14418 		 * The rest of this function implements Neighbor Unreachability
14419 		 * detection. Determine if the ncec is eligible for NUD.
14420 		 */
14421 		if (ncec->ncec_flags & NCE_F_NONUD)
14422 			return (0);
14423 
14424 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14425 
14426 		/*
14427 		 * Check for upper layer advice
14428 		 */
14429 		if (ixaflags & IXAF_REACH_CONF) {
14430 			timeout_id_t tid;
14431 
14432 			/*
14433 			 * It should be o.k. to check the state without
14434 			 * a lock here, at most we lose an advice.
14435 			 */
14436 			ncec->ncec_last = TICK_TO_MSEC(now);
14437 			if (ncec->ncec_state != ND_REACHABLE) {
14438 				mutex_enter(&ncec->ncec_lock);
14439 				ncec->ncec_state = ND_REACHABLE;
14440 				tid = ncec->ncec_timeout_id;
14441 				ncec->ncec_timeout_id = 0;
14442 				mutex_exit(&ncec->ncec_lock);
14443 				(void) untimeout(tid);
14444 				if (ip_debug > 2) {
14445 					/* ip1dbg */
14446 					pr_addr_dbg("ip_xmit: state"
14447 					    " for %s changed to"
14448 					    " REACHABLE\n", AF_INET6,
14449 					    &ncec->ncec_addr);
14450 				}
14451 			}
14452 			return (0);
14453 		}
14454 
14455 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14456 		ip1dbg(("ip_xmit: delta = %" PRId64
14457 		    " ill_reachable_time = %d \n", delta,
14458 		    ill->ill_reachable_time));
14459 		if (delta > (uint64_t)ill->ill_reachable_time) {
14460 			mutex_enter(&ncec->ncec_lock);
14461 			switch (ncec->ncec_state) {
14462 			case ND_REACHABLE:
14463 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14464 				/* FALLTHROUGH */
14465 			case ND_STALE:
14466 				/*
14467 				 * ND_REACHABLE is identical to
14468 				 * ND_STALE in this specific case. If
14469 				 * reachable time has expired for this
14470 				 * neighbor (delta is greater than
14471 				 * reachable time), conceptually, the
14472 				 * neighbor cache is no longer in
14473 				 * REACHABLE state, but already in
14474 				 * STALE state.  So the correct
14475 				 * transition here is to ND_DELAY.
14476 				 */
14477 				ncec->ncec_state = ND_DELAY;
14478 				mutex_exit(&ncec->ncec_lock);
14479 				nce_restart_timer(ncec,
14480 				    ipst->ips_delay_first_probe_time);
14481 				if (ip_debug > 3) {
14482 					/* ip2dbg */
14483 					pr_addr_dbg("ip_xmit: state"
14484 					    " for %s changed to"
14485 					    " DELAY\n", AF_INET6,
14486 					    &ncec->ncec_addr);
14487 				}
14488 				break;
14489 			case ND_DELAY:
14490 			case ND_PROBE:
14491 				mutex_exit(&ncec->ncec_lock);
14492 				/* Timers have already started */
14493 				break;
14494 			case ND_UNREACHABLE:
14495 				/*
14496 				 * nce_timer has detected that this ncec
14497 				 * is unreachable and initiated deleting
14498 				 * this ncec.
14499 				 * This is a harmless race where we found the
14500 				 * ncec before it was deleted and have
14501 				 * just sent out a packet using this
14502 				 * unreachable ncec.
14503 				 */
14504 				mutex_exit(&ncec->ncec_lock);
14505 				break;
14506 			default:
14507 				ASSERT(0);
14508 				mutex_exit(&ncec->ncec_lock);
14509 			}
14510 		}
14511 		return (0);
14512 
14513 	case ND_INCOMPLETE:
14514 		/*
14515 		 * the state could have changed since we didn't hold the lock.
14516 		 * Re-verify state under lock.
14517 		 */
14518 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14519 		mutex_enter(&ncec->ncec_lock);
14520 		if (NCE_ISREACHABLE(ncec)) {
14521 			mutex_exit(&ncec->ncec_lock);
14522 			goto sendit;
14523 		}
14524 		/* queue the packet */
14525 		nce_queue_mp(ncec, mp, is_probe);
14526 		mutex_exit(&ncec->ncec_lock);
14527 		DTRACE_PROBE2(ip__xmit__incomplete,
14528 		    (ncec_t *), ncec, (mblk_t *), mp);
14529 		return (0);
14530 
14531 	case ND_INITIAL:
14532 		/*
14533 		 * State could have changed since we didn't hold the lock, so
14534 		 * re-verify state.
14535 		 */
14536 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14537 		mutex_enter(&ncec->ncec_lock);
14538 		if (NCE_ISREACHABLE(ncec))  {
14539 			mutex_exit(&ncec->ncec_lock);
14540 			goto sendit;
14541 		}
14542 		nce_queue_mp(ncec, mp, is_probe);
14543 		if (ncec->ncec_state == ND_INITIAL) {
14544 			ncec->ncec_state = ND_INCOMPLETE;
14545 			mutex_exit(&ncec->ncec_lock);
14546 			/*
14547 			 * figure out the source we want to use
14548 			 * and resolve it.
14549 			 */
14550 			ip_ndp_resolve(ncec);
14551 		} else  {
14552 			mutex_exit(&ncec->ncec_lock);
14553 		}
14554 		return (0);
14555 
14556 	case ND_UNREACHABLE:
14557 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14558 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14559 		    mp, ill);
14560 		freemsg(mp);
14561 		return (0);
14562 
14563 	default:
14564 		ASSERT(0);
14565 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14566 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14567 		    mp, ill);
14568 		freemsg(mp);
14569 		return (ENETUNREACH);
14570 	}
14571 }
14572 
14573 /*
14574  * Return B_TRUE if the buffers differ in length or content.
14575  * This is used for comparing extension header buffers.
14576  * Note that an extension header would be declared different
14577  * even if all that changed was the next header value in that header i.e.
14578  * what really changed is the next extension header.
14579  */
14580 boolean_t
14581 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14582     uint_t blen)
14583 {
14584 	if (!b_valid)
14585 		blen = 0;
14586 
14587 	if (alen != blen)
14588 		return (B_TRUE);
14589 	if (alen == 0)
14590 		return (B_FALSE);	/* Both zero length */
14591 	return (bcmp(abuf, bbuf, alen));
14592 }
14593 
14594 /*
14595  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14596  * Return B_FALSE if memory allocation fails - don't change any state!
14597  */
14598 boolean_t
14599 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14600     const void *src, uint_t srclen)
14601 {
14602 	void *dst;
14603 
14604 	if (!src_valid)
14605 		srclen = 0;
14606 
14607 	ASSERT(*dstlenp == 0);
14608 	if (src != NULL && srclen != 0) {
14609 		dst = mi_alloc(srclen, BPRI_MED);
14610 		if (dst == NULL)
14611 			return (B_FALSE);
14612 	} else {
14613 		dst = NULL;
14614 	}
14615 	if (*dstp != NULL)
14616 		mi_free(*dstp);
14617 	*dstp = dst;
14618 	*dstlenp = dst == NULL ? 0 : srclen;
14619 	return (B_TRUE);
14620 }
14621 
14622 /*
14623  * Replace what is in *dst, *dstlen with the source.
14624  * Assumes ip_allocbuf has already been called.
14625  */
14626 void
14627 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14628     const void *src, uint_t srclen)
14629 {
14630 	if (!src_valid)
14631 		srclen = 0;
14632 
14633 	ASSERT(*dstlenp == srclen);
14634 	if (src != NULL && srclen != 0)
14635 		bcopy(src, *dstp, srclen);
14636 }
14637 
14638 /*
14639  * Free the storage pointed to by the members of an ip_pkt_t.
14640  */
14641 void
14642 ip_pkt_free(ip_pkt_t *ipp)
14643 {
14644 	uint_t	fields = ipp->ipp_fields;
14645 
14646 	if (fields & IPPF_HOPOPTS) {
14647 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14648 		ipp->ipp_hopopts = NULL;
14649 		ipp->ipp_hopoptslen = 0;
14650 	}
14651 	if (fields & IPPF_RTHDRDSTOPTS) {
14652 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14653 		ipp->ipp_rthdrdstopts = NULL;
14654 		ipp->ipp_rthdrdstoptslen = 0;
14655 	}
14656 	if (fields & IPPF_DSTOPTS) {
14657 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14658 		ipp->ipp_dstopts = NULL;
14659 		ipp->ipp_dstoptslen = 0;
14660 	}
14661 	if (fields & IPPF_RTHDR) {
14662 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14663 		ipp->ipp_rthdr = NULL;
14664 		ipp->ipp_rthdrlen = 0;
14665 	}
14666 	if (fields & IPPF_IPV4_OPTIONS) {
14667 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14668 		ipp->ipp_ipv4_options = NULL;
14669 		ipp->ipp_ipv4_options_len = 0;
14670 	}
14671 	if (fields & IPPF_LABEL_V4) {
14672 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14673 		ipp->ipp_label_v4 = NULL;
14674 		ipp->ipp_label_len_v4 = 0;
14675 	}
14676 	if (fields & IPPF_LABEL_V6) {
14677 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14678 		ipp->ipp_label_v6 = NULL;
14679 		ipp->ipp_label_len_v6 = 0;
14680 	}
14681 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14682 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14683 }
14684 
14685 /*
14686  * Copy from src to dst and allocate as needed.
14687  * Returns zero or ENOMEM.
14688  *
14689  * The caller must initialize dst to zero.
14690  */
14691 int
14692 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14693 {
14694 	uint_t	fields = src->ipp_fields;
14695 
14696 	/* Start with fields that don't require memory allocation */
14697 	dst->ipp_fields = fields &
14698 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14699 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14700 
14701 	dst->ipp_addr = src->ipp_addr;
14702 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14703 	dst->ipp_hoplimit = src->ipp_hoplimit;
14704 	dst->ipp_tclass = src->ipp_tclass;
14705 	dst->ipp_type_of_service = src->ipp_type_of_service;
14706 
14707 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14708 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14709 		return (0);
14710 
14711 	if (fields & IPPF_HOPOPTS) {
14712 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14713 		if (dst->ipp_hopopts == NULL) {
14714 			ip_pkt_free(dst);
14715 			return (ENOMEM);
14716 		}
14717 		dst->ipp_fields |= IPPF_HOPOPTS;
14718 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14719 		    src->ipp_hopoptslen);
14720 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14721 	}
14722 	if (fields & IPPF_RTHDRDSTOPTS) {
14723 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14724 		    kmflag);
14725 		if (dst->ipp_rthdrdstopts == NULL) {
14726 			ip_pkt_free(dst);
14727 			return (ENOMEM);
14728 		}
14729 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14730 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14731 		    src->ipp_rthdrdstoptslen);
14732 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14733 	}
14734 	if (fields & IPPF_DSTOPTS) {
14735 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14736 		if (dst->ipp_dstopts == NULL) {
14737 			ip_pkt_free(dst);
14738 			return (ENOMEM);
14739 		}
14740 		dst->ipp_fields |= IPPF_DSTOPTS;
14741 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14742 		    src->ipp_dstoptslen);
14743 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14744 	}
14745 	if (fields & IPPF_RTHDR) {
14746 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14747 		if (dst->ipp_rthdr == NULL) {
14748 			ip_pkt_free(dst);
14749 			return (ENOMEM);
14750 		}
14751 		dst->ipp_fields |= IPPF_RTHDR;
14752 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14753 		    src->ipp_rthdrlen);
14754 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14755 	}
14756 	if (fields & IPPF_IPV4_OPTIONS) {
14757 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14758 		    kmflag);
14759 		if (dst->ipp_ipv4_options == NULL) {
14760 			ip_pkt_free(dst);
14761 			return (ENOMEM);
14762 		}
14763 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14764 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14765 		    src->ipp_ipv4_options_len);
14766 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14767 	}
14768 	if (fields & IPPF_LABEL_V4) {
14769 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14770 		if (dst->ipp_label_v4 == NULL) {
14771 			ip_pkt_free(dst);
14772 			return (ENOMEM);
14773 		}
14774 		dst->ipp_fields |= IPPF_LABEL_V4;
14775 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14776 		    src->ipp_label_len_v4);
14777 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14778 	}
14779 	if (fields & IPPF_LABEL_V6) {
14780 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14781 		if (dst->ipp_label_v6 == NULL) {
14782 			ip_pkt_free(dst);
14783 			return (ENOMEM);
14784 		}
14785 		dst->ipp_fields |= IPPF_LABEL_V6;
14786 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14787 		    src->ipp_label_len_v6);
14788 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14789 	}
14790 	if (fields & IPPF_FRAGHDR) {
14791 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14792 		if (dst->ipp_fraghdr == NULL) {
14793 			ip_pkt_free(dst);
14794 			return (ENOMEM);
14795 		}
14796 		dst->ipp_fields |= IPPF_FRAGHDR;
14797 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14798 		    src->ipp_fraghdrlen);
14799 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14800 	}
14801 	return (0);
14802 }
14803 
14804 /*
14805  * Returns INADDR_ANY if no source route
14806  */
14807 ipaddr_t
14808 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14809 {
14810 	ipaddr_t	nexthop = INADDR_ANY;
14811 	ipoptp_t	opts;
14812 	uchar_t		*opt;
14813 	uint8_t		optval;
14814 	uint8_t		optlen;
14815 	uint32_t	totallen;
14816 
14817 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14818 		return (INADDR_ANY);
14819 
14820 	totallen = ipp->ipp_ipv4_options_len;
14821 	if (totallen & 0x3)
14822 		return (INADDR_ANY);
14823 
14824 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14825 	    optval != IPOPT_EOL;
14826 	    optval = ipoptp_next(&opts)) {
14827 		opt = opts.ipoptp_cur;
14828 		switch (optval) {
14829 			uint8_t off;
14830 		case IPOPT_SSRR:
14831 		case IPOPT_LSRR:
14832 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14833 				break;
14834 			}
14835 			optlen = opts.ipoptp_len;
14836 			off = opt[IPOPT_OFFSET];
14837 			off--;
14838 			if (optlen < IP_ADDR_LEN ||
14839 			    off > optlen - IP_ADDR_LEN) {
14840 				/* End of source route */
14841 				break;
14842 			}
14843 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
14844 			if (nexthop == htonl(INADDR_LOOPBACK)) {
14845 				/* Ignore */
14846 				nexthop = INADDR_ANY;
14847 				break;
14848 			}
14849 			break;
14850 		}
14851 	}
14852 	return (nexthop);
14853 }
14854 
14855 /*
14856  * Reverse a source route.
14857  */
14858 void
14859 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
14860 {
14861 	ipaddr_t	tmp;
14862 	ipoptp_t	opts;
14863 	uchar_t		*opt;
14864 	uint8_t		optval;
14865 	uint32_t	totallen;
14866 
14867 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14868 		return;
14869 
14870 	totallen = ipp->ipp_ipv4_options_len;
14871 	if (totallen & 0x3)
14872 		return;
14873 
14874 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14875 	    optval != IPOPT_EOL;
14876 	    optval = ipoptp_next(&opts)) {
14877 		uint8_t off1, off2;
14878 
14879 		opt = opts.ipoptp_cur;
14880 		switch (optval) {
14881 		case IPOPT_SSRR:
14882 		case IPOPT_LSRR:
14883 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14884 				break;
14885 			}
14886 			off1 = IPOPT_MINOFF_SR - 1;
14887 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
14888 			while (off2 > off1) {
14889 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
14890 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
14891 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
14892 				off2 -= IP_ADDR_LEN;
14893 				off1 += IP_ADDR_LEN;
14894 			}
14895 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
14896 			break;
14897 		}
14898 	}
14899 }
14900 
14901 /*
14902  * Returns NULL if no routing header
14903  */
14904 in6_addr_t *
14905 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
14906 {
14907 	in6_addr_t	*nexthop = NULL;
14908 	ip6_rthdr0_t	*rthdr;
14909 
14910 	if (!(ipp->ipp_fields & IPPF_RTHDR))
14911 		return (NULL);
14912 
14913 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
14914 	if (rthdr->ip6r0_segleft == 0)
14915 		return (NULL);
14916 
14917 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
14918 	return (nexthop);
14919 }
14920 
14921 zoneid_t
14922 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
14923     zoneid_t lookup_zoneid)
14924 {
14925 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
14926 	ire_t		*ire;
14927 	int		ire_flags = MATCH_IRE_TYPE;
14928 	zoneid_t	zoneid = ALL_ZONES;
14929 
14930 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
14931 		return (ALL_ZONES);
14932 
14933 	if (lookup_zoneid != ALL_ZONES)
14934 		ire_flags |= MATCH_IRE_ZONEONLY;
14935 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
14936 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
14937 	if (ire != NULL) {
14938 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
14939 		ire_refrele(ire);
14940 	}
14941 	return (zoneid);
14942 }
14943 
14944 zoneid_t
14945 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
14946     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
14947 {
14948 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
14949 	ire_t		*ire;
14950 	int		ire_flags = MATCH_IRE_TYPE;
14951 	zoneid_t	zoneid = ALL_ZONES;
14952 
14953 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
14954 		return (ALL_ZONES);
14955 
14956 	if (IN6_IS_ADDR_LINKLOCAL(addr))
14957 		ire_flags |= MATCH_IRE_ILL;
14958 
14959 	if (lookup_zoneid != ALL_ZONES)
14960 		ire_flags |= MATCH_IRE_ZONEONLY;
14961 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
14962 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
14963 	if (ire != NULL) {
14964 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
14965 		ire_refrele(ire);
14966 	}
14967 	return (zoneid);
14968 }
14969 
14970 /*
14971  * IP obserability hook support functions.
14972  */
14973 static void
14974 ipobs_init(ip_stack_t *ipst)
14975 {
14976 	netid_t id;
14977 
14978 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
14979 
14980 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
14981 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
14982 
14983 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
14984 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
14985 }
14986 
14987 static void
14988 ipobs_fini(ip_stack_t *ipst)
14989 {
14990 
14991 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
14992 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
14993 }
14994 
14995 /*
14996  * hook_pkt_observe_t is composed in network byte order so that the
14997  * entire mblk_t chain handed into hook_run can be used as-is.
14998  * The caveat is that use of the fields, such as the zone fields,
14999  * requires conversion into host byte order first.
15000  */
15001 void
15002 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15003     const ill_t *ill, ip_stack_t *ipst)
15004 {
15005 	hook_pkt_observe_t *hdr;
15006 	uint64_t grifindex;
15007 	mblk_t *imp;
15008 
15009 	imp = allocb(sizeof (*hdr), BPRI_HI);
15010 	if (imp == NULL)
15011 		return;
15012 
15013 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15014 	/*
15015 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15016 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15017 	 */
15018 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15019 	imp->b_cont = mp;
15020 
15021 	ASSERT(DB_TYPE(mp) == M_DATA);
15022 
15023 	if (IS_UNDER_IPMP(ill))
15024 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15025 	else
15026 		grifindex = 0;
15027 
15028 	hdr->hpo_version = 1;
15029 	hdr->hpo_htype = htons(htype);
15030 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15031 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15032 	hdr->hpo_grifindex = htonl(grifindex);
15033 	hdr->hpo_zsrc = htonl(zsrc);
15034 	hdr->hpo_zdst = htonl(zdst);
15035 	hdr->hpo_pkt = imp;
15036 	hdr->hpo_ctx = ipst->ips_netstack;
15037 
15038 	if (ill->ill_isv6) {
15039 		hdr->hpo_family = AF_INET6;
15040 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15041 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15042 	} else {
15043 		hdr->hpo_family = AF_INET;
15044 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15045 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15046 	}
15047 
15048 	imp->b_cont = NULL;
15049 	freemsg(imp);
15050 }
15051 
15052 /*
15053  * Utility routine that checks if `v4srcp' is a valid address on underlying
15054  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15055  * associated with `v4srcp' on success.  NOTE: if this is not called from
15056  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15057  * group during or after this lookup.
15058  */
15059 boolean_t
15060 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15061 {
15062 	ipif_t *ipif;
15063 
15064 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15065 	if (ipif != NULL) {
15066 		if (ipifp != NULL)
15067 			*ipifp = ipif;
15068 		else
15069 			ipif_refrele(ipif);
15070 		return (B_TRUE);
15071 	}
15072 
15073 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15074 	    *v4srcp));
15075 	return (B_FALSE);
15076 }
15077