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