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