xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision 8e30ce7b864214c672f5378abebdcce0490c47ec)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 1990 Mentat Inc.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/stream.h>
29 #include <sys/dlpi.h>
30 #include <sys/stropts.h>
31 #include <sys/sysmacros.h>
32 #include <sys/strsubr.h>
33 #include <sys/strlog.h>
34 #include <sys/strsun.h>
35 #include <sys/zone.h>
36 #define	_SUN_TPI_VERSION 2
37 #include <sys/tihdr.h>
38 #include <sys/xti_inet.h>
39 #include <sys/ddi.h>
40 #include <sys/suntpi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/sadb.h>
98 #include <inet/ipsec_impl.h>
99 #include <inet/iptun/iptun_impl.h>
100 #include <inet/ipdrop.h>
101 #include <inet/ip_netinfo.h>
102 #include <inet/ilb_ip.h>
103 
104 #include <sys/ethernet.h>
105 #include <net/if_types.h>
106 #include <sys/cpuvar.h>
107 
108 #include <ipp/ipp.h>
109 #include <ipp/ipp_impl.h>
110 #include <ipp/ipgpc/ipgpc.h>
111 
112 #include <sys/pattr.h>
113 #include <inet/ipclassifier.h>
114 #include <inet/sctp_ip.h>
115 #include <inet/sctp/sctp_impl.h>
116 #include <inet/udp_impl.h>
117 #include <inet/rawip_impl.h>
118 #include <inet/rts_impl.h>
119 
120 #include <sys/tsol/label.h>
121 #include <sys/tsol/tnet.h>
122 
123 #include <sys/squeue_impl.h>
124 #include <inet/ip_arp.h>
125 
126 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
131  * IP_SQUEUE_ENTER: SQ_PROCESS
132  * IP_SQUEUE_FILL: SQ_FILL
133  */
134 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
135 
136 int ip_squeue_flag;
137 
138 /*
139  * Setable in /etc/system
140  */
141 int ip_poll_normal_ms = 100;
142 int ip_poll_normal_ticks = 0;
143 int ip_modclose_ackwait_ms = 3000;
144 
145 /*
146  * It would be nice to have these present only in DEBUG systems, but the
147  * current design of the global symbol checking logic requires them to be
148  * unconditionally present.
149  */
150 uint_t ip_thread_data;			/* TSD key for debug support */
151 krwlock_t ip_thread_rwlock;
152 list_t	ip_thread_list;
153 
154 /*
155  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
156  */
157 
158 struct listptr_s {
159 	mblk_t	*lp_head;	/* pointer to the head of the list */
160 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
161 };
162 
163 typedef struct listptr_s listptr_t;
164 
165 /*
166  * This is used by ip_snmp_get_mib2_ip_route_media and
167  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
168  */
169 typedef struct iproutedata_s {
170 	uint_t		ird_idx;
171 	uint_t		ird_flags;	/* see below */
172 	listptr_t	ird_route;	/* ipRouteEntryTable */
173 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
174 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
175 } iproutedata_t;
176 
177 /* Include ire_testhidden and IRE_IF_CLONE routes */
178 #define	IRD_REPORT_ALL	0x01
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
199     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
200     void *args) = NULL;
201 
202 /*
203  * Hook function to generate cluster wide SPI.
204  */
205 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
206     void *) = NULL;
207 
208 /*
209  * Hook function to verify if the SPI is already utlized.
210  */
211 
212 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
213 
214 /*
215  * Hook function to delete the SPI from the cluster wide repository.
216  */
217 
218 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
219 
220 /*
221  * Hook function to inform the cluster when packet received on an IDLE SA
222  */
223 
224 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
225     in6_addr_t, in6_addr_t, void *) = NULL;
226 
227 /*
228  * Synchronization notes:
229  *
230  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
231  * MT level protection given by STREAMS. IP uses a combination of its own
232  * internal serialization mechanism and standard Solaris locking techniques.
233  * The internal serialization is per phyint.  This is used to serialize
234  * plumbing operations, IPMP operations, most set ioctls, etc.
235  *
236  * Plumbing is a long sequence of operations involving message
237  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
238  * involved in plumbing operations. A natural model is to serialize these
239  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
240  * parallel without any interference. But various set ioctls on hme0 are best
241  * serialized, along with IPMP operations and processing of DLPI control
242  * messages received from drivers on a per phyint basis. This serialization is
243  * provided by the ipsq_t and primitives operating on this. Details can
244  * be found in ip_if.c above the core primitives operating on ipsq_t.
245  *
246  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
247  * Simiarly lookup of an ire by a thread also returns a refheld ire.
248  * In addition ipif's and ill's referenced by the ire are also indirectly
249  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
250  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
251  * address of an ipif has to go through the ipsq_t. This ensures that only
252  * one such exclusive operation proceeds at any time on the ipif. It then
253  * waits for all refcnts
254  * associated with this ipif to come down to zero. The address is changed
255  * only after the ipif has been quiesced. Then the ipif is brought up again.
256  * More details are described above the comment in ip_sioctl_flags.
257  *
258  * Packet processing is based mostly on IREs and are fully multi-threaded
259  * using standard Solaris MT techniques.
260  *
261  * There are explicit locks in IP to handle:
262  * - The ip_g_head list maintained by mi_open_link() and friends.
263  *
264  * - The reassembly data structures (one lock per hash bucket)
265  *
266  * - conn_lock is meant to protect conn_t fields. The fields actually
267  *   protected by conn_lock are documented in the conn_t definition.
268  *
269  * - ire_lock to protect some of the fields of the ire, IRE tables
270  *   (one lock per hash bucket). Refer to ip_ire.c for details.
271  *
272  * - ndp_g_lock and ncec_lock for protecting NCEs.
273  *
274  * - ill_lock protects fields of the ill and ipif. Details in ip.h
275  *
276  * - ill_g_lock: This is a global reader/writer lock. Protects the following
277  *	* The AVL tree based global multi list of all ills.
278  *	* The linked list of all ipifs of an ill
279  *	* The <ipsq-xop> mapping
280  *	* <ill-phyint> association
281  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
282  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
283  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
284  *   writer for the actual duration of the insertion/deletion/change.
285  *
286  * - ill_lock:  This is a per ill mutex.
287  *   It protects some members of the ill_t struct; see ip.h for details.
288  *   It also protects the <ill-phyint> assoc.
289  *   It also protects the list of ipifs hanging off the ill.
290  *
291  * - ipsq_lock: This is a per ipsq_t mutex lock.
292  *   This protects some members of the ipsq_t struct; see ip.h for details.
293  *   It also protects the <ipsq-ipxop> mapping
294  *
295  * - ipx_lock: This is a per ipxop_t mutex lock.
296  *   This protects some members of the ipxop_t struct; see ip.h for details.
297  *
298  * - phyint_lock: This is a per phyint mutex lock. Protects just the
299  *   phyint_flags
300  *
301  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
302  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
303  *   uniqueness check also done atomically.
304  *
305  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
306  *   group list linked by ill_usesrc_grp_next. It also protects the
307  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
308  *   group is being added or deleted.  This lock is taken as a reader when
309  *   walking the list/group(eg: to get the number of members in a usesrc group).
310  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
311  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
312  *   example, it is not necessary to take this lock in the initial portion
313  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
314  *   operations are executed exclusively and that ensures that the "usesrc
315  *   group state" cannot change. The "usesrc group state" change can happen
316  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ipsq-xop> assocications:
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ipsq-xop> association, the ill_g_lock must be held as
325  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
326  * This is only done when ills are added or removed from IPMP groups.
327  *
328  * To add or delete an ipif from the list of ipifs hanging off the ill,
329  * ill_g_lock (writer) and ill_lock must be held and the thread must be
330  * a writer on the associated ipsq.
331  *
332  * To add or delete an ill to the system, the ill_g_lock must be held as
333  * writer and the thread must be a writer on the associated ipsq.
334  *
335  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
336  * must be a writer on the associated ipsq.
337  *
338  * Lock hierarchy
339  *
340  * Some lock hierarchy scenarios are listed below.
341  *
342  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
343  * ill_g_lock -> ill_lock(s) -> phyint_lock
344  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
345  * ill_g_lock -> ip_addr_avail_lock
346  * conn_lock -> irb_lock -> ill_lock -> ire_lock
347  * ill_g_lock -> ip_g_nd_lock
348  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
350  * arl_lock -> ill_lock
351  * ips_ire_dep_lock -> irb_lock
352  *
353  * When more than 1 ill lock is needed to be held, all ill lock addresses
354  * are sorted on address and locked starting from highest addressed lock
355  * downward.
356  *
357  * Multicast scenarios
358  * ips_ill_g_lock -> ill_mcast_lock
359  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
360  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
361  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
362  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
363  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
364  *
365  * IPsec scenarios
366  *
367  * ipsa_lock -> ill_g_lock -> ill_lock
368  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
369  *
370  * Trusted Solaris scenarios
371  *
372  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
373  * igsa_lock -> gcdb_lock
374  * gcgrp_rwlock -> ire_lock
375  * gcgrp_rwlock -> gcdb_lock
376  *
377  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
378  *
379  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
380  * sq_lock -> conn_lock -> QLOCK(q)
381  * ill_lock -> ft_lock -> fe_lock
382  *
383  * Routing/forwarding table locking notes:
384  *
385  * Lock acquisition order: Radix tree lock, irb_lock.
386  * Requirements:
387  * i.  Walker must not hold any locks during the walker callback.
388  * ii  Walker must not see a truncated tree during the walk because of any node
389  *     deletion.
390  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
391  *     in many places in the code to walk the irb list. Thus even if all the
392  *     ires in a bucket have been deleted, we still can't free the radix node
393  *     until the ires have actually been inactive'd (freed).
394  *
395  * Tree traversal - Need to hold the global tree lock in read mode.
396  * Before dropping the global tree lock, need to either increment the ire_refcnt
397  * to ensure that the radix node can't be deleted.
398  *
399  * Tree add - Need to hold the global tree lock in write mode to add a
400  * radix node. To prevent the node from being deleted, increment the
401  * irb_refcnt, after the node is added to the tree. The ire itself is
402  * added later while holding the irb_lock, but not the tree lock.
403  *
404  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
405  * All associated ires must be inactive (i.e. freed), and irb_refcnt
406  * must be zero.
407  *
408  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
409  * global tree lock (read mode) for traversal.
410  *
411  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
412  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
413  *
414  * IPsec notes :
415  *
416  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
417  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
418  * ip_xmit_attr_t has the
419  * information used by the IPsec code for applying the right level of
420  * protection. The information initialized by IP in the ip_xmit_attr_t
421  * is determined by the per-socket policy or global policy in the system.
422  * For inbound datagrams, the ip_recv_attr_t
423  * starts out with nothing in it. It gets filled
424  * with the right information if it goes through the AH/ESP code, which
425  * happens if the incoming packet is secure. The information initialized
426  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
427  * the policy requirements needed by per-socket policy or global policy
428  * is met or not.
429  *
430  * For fully connected sockets i.e dst, src [addr, port] is known,
431  * conn_policy_cached is set indicating that policy has been cached.
432  * conn_in_enforce_policy may or may not be set depending on whether
433  * there is a global policy match or per-socket policy match.
434  * Policy inheriting happpens in ip_policy_set once the destination is known.
435  * Once the right policy is set on the conn_t, policy cannot change for
436  * this socket. This makes life simpler for TCP (UDP ?) where
437  * re-transmissions go out with the same policy. For symmetry, policy
438  * is cached for fully connected UDP sockets also. Thus if policy is cached,
439  * it also implies that policy is latched i.e policy cannot change
440  * on these sockets. As we have the right policy on the conn, we don't
441  * have to lookup global policy for every outbound and inbound datagram
442  * and thus serving as an optimization. Note that a global policy change
443  * does not affect fully connected sockets if they have policy. If fully
444  * connected sockets did not have any policy associated with it, global
445  * policy change may affect them.
446  *
447  * IP Flow control notes:
448  * ---------------------
449  * Non-TCP streams are flow controlled by IP. The way this is accomplished
450  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
451  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
452  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
453  * functions.
454  *
455  * Per Tx ring udp flow control:
456  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
457  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
458  *
459  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
460  * To achieve best performance, outgoing traffic need to be fanned out among
461  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
462  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
463  * the address of connp as fanout hint to mac_tx(). Under flow controlled
464  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
465  * cookie points to a specific Tx ring that is blocked. The cookie is used to
466  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
467  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
468  * connp's. The drain list is not a single list but a configurable number of
469  * lists.
470  *
471  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
472  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
473  * which is equal to 128. This array in turn contains a pointer to idl_t[],
474  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
475  * list will point to the list of connp's that are flow controlled.
476  *
477  *                      ---------------   -------   -------   -------
478  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
479  *                   |  ---------------   -------   -------   -------
480  *                   |  ---------------   -------   -------   -------
481  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
482  * ----------------  |  ---------------   -------   -------   -------
483  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
484  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   .        .              .         .         .
487  *                   |  ---------------   -------   -------   -------
488  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
489  *                      ---------------   -------   -------   -------
490  *                      ---------------   -------   -------   -------
491  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
492  *                   |  ---------------   -------   -------   -------
493  *                   |  ---------------   -------   -------   -------
494  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
495  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
496  * ----------------  |        .              .         .         .
497  *                   |  ---------------   -------   -------   -------
498  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
499  *                      ---------------   -------   -------   -------
500  *     .....
501  * ----------------
502  * |idl_tx_list[n]|-> ...
503  * ----------------
504  *
505  * When mac_tx() returns a cookie, the cookie is hashed into an index into
506  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
507  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
508  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
509  * Further, conn_blocked is set to indicate that the conn is blocked.
510  *
511  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
512  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
513  * is again hashed to locate the appropriate idl_tx_list, which is then
514  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
515  * the drain list and calls conn_drain_remove() to clear flow control (via
516  * calling su_txq_full() or clearing QFULL), and remove the conn from the
517  * drain list.
518  *
519  * Note that the drain list is not a single list but a (configurable) array of
520  * lists (8 elements by default).  Synchronization between drain insertion and
521  * flow control wakeup is handled by using idl_txl->txl_lock, and only
522  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
523  *
524  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
525  * On the send side, if the packet cannot be sent down to the driver by IP
526  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
527  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
528  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
529  * control has been relieved, the blocked conns in the 0'th drain list are
530  * drained as in the non-STREAMS case.
531  *
532  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
533  * is done when the conn is inserted into the drain list (conn_drain_insert())
534  * and cleared when the conn is removed from the it (conn_drain_remove()).
535  *
536  * IPQOS notes:
537  *
538  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
539  * and IPQoS modules. IPPF includes hooks in IP at different control points
540  * (callout positions) which direct packets to IPQoS modules for policy
541  * processing. Policies, if present, are global.
542  *
543  * The callout positions are located in the following paths:
544  *		o local_in (packets destined for this host)
545  *		o local_out (packets orginating from this host )
546  *		o fwd_in  (packets forwarded by this m/c - inbound)
547  *		o fwd_out (packets forwarded by this m/c - outbound)
548  * Hooks at these callout points can be enabled/disabled using the ndd variable
549  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
550  * By default all the callout positions are enabled.
551  *
552  * Outbound (local_out)
553  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
554  *
555  * Inbound (local_in)
556  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
557  *
558  * Forwarding (in and out)
559  * Hooks are placed in ire_recv_forward_v4/v6.
560  *
561  * IP Policy Framework processing (IPPF processing)
562  * Policy processing for a packet is initiated by ip_process, which ascertains
563  * that the classifier (ipgpc) is loaded and configured, failing which the
564  * packet resumes normal processing in IP. If the clasifier is present, the
565  * packet is acted upon by one or more IPQoS modules (action instances), per
566  * filters configured in ipgpc and resumes normal IP processing thereafter.
567  * An action instance can drop a packet in course of its processing.
568  *
569  * Zones notes:
570  *
571  * The partitioning rules for networking are as follows:
572  * 1) Packets coming from a zone must have a source address belonging to that
573  * zone.
574  * 2) Packets coming from a zone can only be sent on a physical interface on
575  * which the zone has an IP address.
576  * 3) Between two zones on the same machine, packet delivery is only allowed if
577  * there's a matching route for the destination and zone in the forwarding
578  * table.
579  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
580  * different zones can bind to the same port with the wildcard address
581  * (INADDR_ANY).
582  *
583  * The granularity of interface partitioning is at the logical interface level.
584  * Therefore, every zone has its own IP addresses, and incoming packets can be
585  * attributed to a zone unambiguously. A logical interface is placed into a zone
586  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
587  * structure. Rule (1) is implemented by modifying the source address selection
588  * algorithm so that the list of eligible addresses is filtered based on the
589  * sending process zone.
590  *
591  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
592  * across all zones, depending on their type. Here is the break-up:
593  *
594  * IRE type				Shared/exclusive
595  * --------				----------------
596  * IRE_BROADCAST			Exclusive
597  * IRE_DEFAULT (default routes)		Shared (*)
598  * IRE_LOCAL				Exclusive (x)
599  * IRE_LOOPBACK				Exclusive
600  * IRE_PREFIX (net routes)		Shared (*)
601  * IRE_IF_NORESOLVER (interface routes)	Exclusive
602  * IRE_IF_RESOLVER (interface routes)	Exclusive
603  * IRE_IF_CLONE (interface routes)	Exclusive
604  * IRE_HOST (host routes)		Shared (*)
605  *
606  * (*) A zone can only use a default or off-subnet route if the gateway is
607  * directly reachable from the zone, that is, if the gateway's address matches
608  * one of the zone's logical interfaces.
609  *
610  * (x) IRE_LOCAL are handled a bit differently.
611  * When ip_restrict_interzone_loopback is set (the default),
612  * ire_route_recursive restricts loopback using an IRE_LOCAL
613  * between zone to the case when L2 would have conceptually looped the packet
614  * back, i.e. the loopback which is required since neither Ethernet drivers
615  * nor Ethernet hardware loops them back. This is the case when the normal
616  * routes (ignoring IREs with different zoneids) would send out the packet on
617  * the same ill as the ill with which is IRE_LOCAL is associated.
618  *
619  * Multiple zones can share a common broadcast address; typically all zones
620  * share the 255.255.255.255 address. Incoming as well as locally originated
621  * broadcast packets must be dispatched to all the zones on the broadcast
622  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
623  * since some zones may not be on the 10.16.72/24 network. To handle this, each
624  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
625  * sent to every zone that has an IRE_BROADCAST entry for the destination
626  * address on the input ill, see ip_input_broadcast().
627  *
628  * Applications in different zones can join the same multicast group address.
629  * The same logic applies for multicast as for broadcast. ip_input_multicast
630  * dispatches packets to all zones that have members on the physical interface.
631  */
632 
633 /*
634  * Squeue Fanout flags:
635  *	0: No fanout.
636  *	1: Fanout across all squeues
637  */
638 boolean_t	ip_squeue_fanout = 0;
639 
640 /*
641  * Maximum dups allowed per packet.
642  */
643 uint_t ip_max_frag_dups = 10;
644 
645 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
646 		    cred_t *credp, boolean_t isv6);
647 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
648 
649 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
650 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
651 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
652     ip_recv_attr_t *);
653 static void	icmp_options_update(ipha_t *);
654 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
655 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
656 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
657 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
658     ip_recv_attr_t *);
659 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
660 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
661     ip_recv_attr_t *);
662 
663 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
664 char		*ip_dot_addr(ipaddr_t, char *);
665 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
666 int		ip_close(queue_t *, int);
667 static char	*ip_dot_saddr(uchar_t *, char *);
668 static void	ip_lrput(queue_t *, mblk_t *);
669 ipaddr_t	ip_net_mask(ipaddr_t);
670 char		*ip_nv_lookup(nv_t *, int);
671 void	ip_rput(queue_t *, mblk_t *);
672 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
673 		    void *dummy_arg);
674 int		ip_snmp_get(queue_t *, mblk_t *, int);
675 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
676 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
678 		    ip_stack_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
680 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
703 		    ip_stack_t *ipst);
704 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
705 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
706 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
707 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
708 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
709 
710 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
711 		    mblk_t *);
712 
713 static void	conn_drain_init(ip_stack_t *);
714 static void	conn_drain_fini(ip_stack_t *);
715 static void	conn_drain(conn_t *connp, boolean_t closing);
716 
717 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
718 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
719 
720 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
721 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
722 static void	ip_stack_fini(netstackid_t stackid, void *arg);
723 
724 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
725     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
726     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
727     const in6_addr_t *);
728 
729 static int	ip_squeue_switch(int);
730 
731 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
732 static void	ip_kstat_fini(netstackid_t, kstat_t *);
733 static int	ip_kstat_update(kstat_t *kp, int rw);
734 static void	*icmp_kstat_init(netstackid_t);
735 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
736 static int	icmp_kstat_update(kstat_t *kp, int rw);
737 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
738 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
739 
740 static void	ipobs_init(ip_stack_t *);
741 static void	ipobs_fini(ip_stack_t *);
742 
743 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
744 
745 static long ip_rput_pullups;
746 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
747 
748 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
749 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
750 
751 int	ip_debug;
752 
753 /*
754  * Multirouting/CGTP stuff
755  */
756 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
757 
758 /*
759  * IP tunables related declarations. Definitions are in ip_tunables.c
760  */
761 extern mod_prop_info_t ip_propinfo_tbl[];
762 extern int ip_propinfo_count;
763 
764 /*
765  * Table of IP ioctls encoding the various properties of the ioctl and
766  * indexed based on the last byte of the ioctl command. Occasionally there
767  * is a clash, and there is more than 1 ioctl with the same last byte.
768  * In such a case 1 ioctl is encoded in the ndx table and the remaining
769  * ioctls are encoded in the misc table. An entry in the ndx table is
770  * retrieved by indexing on the last byte of the ioctl command and comparing
771  * the ioctl command with the value in the ndx table. In the event of a
772  * mismatch the misc table is then searched sequentially for the desired
773  * ioctl command.
774  *
775  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
776  */
777 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
778 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
779 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
780 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
781 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
782 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
783 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
784 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
785 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
786 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
787 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
788 
789 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
790 			MISC_CMD, ip_siocaddrt, NULL },
791 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
792 			MISC_CMD, ip_siocdelrt, NULL },
793 
794 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
795 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
796 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
797 			IF_CMD, ip_sioctl_get_addr, NULL },
798 
799 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
800 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
801 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
802 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
803 
804 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
805 			IPI_PRIV | IPI_WR,
806 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
807 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
808 			IPI_MODOK | IPI_GET_CMD,
809 			IF_CMD, ip_sioctl_get_flags, NULL },
810 
811 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
812 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
813 
814 	/* copyin size cannot be coded for SIOCGIFCONF */
815 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
816 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
817 
818 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
819 			IF_CMD, ip_sioctl_mtu, NULL },
820 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
821 			IF_CMD, ip_sioctl_get_mtu, NULL },
822 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
823 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
824 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
825 			IF_CMD, ip_sioctl_brdaddr, NULL },
826 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
827 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
828 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
829 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
830 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
831 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
832 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
833 			IF_CMD, ip_sioctl_metric, NULL },
834 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
835 
836 	/* See 166-168 below for extended SIOC*XARP ioctls */
837 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
838 			ARP_CMD, ip_sioctl_arp, NULL },
839 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
840 			ARP_CMD, ip_sioctl_arp, NULL },
841 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
842 			ARP_CMD, ip_sioctl_arp, NULL },
843 
844 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
845 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
846 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
847 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
848 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
849 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
850 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
851 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
852 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
853 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
854 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
855 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
856 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
857 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
858 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
859 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
860 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
861 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
862 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
863 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
864 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
865 
866 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
867 			MISC_CMD, if_unitsel, if_unitsel_restart },
868 
869 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
870 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
871 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
872 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
873 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
874 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
875 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
876 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
877 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
878 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
879 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
880 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
881 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
882 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
883 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
884 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
885 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
886 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
887 
888 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
889 			IPI_PRIV | IPI_WR | IPI_MODOK,
890 			IF_CMD, ip_sioctl_sifname, NULL },
891 
892 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
893 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
894 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
895 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
896 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
897 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
898 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
899 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
900 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
901 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
902 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
903 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
904 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
905 
906 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
907 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
908 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
909 			IF_CMD, ip_sioctl_get_muxid, NULL },
910 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
911 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
912 
913 	/* Both if and lif variants share same func */
914 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
915 			IF_CMD, ip_sioctl_get_lifindex, NULL },
916 	/* Both if and lif variants share same func */
917 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
918 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
919 
920 	/* copyin size cannot be coded for SIOCGIFCONF */
921 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
922 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
923 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
924 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
925 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
926 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
927 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
928 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
929 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
930 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
931 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
932 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
933 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
934 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
935 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
936 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
937 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
938 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
939 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
940 
941 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
942 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
943 			ip_sioctl_removeif_restart },
944 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
945 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
946 			LIF_CMD, ip_sioctl_addif, NULL },
947 #define	SIOCLIFADDR_NDX 112
948 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
949 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
950 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
951 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
952 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
953 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
954 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
955 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
956 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
957 			IPI_PRIV | IPI_WR,
958 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
959 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
960 			IPI_GET_CMD | IPI_MODOK,
961 			LIF_CMD, ip_sioctl_get_flags, NULL },
962 
963 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
964 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
965 
966 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
967 			ip_sioctl_get_lifconf, NULL },
968 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
969 			LIF_CMD, ip_sioctl_mtu, NULL },
970 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
971 			LIF_CMD, ip_sioctl_get_mtu, NULL },
972 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
973 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
974 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
975 			LIF_CMD, ip_sioctl_brdaddr, NULL },
976 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
977 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
978 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
979 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
980 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
981 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
982 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
983 			LIF_CMD, ip_sioctl_metric, NULL },
984 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
985 			IPI_PRIV | IPI_WR | IPI_MODOK,
986 			LIF_CMD, ip_sioctl_slifname,
987 			ip_sioctl_slifname_restart },
988 
989 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
990 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
991 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
992 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
993 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
994 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
995 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
996 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
997 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
998 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
999 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1000 			LIF_CMD, ip_sioctl_token, NULL },
1001 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1002 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1003 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1004 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1005 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1006 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1007 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1008 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1009 
1010 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1011 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1012 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1013 			LIF_CMD, ip_siocdelndp_v6, NULL },
1014 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1015 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1016 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1017 			LIF_CMD, ip_siocsetndp_v6, NULL },
1018 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1019 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1020 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1021 			MISC_CMD, ip_sioctl_tonlink, NULL },
1022 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1023 			MISC_CMD, ip_sioctl_tmysite, NULL },
1024 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1027 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1028 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1029 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1030 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1031 
1032 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 
1034 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1035 			LIF_CMD, ip_sioctl_get_binding, NULL },
1036 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1037 			IPI_PRIV | IPI_WR,
1038 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1039 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1040 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1041 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1042 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1043 
1044 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1045 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 
1049 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 
1051 	/* These are handled in ip_sioctl_copyin_setup itself */
1052 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1053 			MISC_CMD, NULL, NULL },
1054 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1055 			MISC_CMD, NULL, NULL },
1056 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1057 
1058 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1059 			ip_sioctl_get_lifconf, NULL },
1060 
1061 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1062 			XARP_CMD, ip_sioctl_arp, NULL },
1063 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1064 			XARP_CMD, ip_sioctl_arp, NULL },
1065 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1066 			XARP_CMD, ip_sioctl_arp, NULL },
1067 
1068 	/* SIOCPOPSOCKFS is not handled by IP */
1069 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1070 
1071 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1072 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1073 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1074 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1075 			ip_sioctl_slifzone_restart },
1076 	/* 172-174 are SCTP ioctls and not handled by IP */
1077 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1081 			IPI_GET_CMD, LIF_CMD,
1082 			ip_sioctl_get_lifusesrc, 0 },
1083 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1084 			IPI_PRIV | IPI_WR,
1085 			LIF_CMD, ip_sioctl_slifusesrc,
1086 			NULL },
1087 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1088 			ip_sioctl_get_lifsrcof, NULL },
1089 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1090 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1091 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1092 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1093 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1094 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1095 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1096 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1097 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* SIOCSENABLESDP is handled by SDP */
1099 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1100 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1101 	/* 185 */ { IPI_DONTCARE /* SIOCGIFHWADDR */, 0, 0, 0, NULL, NULL },
1102 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1103 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1104 			ip_sioctl_ilb_cmd, NULL },
1105 	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1106 	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1107 	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1108 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1109 	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1110 			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart }
1111 };
1112 
1113 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1114 
1115 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1116 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1117 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1118 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1119 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1120 	{ ND_GET,	0, 0, 0, NULL, NULL },
1121 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1122 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1123 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1124 		MISC_CMD, mrt_ioctl},
1125 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1126 		MISC_CMD, mrt_ioctl},
1127 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1128 		MISC_CMD, mrt_ioctl}
1129 };
1130 
1131 int ip_misc_ioctl_count =
1132     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1133 
1134 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1135 					/* Settable in /etc/system */
1136 /* Defined in ip_ire.c */
1137 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1138 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1139 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1140 
1141 static nv_t	ire_nv_arr[] = {
1142 	{ IRE_BROADCAST, "BROADCAST" },
1143 	{ IRE_LOCAL, "LOCAL" },
1144 	{ IRE_LOOPBACK, "LOOPBACK" },
1145 	{ IRE_DEFAULT, "DEFAULT" },
1146 	{ IRE_PREFIX, "PREFIX" },
1147 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1148 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1149 	{ IRE_IF_CLONE, "IF_CLONE" },
1150 	{ IRE_HOST, "HOST" },
1151 	{ IRE_MULTICAST, "MULTICAST" },
1152 	{ IRE_NOROUTE, "NOROUTE" },
1153 	{ 0 }
1154 };
1155 
1156 nv_t	*ire_nv_tbl = ire_nv_arr;
1157 
1158 /* Simple ICMP IP Header Template */
1159 static ipha_t icmp_ipha = {
1160 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1161 };
1162 
1163 struct module_info ip_mod_info = {
1164 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1165 	IP_MOD_LOWAT
1166 };
1167 
1168 /*
1169  * Duplicate static symbols within a module confuses mdb; so we avoid the
1170  * problem by making the symbols here distinct from those in udp.c.
1171  */
1172 
1173 /*
1174  * Entry points for IP as a device and as a module.
1175  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1176  */
1177 static struct qinit iprinitv4 = {
1178 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1179 	&ip_mod_info
1180 };
1181 
1182 struct qinit iprinitv6 = {
1183 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1184 	&ip_mod_info
1185 };
1186 
1187 static struct qinit ipwinit = {
1188 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1189 	&ip_mod_info
1190 };
1191 
1192 static struct qinit iplrinit = {
1193 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1194 	&ip_mod_info
1195 };
1196 
1197 static struct qinit iplwinit = {
1198 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1199 	&ip_mod_info
1200 };
1201 
1202 /* For AF_INET aka /dev/ip */
1203 struct streamtab ipinfov4 = {
1204 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1205 };
1206 
1207 /* For AF_INET6 aka /dev/ip6 */
1208 struct streamtab ipinfov6 = {
1209 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1210 };
1211 
1212 #ifdef	DEBUG
1213 boolean_t skip_sctp_cksum = B_FALSE;
1214 #endif
1215 
1216 /*
1217  * Generate an ICMP fragmentation needed message.
1218  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1219  * constructed by the caller.
1220  */
1221 void
1222 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1223 {
1224 	icmph_t	icmph;
1225 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1226 
1227 	mp = icmp_pkt_err_ok(mp, ira);
1228 	if (mp == NULL)
1229 		return;
1230 
1231 	bzero(&icmph, sizeof (icmph_t));
1232 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1233 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1234 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1235 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1236 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1237 
1238 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1239 }
1240 
1241 /*
1242  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1243  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1244  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1245  * Likewise, if the ICMP error is misformed (too short, etc), then it
1246  * returns NULL. The caller uses this to determine whether or not to send
1247  * to raw sockets.
1248  *
1249  * All error messages are passed to the matching transport stream.
1250  *
1251  * The following cases are handled by icmp_inbound:
1252  * 1) It needs to send a reply back and possibly delivering it
1253  *    to the "interested" upper clients.
1254  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1255  * 3) It needs to change some values in IP only.
1256  * 4) It needs to change some values in IP and upper layers e.g TCP
1257  *    by delivering an error to the upper layers.
1258  *
1259  * We handle the above three cases in the context of IPsec in the
1260  * following way :
1261  *
1262  * 1) Send the reply back in the same way as the request came in.
1263  *    If it came in encrypted, it goes out encrypted. If it came in
1264  *    clear, it goes out in clear. Thus, this will prevent chosen
1265  *    plain text attack.
1266  * 2) The client may or may not expect things to come in secure.
1267  *    If it comes in secure, the policy constraints are checked
1268  *    before delivering it to the upper layers. If it comes in
1269  *    clear, ipsec_inbound_accept_clear will decide whether to
1270  *    accept this in clear or not. In both the cases, if the returned
1271  *    message (IP header + 8 bytes) that caused the icmp message has
1272  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1273  *    sending up. If there are only 8 bytes of returned message, then
1274  *    upper client will not be notified.
1275  * 3) Check with global policy to see whether it matches the constaints.
1276  *    But this will be done only if icmp_accept_messages_in_clear is
1277  *    zero.
1278  * 4) If we need to change both in IP and ULP, then the decision taken
1279  *    while affecting the values in IP and while delivering up to TCP
1280  *    should be the same.
1281  *
1282  * 	There are two cases.
1283  *
1284  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1285  *	   failed), we will not deliver it to the ULP, even though they
1286  *	   are *willing* to accept in *clear*. This is fine as our global
1287  *	   disposition to icmp messages asks us reject the datagram.
1288  *
1289  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1290  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1291  *	   to deliver it to ULP (policy failed), it can lead to
1292  *	   consistency problems. The cases known at this time are
1293  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1294  *	   values :
1295  *
1296  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1297  *	     and Upper layer rejects. Then the communication will
1298  *	     come to a stop. This is solved by making similar decisions
1299  *	     at both levels. Currently, when we are unable to deliver
1300  *	     to the Upper Layer (due to policy failures) while IP has
1301  *	     adjusted dce_pmtu, the next outbound datagram would
1302  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1303  *	     will be with the right level of protection. Thus the right
1304  *	     value will be communicated even if we are not able to
1305  *	     communicate when we get from the wire initially. But this
1306  *	     assumes there would be at least one outbound datagram after
1307  *	     IP has adjusted its dce_pmtu value. To make things
1308  *	     simpler, we accept in clear after the validation of
1309  *	     AH/ESP headers.
1310  *
1311  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1312  *	     upper layer depending on the level of protection the upper
1313  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1314  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1315  *	     should be accepted in clear when the Upper layer expects secure.
1316  *	     Thus the communication may get aborted by some bad ICMP
1317  *	     packets.
1318  */
1319 mblk_t *
1320 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1321 {
1322 	icmph_t		*icmph;
1323 	ipha_t		*ipha;		/* Outer header */
1324 	int		ip_hdr_length;	/* Outer header length */
1325 	boolean_t	interested;
1326 	ipif_t		*ipif;
1327 	uint32_t	ts;
1328 	uint32_t	*tsp;
1329 	timestruc_t	now;
1330 	ill_t		*ill = ira->ira_ill;
1331 	ip_stack_t	*ipst = ill->ill_ipst;
1332 	zoneid_t	zoneid = ira->ira_zoneid;
1333 	int		len_needed;
1334 	mblk_t		*mp_ret = NULL;
1335 
1336 	ipha = (ipha_t *)mp->b_rptr;
1337 
1338 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1339 
1340 	ip_hdr_length = ira->ira_ip_hdr_length;
1341 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1342 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1343 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1344 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1345 			freemsg(mp);
1346 			return (NULL);
1347 		}
1348 		/* Last chance to get real. */
1349 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1350 		if (ipha == NULL) {
1351 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1352 			freemsg(mp);
1353 			return (NULL);
1354 		}
1355 	}
1356 
1357 	/* The IP header will always be a multiple of four bytes */
1358 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1359 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1360 	    icmph->icmph_code));
1361 
1362 	/*
1363 	 * We will set "interested" to "true" if we should pass a copy to
1364 	 * the transport or if we handle the packet locally.
1365 	 */
1366 	interested = B_FALSE;
1367 	switch (icmph->icmph_type) {
1368 	case ICMP_ECHO_REPLY:
1369 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1370 		break;
1371 	case ICMP_DEST_UNREACHABLE:
1372 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1373 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1374 		interested = B_TRUE;	/* Pass up to transport */
1375 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1376 		break;
1377 	case ICMP_SOURCE_QUENCH:
1378 		interested = B_TRUE;	/* Pass up to transport */
1379 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1380 		break;
1381 	case ICMP_REDIRECT:
1382 		if (!ipst->ips_ip_ignore_redirect)
1383 			interested = B_TRUE;
1384 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1385 		break;
1386 	case ICMP_ECHO_REQUEST:
1387 		/*
1388 		 * Whether to respond to echo requests that come in as IP
1389 		 * broadcasts or as IP multicast is subject to debate
1390 		 * (what isn't?).  We aim to please, you pick it.
1391 		 * Default is do it.
1392 		 */
1393 		if (ira->ira_flags & IRAF_MULTICAST) {
1394 			/* multicast: respond based on tunable */
1395 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1396 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1397 			/* broadcast: respond based on tunable */
1398 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1399 		} else {
1400 			/* unicast: always respond */
1401 			interested = B_TRUE;
1402 		}
1403 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1404 		if (!interested) {
1405 			/* We never pass these to RAW sockets */
1406 			freemsg(mp);
1407 			return (NULL);
1408 		}
1409 
1410 		/* Check db_ref to make sure we can modify the packet. */
1411 		if (mp->b_datap->db_ref > 1) {
1412 			mblk_t	*mp1;
1413 
1414 			mp1 = copymsg(mp);
1415 			freemsg(mp);
1416 			if (!mp1) {
1417 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1418 				return (NULL);
1419 			}
1420 			mp = mp1;
1421 			ipha = (ipha_t *)mp->b_rptr;
1422 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1423 		}
1424 		icmph->icmph_type = ICMP_ECHO_REPLY;
1425 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1426 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1427 		return (NULL);
1428 
1429 	case ICMP_ROUTER_ADVERTISEMENT:
1430 	case ICMP_ROUTER_SOLICITATION:
1431 		break;
1432 	case ICMP_TIME_EXCEEDED:
1433 		interested = B_TRUE;	/* Pass up to transport */
1434 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1435 		break;
1436 	case ICMP_PARAM_PROBLEM:
1437 		interested = B_TRUE;	/* Pass up to transport */
1438 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1439 		break;
1440 	case ICMP_TIME_STAMP_REQUEST:
1441 		/* Response to Time Stamp Requests is local policy. */
1442 		if (ipst->ips_ip_g_resp_to_timestamp) {
1443 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1444 				interested =
1445 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1446 			else
1447 				interested = B_TRUE;
1448 		}
1449 		if (!interested) {
1450 			/* We never pass these to RAW sockets */
1451 			freemsg(mp);
1452 			return (NULL);
1453 		}
1454 
1455 		/* Make sure we have enough of the packet */
1456 		len_needed = ip_hdr_length + ICMPH_SIZE +
1457 		    3 * sizeof (uint32_t);
1458 
1459 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1460 			ipha = ip_pullup(mp, len_needed, ira);
1461 			if (ipha == NULL) {
1462 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1463 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1464 				    mp, ill);
1465 				freemsg(mp);
1466 				return (NULL);
1467 			}
1468 			/* Refresh following the pullup. */
1469 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1470 		}
1471 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1472 		/* Check db_ref to make sure we can modify the packet. */
1473 		if (mp->b_datap->db_ref > 1) {
1474 			mblk_t	*mp1;
1475 
1476 			mp1 = copymsg(mp);
1477 			freemsg(mp);
1478 			if (!mp1) {
1479 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1480 				return (NULL);
1481 			}
1482 			mp = mp1;
1483 			ipha = (ipha_t *)mp->b_rptr;
1484 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1485 		}
1486 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1487 		tsp = (uint32_t *)&icmph[1];
1488 		tsp++;		/* Skip past 'originate time' */
1489 		/* Compute # of milliseconds since midnight */
1490 		gethrestime(&now);
1491 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1492 		    now.tv_nsec / (NANOSEC / MILLISEC);
1493 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1494 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1495 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1496 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1497 		return (NULL);
1498 
1499 	case ICMP_TIME_STAMP_REPLY:
1500 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1501 		break;
1502 	case ICMP_INFO_REQUEST:
1503 		/* Per RFC 1122 3.2.2.7, ignore this. */
1504 	case ICMP_INFO_REPLY:
1505 		break;
1506 	case ICMP_ADDRESS_MASK_REQUEST:
1507 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1508 			interested =
1509 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1510 		} else {
1511 			interested = B_TRUE;
1512 		}
1513 		if (!interested) {
1514 			/* We never pass these to RAW sockets */
1515 			freemsg(mp);
1516 			return (NULL);
1517 		}
1518 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1519 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1520 			ipha = ip_pullup(mp, len_needed, ira);
1521 			if (ipha == NULL) {
1522 				BUMP_MIB(ill->ill_ip_mib,
1523 				    ipIfStatsInTruncatedPkts);
1524 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1525 				    ill);
1526 				freemsg(mp);
1527 				return (NULL);
1528 			}
1529 			/* Refresh following the pullup. */
1530 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1531 		}
1532 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1533 		/* Check db_ref to make sure we can modify the packet. */
1534 		if (mp->b_datap->db_ref > 1) {
1535 			mblk_t	*mp1;
1536 
1537 			mp1 = copymsg(mp);
1538 			freemsg(mp);
1539 			if (!mp1) {
1540 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1541 				return (NULL);
1542 			}
1543 			mp = mp1;
1544 			ipha = (ipha_t *)mp->b_rptr;
1545 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1546 		}
1547 		/*
1548 		 * Need the ipif with the mask be the same as the source
1549 		 * address of the mask reply. For unicast we have a specific
1550 		 * ipif. For multicast/broadcast we only handle onlink
1551 		 * senders, and use the source address to pick an ipif.
1552 		 */
1553 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1554 		if (ipif == NULL) {
1555 			/* Broadcast or multicast */
1556 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1557 			if (ipif == NULL) {
1558 				freemsg(mp);
1559 				return (NULL);
1560 			}
1561 		}
1562 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1563 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1564 		ipif_refrele(ipif);
1565 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1566 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1567 		return (NULL);
1568 
1569 	case ICMP_ADDRESS_MASK_REPLY:
1570 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1571 		break;
1572 	default:
1573 		interested = B_TRUE;	/* Pass up to transport */
1574 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1575 		break;
1576 	}
1577 	/*
1578 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1579 	 * if there isn't one.
1580 	 */
1581 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1582 		/* If there is an ICMP client and we want one too, copy it. */
1583 
1584 		if (!interested) {
1585 			/* Caller will deliver to RAW sockets */
1586 			return (mp);
1587 		}
1588 		mp_ret = copymsg(mp);
1589 		if (mp_ret == NULL) {
1590 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1591 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1592 		}
1593 	} else if (!interested) {
1594 		/* Neither we nor raw sockets are interested. Drop packet now */
1595 		freemsg(mp);
1596 		return (NULL);
1597 	}
1598 
1599 	/*
1600 	 * ICMP error or redirect packet. Make sure we have enough of
1601 	 * the header and that db_ref == 1 since we might end up modifying
1602 	 * the packet.
1603 	 */
1604 	if (mp->b_cont != NULL) {
1605 		if (ip_pullup(mp, -1, ira) == NULL) {
1606 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1607 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1608 			    mp, ill);
1609 			freemsg(mp);
1610 			return (mp_ret);
1611 		}
1612 	}
1613 
1614 	if (mp->b_datap->db_ref > 1) {
1615 		mblk_t	*mp1;
1616 
1617 		mp1 = copymsg(mp);
1618 		if (mp1 == NULL) {
1619 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1620 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1621 			freemsg(mp);
1622 			return (mp_ret);
1623 		}
1624 		freemsg(mp);
1625 		mp = mp1;
1626 	}
1627 
1628 	/*
1629 	 * In case mp has changed, verify the message before any further
1630 	 * processes.
1631 	 */
1632 	ipha = (ipha_t *)mp->b_rptr;
1633 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1634 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1635 		freemsg(mp);
1636 		return (mp_ret);
1637 	}
1638 
1639 	switch (icmph->icmph_type) {
1640 	case ICMP_REDIRECT:
1641 		icmp_redirect_v4(mp, ipha, icmph, ira);
1642 		break;
1643 	case ICMP_DEST_UNREACHABLE:
1644 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1645 			/* Update DCE and adjust MTU is icmp header if needed */
1646 			icmp_inbound_too_big_v4(icmph, ira);
1647 		}
1648 		/* FALLTHRU */
1649 	default:
1650 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1651 		break;
1652 	}
1653 	return (mp_ret);
1654 }
1655 
1656 /*
1657  * Send an ICMP echo, timestamp or address mask reply.
1658  * The caller has already updated the payload part of the packet.
1659  * We handle the ICMP checksum, IP source address selection and feed
1660  * the packet into ip_output_simple.
1661  */
1662 static void
1663 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1664     ip_recv_attr_t *ira)
1665 {
1666 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1667 	ill_t		*ill = ira->ira_ill;
1668 	ip_stack_t	*ipst = ill->ill_ipst;
1669 	ip_xmit_attr_t	ixas;
1670 
1671 	/* Send out an ICMP packet */
1672 	icmph->icmph_checksum = 0;
1673 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1674 	/* Reset time to live. */
1675 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1676 	{
1677 		/* Swap source and destination addresses */
1678 		ipaddr_t tmp;
1679 
1680 		tmp = ipha->ipha_src;
1681 		ipha->ipha_src = ipha->ipha_dst;
1682 		ipha->ipha_dst = tmp;
1683 	}
1684 	ipha->ipha_ident = 0;
1685 	if (!IS_SIMPLE_IPH(ipha))
1686 		icmp_options_update(ipha);
1687 
1688 	bzero(&ixas, sizeof (ixas));
1689 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1690 	ixas.ixa_zoneid = ira->ira_zoneid;
1691 	ixas.ixa_cred = kcred;
1692 	ixas.ixa_cpid = NOPID;
1693 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1694 	ixas.ixa_ifindex = 0;
1695 	ixas.ixa_ipst = ipst;
1696 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1697 
1698 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1699 		/*
1700 		 * This packet should go out the same way as it
1701 		 * came in i.e in clear, independent of the IPsec policy
1702 		 * for transmitting packets.
1703 		 */
1704 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1705 	} else {
1706 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1707 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1708 			/* Note: mp already consumed and ip_drop_packet done */
1709 			return;
1710 		}
1711 	}
1712 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1713 		/*
1714 		 * Not one or our addresses (IRE_LOCALs), thus we let
1715 		 * ip_output_simple pick the source.
1716 		 */
1717 		ipha->ipha_src = INADDR_ANY;
1718 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1719 	}
1720 	/* Should we send with DF and use dce_pmtu? */
1721 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1722 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1723 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1724 	}
1725 
1726 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1727 
1728 	(void) ip_output_simple(mp, &ixas);
1729 	ixa_cleanup(&ixas);
1730 }
1731 
1732 /*
1733  * Verify the ICMP messages for either for ICMP error or redirect packet.
1734  * The caller should have fully pulled up the message. If it's a redirect
1735  * packet, only basic checks on IP header will be done; otherwise, verify
1736  * the packet by looking at the included ULP header.
1737  *
1738  * Called before icmp_inbound_error_fanout_v4 is called.
1739  */
1740 static boolean_t
1741 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1742 {
1743 	ill_t		*ill = ira->ira_ill;
1744 	int		hdr_length;
1745 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1746 	conn_t		*connp;
1747 	ipha_t		*ipha;	/* Inner IP header */
1748 
1749 	ipha = (ipha_t *)&icmph[1];
1750 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1751 		goto truncated;
1752 
1753 	hdr_length = IPH_HDR_LENGTH(ipha);
1754 
1755 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1756 		goto discard_pkt;
1757 
1758 	if (hdr_length < sizeof (ipha_t))
1759 		goto truncated;
1760 
1761 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1762 		goto truncated;
1763 
1764 	/*
1765 	 * Stop here for ICMP_REDIRECT.
1766 	 */
1767 	if (icmph->icmph_type == ICMP_REDIRECT)
1768 		return (B_TRUE);
1769 
1770 	/*
1771 	 * ICMP errors only.
1772 	 */
1773 	switch (ipha->ipha_protocol) {
1774 	case IPPROTO_UDP:
1775 		/*
1776 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1777 		 * transport header.
1778 		 */
1779 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1780 		    mp->b_wptr)
1781 			goto truncated;
1782 		break;
1783 	case IPPROTO_TCP: {
1784 		tcpha_t		*tcpha;
1785 
1786 		/*
1787 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1788 		 * transport header.
1789 		 */
1790 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1791 		    mp->b_wptr)
1792 			goto truncated;
1793 
1794 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1795 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1796 		    ipst);
1797 		if (connp == NULL)
1798 			goto discard_pkt;
1799 
1800 		if ((connp->conn_verifyicmp != NULL) &&
1801 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1802 			CONN_DEC_REF(connp);
1803 			goto discard_pkt;
1804 		}
1805 		CONN_DEC_REF(connp);
1806 		break;
1807 	}
1808 	case IPPROTO_SCTP:
1809 		/*
1810 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1811 		 * transport header.
1812 		 */
1813 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1814 		    mp->b_wptr)
1815 			goto truncated;
1816 		break;
1817 	case IPPROTO_ESP:
1818 	case IPPROTO_AH:
1819 		break;
1820 	case IPPROTO_ENCAP:
1821 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1822 		    mp->b_wptr)
1823 			goto truncated;
1824 		break;
1825 	default:
1826 		break;
1827 	}
1828 
1829 	return (B_TRUE);
1830 
1831 discard_pkt:
1832 	/* Bogus ICMP error. */
1833 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1834 	return (B_FALSE);
1835 
1836 truncated:
1837 	/* We pulled up everthing already. Must be truncated */
1838 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1839 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1840 	return (B_FALSE);
1841 }
1842 
1843 /* Table from RFC 1191 */
1844 static int icmp_frag_size_table[] =
1845 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1846 
1847 /*
1848  * Process received ICMP Packet too big.
1849  * Just handles the DCE create/update, including using the above table of
1850  * PMTU guesses. The caller is responsible for validating the packet before
1851  * passing it in and also to fanout the ICMP error to any matching transport
1852  * conns. Assumes the message has been fully pulled up and verified.
1853  *
1854  * Before getting here, the caller has called icmp_inbound_verify_v4()
1855  * that should have verified with ULP to prevent undoing the changes we're
1856  * going to make to DCE. For example, TCP might have verified that the packet
1857  * which generated error is in the send window.
1858  *
1859  * In some cases modified this MTU in the ICMP header packet; the caller
1860  * should pass to the matching ULP after this returns.
1861  */
1862 static void
1863 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1864 {
1865 	dce_t		*dce;
1866 	int		old_mtu;
1867 	int		mtu, orig_mtu;
1868 	ipaddr_t	dst;
1869 	boolean_t	disable_pmtud;
1870 	ill_t		*ill = ira->ira_ill;
1871 	ip_stack_t	*ipst = ill->ill_ipst;
1872 	uint_t		hdr_length;
1873 	ipha_t		*ipha;
1874 
1875 	/* Caller already pulled up everything. */
1876 	ipha = (ipha_t *)&icmph[1];
1877 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1878 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1879 	ASSERT(ill != NULL);
1880 
1881 	hdr_length = IPH_HDR_LENGTH(ipha);
1882 
1883 	/*
1884 	 * We handle path MTU for source routed packets since the DCE
1885 	 * is looked up using the final destination.
1886 	 */
1887 	dst = ip_get_dst(ipha);
1888 
1889 	dce = dce_lookup_and_add_v4(dst, ipst);
1890 	if (dce == NULL) {
1891 		/* Couldn't add a unique one - ENOMEM */
1892 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1893 		    ntohl(dst)));
1894 		return;
1895 	}
1896 
1897 	/* Check for MTU discovery advice as described in RFC 1191 */
1898 	mtu = ntohs(icmph->icmph_du_mtu);
1899 	orig_mtu = mtu;
1900 	disable_pmtud = B_FALSE;
1901 
1902 	mutex_enter(&dce->dce_lock);
1903 	if (dce->dce_flags & DCEF_PMTU)
1904 		old_mtu = dce->dce_pmtu;
1905 	else
1906 		old_mtu = ill->ill_mtu;
1907 
1908 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1909 		uint32_t length;
1910 		int	i;
1911 
1912 		/*
1913 		 * Use the table from RFC 1191 to figure out
1914 		 * the next "plateau" based on the length in
1915 		 * the original IP packet.
1916 		 */
1917 		length = ntohs(ipha->ipha_length);
1918 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1919 		    uint32_t, length);
1920 		if (old_mtu <= length &&
1921 		    old_mtu >= length - hdr_length) {
1922 			/*
1923 			 * Handle broken BSD 4.2 systems that
1924 			 * return the wrong ipha_length in ICMP
1925 			 * errors.
1926 			 */
1927 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1928 			    length, old_mtu));
1929 			length -= hdr_length;
1930 		}
1931 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1932 			if (length > icmp_frag_size_table[i])
1933 				break;
1934 		}
1935 		if (i == A_CNT(icmp_frag_size_table)) {
1936 			/* Smaller than IP_MIN_MTU! */
1937 			ip1dbg(("Too big for packet size %d\n",
1938 			    length));
1939 			disable_pmtud = B_TRUE;
1940 			mtu = ipst->ips_ip_pmtu_min;
1941 		} else {
1942 			mtu = icmp_frag_size_table[i];
1943 			ip1dbg(("Calculated mtu %d, packet size %d, "
1944 			    "before %d\n", mtu, length, old_mtu));
1945 			if (mtu < ipst->ips_ip_pmtu_min) {
1946 				mtu = ipst->ips_ip_pmtu_min;
1947 				disable_pmtud = B_TRUE;
1948 			}
1949 		}
1950 	}
1951 	if (disable_pmtud)
1952 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1953 	else
1954 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1955 
1956 	dce->dce_pmtu = MIN(old_mtu, mtu);
1957 	/* Prepare to send the new max frag size for the ULP. */
1958 	icmph->icmph_du_zero = 0;
1959 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1960 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1961 	    dce, int, orig_mtu, int, mtu);
1962 
1963 	/* We now have a PMTU for sure */
1964 	dce->dce_flags |= DCEF_PMTU;
1965 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1966 	mutex_exit(&dce->dce_lock);
1967 	/*
1968 	 * After dropping the lock the new value is visible to everyone.
1969 	 * Then we bump the generation number so any cached values reinspect
1970 	 * the dce_t.
1971 	 */
1972 	dce_increment_generation(dce);
1973 	dce_refrele(dce);
1974 }
1975 
1976 /*
1977  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1978  * calls this function.
1979  */
1980 static mblk_t *
1981 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1982 {
1983 	int length;
1984 
1985 	ASSERT(mp->b_datap->db_type == M_DATA);
1986 
1987 	/* icmp_inbound_v4 has already pulled up the whole error packet */
1988 	ASSERT(mp->b_cont == NULL);
1989 
1990 	/*
1991 	 * The length that we want to overlay is the inner header
1992 	 * and what follows it.
1993 	 */
1994 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
1995 
1996 	/*
1997 	 * Overlay the inner header and whatever follows it over the
1998 	 * outer header.
1999 	 */
2000 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2001 
2002 	/* Adjust for what we removed */
2003 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2004 	return (mp);
2005 }
2006 
2007 /*
2008  * Try to pass the ICMP message upstream in case the ULP cares.
2009  *
2010  * If the packet that caused the ICMP error is secure, we send
2011  * it to AH/ESP to make sure that the attached packet has a
2012  * valid association. ipha in the code below points to the
2013  * IP header of the packet that caused the error.
2014  *
2015  * For IPsec cases, we let the next-layer-up (which has access to
2016  * cached policy on the conn_t, or can query the SPD directly)
2017  * subtract out any IPsec overhead if they must.  We therefore make no
2018  * adjustments here for IPsec overhead.
2019  *
2020  * IFN could have been generated locally or by some router.
2021  *
2022  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2023  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2024  *	    This happens because IP adjusted its value of MTU on an
2025  *	    earlier IFN message and could not tell the upper layer,
2026  *	    the new adjusted value of MTU e.g. Packet was encrypted
2027  *	    or there was not enough information to fanout to upper
2028  *	    layers. Thus on the next outbound datagram, ire_send_wire
2029  *	    generates the IFN, where IPsec processing has *not* been
2030  *	    done.
2031  *
2032  *	    Note that we retain ixa_fragsize across IPsec thus once
2033  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2034  *	    no change the fragsize even if the path MTU changes before
2035  *	    we reach ip_output_post_ipsec.
2036  *
2037  *	    In the local case, IRAF_LOOPBACK will be set indicating
2038  *	    that IFN was generated locally.
2039  *
2040  * ROUTER : IFN could be secure or non-secure.
2041  *
2042  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2043  *	      packet in error has AH/ESP headers to validate the AH/ESP
2044  *	      headers. AH/ESP will verify whether there is a valid SA or
2045  *	      not and send it back. We will fanout again if we have more
2046  *	      data in the packet.
2047  *
2048  *	      If the packet in error does not have AH/ESP, we handle it
2049  *	      like any other case.
2050  *
2051  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2052  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2053  *	      valid SA or not and send it back. We will fanout again if
2054  *	      we have more data in the packet.
2055  *
2056  *	      If the packet in error does not have AH/ESP, we handle it
2057  *	      like any other case.
2058  *
2059  * The caller must have called icmp_inbound_verify_v4.
2060  */
2061 static void
2062 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2063 {
2064 	uint16_t	*up;	/* Pointer to ports in ULP header */
2065 	uint32_t	ports;	/* reversed ports for fanout */
2066 	ipha_t		ripha;	/* With reversed addresses */
2067 	ipha_t		*ipha;  /* Inner IP header */
2068 	uint_t		hdr_length; /* Inner IP header length */
2069 	tcpha_t		*tcpha;
2070 	conn_t		*connp;
2071 	ill_t		*ill = ira->ira_ill;
2072 	ip_stack_t	*ipst = ill->ill_ipst;
2073 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2074 	ill_t		*rill = ira->ira_rill;
2075 
2076 	/* Caller already pulled up everything. */
2077 	ipha = (ipha_t *)&icmph[1];
2078 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2079 	ASSERT(mp->b_cont == NULL);
2080 
2081 	hdr_length = IPH_HDR_LENGTH(ipha);
2082 	ira->ira_protocol = ipha->ipha_protocol;
2083 
2084 	/*
2085 	 * We need a separate IP header with the source and destination
2086 	 * addresses reversed to do fanout/classification because the ipha in
2087 	 * the ICMP error is in the form we sent it out.
2088 	 */
2089 	ripha.ipha_src = ipha->ipha_dst;
2090 	ripha.ipha_dst = ipha->ipha_src;
2091 	ripha.ipha_protocol = ipha->ipha_protocol;
2092 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2093 
2094 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2095 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2096 	    ntohl(ipha->ipha_dst),
2097 	    icmph->icmph_type, icmph->icmph_code));
2098 
2099 	switch (ipha->ipha_protocol) {
2100 	case IPPROTO_UDP:
2101 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2102 
2103 		/* Attempt to find a client stream based on port. */
2104 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2105 		    ntohs(up[0]), ntohs(up[1])));
2106 
2107 		/* Note that we send error to all matches. */
2108 		ira->ira_flags |= IRAF_ICMP_ERROR;
2109 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2110 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2111 		return;
2112 
2113 	case IPPROTO_TCP:
2114 		/*
2115 		 * Find a TCP client stream for this packet.
2116 		 * Note that we do a reverse lookup since the header is
2117 		 * in the form we sent it out.
2118 		 */
2119 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2120 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2121 		    ipst);
2122 		if (connp == NULL)
2123 			goto discard_pkt;
2124 
2125 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2126 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2127 			mp = ipsec_check_inbound_policy(mp, connp,
2128 			    ipha, NULL, ira);
2129 			if (mp == NULL) {
2130 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2131 				/* Note that mp is NULL */
2132 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2133 				CONN_DEC_REF(connp);
2134 				return;
2135 			}
2136 		}
2137 
2138 		ira->ira_flags |= IRAF_ICMP_ERROR;
2139 		ira->ira_ill = ira->ira_rill = NULL;
2140 		if (IPCL_IS_TCP(connp)) {
2141 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2142 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2143 			    SQTAG_TCP_INPUT_ICMP_ERR);
2144 		} else {
2145 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2146 			(connp->conn_recv)(connp, mp, NULL, ira);
2147 			CONN_DEC_REF(connp);
2148 		}
2149 		ira->ira_ill = ill;
2150 		ira->ira_rill = rill;
2151 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2152 		return;
2153 
2154 	case IPPROTO_SCTP:
2155 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2156 		/* Find a SCTP client stream for this packet. */
2157 		((uint16_t *)&ports)[0] = up[1];
2158 		((uint16_t *)&ports)[1] = up[0];
2159 
2160 		ira->ira_flags |= IRAF_ICMP_ERROR;
2161 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2162 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2163 		return;
2164 
2165 	case IPPROTO_ESP:
2166 	case IPPROTO_AH:
2167 		if (!ipsec_loaded(ipss)) {
2168 			ip_proto_not_sup(mp, ira);
2169 			return;
2170 		}
2171 
2172 		if (ipha->ipha_protocol == IPPROTO_ESP)
2173 			mp = ipsecesp_icmp_error(mp, ira);
2174 		else
2175 			mp = ipsecah_icmp_error(mp, ira);
2176 		if (mp == NULL)
2177 			return;
2178 
2179 		/* Just in case ipsec didn't preserve the NULL b_cont */
2180 		if (mp->b_cont != NULL) {
2181 			if (!pullupmsg(mp, -1))
2182 				goto discard_pkt;
2183 		}
2184 
2185 		/*
2186 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2187 		 * correct, but we don't use them any more here.
2188 		 *
2189 		 * If succesful, the mp has been modified to not include
2190 		 * the ESP/AH header so we can fanout to the ULP's icmp
2191 		 * error handler.
2192 		 */
2193 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2194 			goto truncated;
2195 
2196 		/* Verify the modified message before any further processes. */
2197 		ipha = (ipha_t *)mp->b_rptr;
2198 		hdr_length = IPH_HDR_LENGTH(ipha);
2199 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2200 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2201 			freemsg(mp);
2202 			return;
2203 		}
2204 
2205 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2206 		return;
2207 
2208 	case IPPROTO_ENCAP: {
2209 		/* Look for self-encapsulated packets that caused an error */
2210 		ipha_t *in_ipha;
2211 
2212 		/*
2213 		 * Caller has verified that length has to be
2214 		 * at least the size of IP header.
2215 		 */
2216 		ASSERT(hdr_length >= sizeof (ipha_t));
2217 		/*
2218 		 * Check the sanity of the inner IP header like
2219 		 * we did for the outer header.
2220 		 */
2221 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2222 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2223 			goto discard_pkt;
2224 		}
2225 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2226 			goto discard_pkt;
2227 		}
2228 		/* Check for Self-encapsulated tunnels */
2229 		if (in_ipha->ipha_src == ipha->ipha_src &&
2230 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2231 
2232 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2233 			    in_ipha);
2234 			if (mp == NULL)
2235 				goto discard_pkt;
2236 
2237 			/*
2238 			 * Just in case self_encap didn't preserve the NULL
2239 			 * b_cont
2240 			 */
2241 			if (mp->b_cont != NULL) {
2242 				if (!pullupmsg(mp, -1))
2243 					goto discard_pkt;
2244 			}
2245 			/*
2246 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2247 			 * longer correct, but we don't use them any more here.
2248 			 */
2249 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2250 				goto truncated;
2251 
2252 			/*
2253 			 * Verify the modified message before any further
2254 			 * processes.
2255 			 */
2256 			ipha = (ipha_t *)mp->b_rptr;
2257 			hdr_length = IPH_HDR_LENGTH(ipha);
2258 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2259 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2260 				freemsg(mp);
2261 				return;
2262 			}
2263 
2264 			/*
2265 			 * The packet in error is self-encapsualted.
2266 			 * And we are finding it further encapsulated
2267 			 * which we could not have possibly generated.
2268 			 */
2269 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2270 				goto discard_pkt;
2271 			}
2272 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2273 			return;
2274 		}
2275 		/* No self-encapsulated */
2276 		/* FALLTHRU */
2277 	}
2278 	case IPPROTO_IPV6:
2279 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2280 		    &ripha.ipha_dst, ipst)) != NULL) {
2281 			ira->ira_flags |= IRAF_ICMP_ERROR;
2282 			connp->conn_recvicmp(connp, mp, NULL, ira);
2283 			CONN_DEC_REF(connp);
2284 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2285 			return;
2286 		}
2287 		/*
2288 		 * No IP tunnel is interested, fallthrough and see
2289 		 * if a raw socket will want it.
2290 		 */
2291 		/* FALLTHRU */
2292 	default:
2293 		ira->ira_flags |= IRAF_ICMP_ERROR;
2294 		ip_fanout_proto_v4(mp, &ripha, ira);
2295 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2296 		return;
2297 	}
2298 	/* NOTREACHED */
2299 discard_pkt:
2300 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2301 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2302 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2303 	freemsg(mp);
2304 	return;
2305 
2306 truncated:
2307 	/* We pulled up everthing already. Must be truncated */
2308 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2309 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2310 	freemsg(mp);
2311 }
2312 
2313 /*
2314  * Common IP options parser.
2315  *
2316  * Setup routine: fill in *optp with options-parsing state, then
2317  * tail-call ipoptp_next to return the first option.
2318  */
2319 uint8_t
2320 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2321 {
2322 	uint32_t totallen; /* total length of all options */
2323 
2324 	totallen = ipha->ipha_version_and_hdr_length -
2325 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2326 	totallen <<= 2;
2327 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2328 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2329 	optp->ipoptp_flags = 0;
2330 	return (ipoptp_next(optp));
2331 }
2332 
2333 /* Like above but without an ipha_t */
2334 uint8_t
2335 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2336 {
2337 	optp->ipoptp_next = opt;
2338 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2339 	optp->ipoptp_flags = 0;
2340 	return (ipoptp_next(optp));
2341 }
2342 
2343 /*
2344  * Common IP options parser: extract next option.
2345  */
2346 uint8_t
2347 ipoptp_next(ipoptp_t *optp)
2348 {
2349 	uint8_t *end = optp->ipoptp_end;
2350 	uint8_t *cur = optp->ipoptp_next;
2351 	uint8_t opt, len, pointer;
2352 
2353 	/*
2354 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2355 	 * has been corrupted.
2356 	 */
2357 	ASSERT(cur <= end);
2358 
2359 	if (cur == end)
2360 		return (IPOPT_EOL);
2361 
2362 	opt = cur[IPOPT_OPTVAL];
2363 
2364 	/*
2365 	 * Skip any NOP options.
2366 	 */
2367 	while (opt == IPOPT_NOP) {
2368 		cur++;
2369 		if (cur == end)
2370 			return (IPOPT_EOL);
2371 		opt = cur[IPOPT_OPTVAL];
2372 	}
2373 
2374 	if (opt == IPOPT_EOL)
2375 		return (IPOPT_EOL);
2376 
2377 	/*
2378 	 * Option requiring a length.
2379 	 */
2380 	if ((cur + 1) >= end) {
2381 		optp->ipoptp_flags |= IPOPTP_ERROR;
2382 		return (IPOPT_EOL);
2383 	}
2384 	len = cur[IPOPT_OLEN];
2385 	if (len < 2) {
2386 		optp->ipoptp_flags |= IPOPTP_ERROR;
2387 		return (IPOPT_EOL);
2388 	}
2389 	optp->ipoptp_cur = cur;
2390 	optp->ipoptp_len = len;
2391 	optp->ipoptp_next = cur + len;
2392 	if (cur + len > end) {
2393 		optp->ipoptp_flags |= IPOPTP_ERROR;
2394 		return (IPOPT_EOL);
2395 	}
2396 
2397 	/*
2398 	 * For the options which require a pointer field, make sure
2399 	 * its there, and make sure it points to either something
2400 	 * inside this option, or the end of the option.
2401 	 */
2402 	switch (opt) {
2403 	case IPOPT_RR:
2404 	case IPOPT_TS:
2405 	case IPOPT_LSRR:
2406 	case IPOPT_SSRR:
2407 		if (len <= IPOPT_OFFSET) {
2408 			optp->ipoptp_flags |= IPOPTP_ERROR;
2409 			return (opt);
2410 		}
2411 		pointer = cur[IPOPT_OFFSET];
2412 		if (pointer - 1 > len) {
2413 			optp->ipoptp_flags |= IPOPTP_ERROR;
2414 			return (opt);
2415 		}
2416 		break;
2417 	}
2418 
2419 	/*
2420 	 * Sanity check the pointer field based on the type of the
2421 	 * option.
2422 	 */
2423 	switch (opt) {
2424 	case IPOPT_RR:
2425 	case IPOPT_SSRR:
2426 	case IPOPT_LSRR:
2427 		if (pointer < IPOPT_MINOFF_SR)
2428 			optp->ipoptp_flags |= IPOPTP_ERROR;
2429 		break;
2430 	case IPOPT_TS:
2431 		if (pointer < IPOPT_MINOFF_IT)
2432 			optp->ipoptp_flags |= IPOPTP_ERROR;
2433 		/*
2434 		 * Note that the Internet Timestamp option also
2435 		 * contains two four bit fields (the Overflow field,
2436 		 * and the Flag field), which follow the pointer
2437 		 * field.  We don't need to check that these fields
2438 		 * fall within the length of the option because this
2439 		 * was implicitely done above.  We've checked that the
2440 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2441 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2442 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2443 		 */
2444 		ASSERT(len > IPOPT_POS_OV_FLG);
2445 		break;
2446 	}
2447 
2448 	return (opt);
2449 }
2450 
2451 /*
2452  * Use the outgoing IP header to create an IP_OPTIONS option the way
2453  * it was passed down from the application.
2454  *
2455  * This is compatible with BSD in that it returns
2456  * the reverse source route with the final destination
2457  * as the last entry. The first 4 bytes of the option
2458  * will contain the final destination.
2459  */
2460 int
2461 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2462 {
2463 	ipoptp_t	opts;
2464 	uchar_t		*opt;
2465 	uint8_t		optval;
2466 	uint8_t		optlen;
2467 	uint32_t	len = 0;
2468 	uchar_t		*buf1 = buf;
2469 	uint32_t	totallen;
2470 	ipaddr_t	dst;
2471 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2472 
2473 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2474 		return (0);
2475 
2476 	totallen = ipp->ipp_ipv4_options_len;
2477 	if (totallen & 0x3)
2478 		return (0);
2479 
2480 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2481 	len += IP_ADDR_LEN;
2482 	bzero(buf1, IP_ADDR_LEN);
2483 
2484 	dst = connp->conn_faddr_v4;
2485 
2486 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2487 	    optval != IPOPT_EOL;
2488 	    optval = ipoptp_next(&opts)) {
2489 		int	off;
2490 
2491 		opt = opts.ipoptp_cur;
2492 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2493 			break;
2494 		}
2495 		optlen = opts.ipoptp_len;
2496 
2497 		switch (optval) {
2498 		case IPOPT_SSRR:
2499 		case IPOPT_LSRR:
2500 
2501 			/*
2502 			 * Insert destination as the first entry in the source
2503 			 * route and move down the entries on step.
2504 			 * The last entry gets placed at buf1.
2505 			 */
2506 			buf[IPOPT_OPTVAL] = optval;
2507 			buf[IPOPT_OLEN] = optlen;
2508 			buf[IPOPT_OFFSET] = optlen;
2509 
2510 			off = optlen - IP_ADDR_LEN;
2511 			if (off < 0) {
2512 				/* No entries in source route */
2513 				break;
2514 			}
2515 			/* Last entry in source route if not already set */
2516 			if (dst == INADDR_ANY)
2517 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2518 			off -= IP_ADDR_LEN;
2519 
2520 			while (off > 0) {
2521 				bcopy(opt + off,
2522 				    buf + off + IP_ADDR_LEN,
2523 				    IP_ADDR_LEN);
2524 				off -= IP_ADDR_LEN;
2525 			}
2526 			/* ipha_dst into first slot */
2527 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2528 			    IP_ADDR_LEN);
2529 			buf += optlen;
2530 			len += optlen;
2531 			break;
2532 
2533 		default:
2534 			bcopy(opt, buf, optlen);
2535 			buf += optlen;
2536 			len += optlen;
2537 			break;
2538 		}
2539 	}
2540 done:
2541 	/* Pad the resulting options */
2542 	while (len & 0x3) {
2543 		*buf++ = IPOPT_EOL;
2544 		len++;
2545 	}
2546 	return (len);
2547 }
2548 
2549 /*
2550  * Update any record route or timestamp options to include this host.
2551  * Reverse any source route option.
2552  * This routine assumes that the options are well formed i.e. that they
2553  * have already been checked.
2554  */
2555 static void
2556 icmp_options_update(ipha_t *ipha)
2557 {
2558 	ipoptp_t	opts;
2559 	uchar_t		*opt;
2560 	uint8_t		optval;
2561 	ipaddr_t	src;		/* Our local address */
2562 	ipaddr_t	dst;
2563 
2564 	ip2dbg(("icmp_options_update\n"));
2565 	src = ipha->ipha_src;
2566 	dst = ipha->ipha_dst;
2567 
2568 	for (optval = ipoptp_first(&opts, ipha);
2569 	    optval != IPOPT_EOL;
2570 	    optval = ipoptp_next(&opts)) {
2571 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2572 		opt = opts.ipoptp_cur;
2573 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2574 		    optval, opts.ipoptp_len));
2575 		switch (optval) {
2576 			int off1, off2;
2577 		case IPOPT_SSRR:
2578 		case IPOPT_LSRR:
2579 			/*
2580 			 * Reverse the source route.  The first entry
2581 			 * should be the next to last one in the current
2582 			 * source route (the last entry is our address).
2583 			 * The last entry should be the final destination.
2584 			 */
2585 			off1 = IPOPT_MINOFF_SR - 1;
2586 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2587 			if (off2 < 0) {
2588 				/* No entries in source route */
2589 				ip1dbg((
2590 				    "icmp_options_update: bad src route\n"));
2591 				break;
2592 			}
2593 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2594 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2595 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2596 			off2 -= IP_ADDR_LEN;
2597 
2598 			while (off1 < off2) {
2599 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2600 				bcopy((char *)opt + off2, (char *)opt + off1,
2601 				    IP_ADDR_LEN);
2602 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2603 				off1 += IP_ADDR_LEN;
2604 				off2 -= IP_ADDR_LEN;
2605 			}
2606 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2607 			break;
2608 		}
2609 	}
2610 }
2611 
2612 /*
2613  * Process received ICMP Redirect messages.
2614  * Assumes the caller has verified that the headers are in the pulled up mblk.
2615  * Consumes mp.
2616  */
2617 static void
2618 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2619 {
2620 	ire_t		*ire, *nire;
2621 	ire_t		*prev_ire;
2622 	ipaddr_t  	src, dst, gateway;
2623 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2624 	ipha_t		*inner_ipha;	/* Inner IP header */
2625 
2626 	/* Caller already pulled up everything. */
2627 	inner_ipha = (ipha_t *)&icmph[1];
2628 	src = ipha->ipha_src;
2629 	dst = inner_ipha->ipha_dst;
2630 	gateway = icmph->icmph_rd_gateway;
2631 	/* Make sure the new gateway is reachable somehow. */
2632 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2633 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2634 	/*
2635 	 * Make sure we had a route for the dest in question and that
2636 	 * that route was pointing to the old gateway (the source of the
2637 	 * redirect packet.)
2638 	 * We do longest match and then compare ire_gateway_addr below.
2639 	 */
2640 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2641 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2642 	/*
2643 	 * Check that
2644 	 *	the redirect was not from ourselves
2645 	 *	the new gateway and the old gateway are directly reachable
2646 	 */
2647 	if (prev_ire == NULL || ire == NULL ||
2648 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2649 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2650 	    !(ire->ire_type & IRE_IF_ALL) ||
2651 	    prev_ire->ire_gateway_addr != src) {
2652 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2653 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2654 		freemsg(mp);
2655 		if (ire != NULL)
2656 			ire_refrele(ire);
2657 		if (prev_ire != NULL)
2658 			ire_refrele(prev_ire);
2659 		return;
2660 	}
2661 
2662 	ire_refrele(prev_ire);
2663 	ire_refrele(ire);
2664 
2665 	/*
2666 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2667 	 * require TOS routing
2668 	 */
2669 	switch (icmph->icmph_code) {
2670 	case 0:
2671 	case 1:
2672 		/* TODO: TOS specificity for cases 2 and 3 */
2673 	case 2:
2674 	case 3:
2675 		break;
2676 	default:
2677 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2678 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2679 		freemsg(mp);
2680 		return;
2681 	}
2682 	/*
2683 	 * Create a Route Association.  This will allow us to remember that
2684 	 * someone we believe told us to use the particular gateway.
2685 	 */
2686 	ire = ire_create(
2687 	    (uchar_t *)&dst,			/* dest addr */
2688 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2689 	    (uchar_t *)&gateway,		/* gateway addr */
2690 	    IRE_HOST,
2691 	    NULL,				/* ill */
2692 	    ALL_ZONES,
2693 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2694 	    NULL,				/* tsol_gc_t */
2695 	    ipst);
2696 
2697 	if (ire == NULL) {
2698 		freemsg(mp);
2699 		return;
2700 	}
2701 	nire = ire_add(ire);
2702 	/* Check if it was a duplicate entry */
2703 	if (nire != NULL && nire != ire) {
2704 		ASSERT(nire->ire_identical_ref > 1);
2705 		ire_delete(nire);
2706 		ire_refrele(nire);
2707 		nire = NULL;
2708 	}
2709 	ire = nire;
2710 	if (ire != NULL) {
2711 		ire_refrele(ire);		/* Held in ire_add */
2712 
2713 		/* tell routing sockets that we received a redirect */
2714 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2715 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2716 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2717 	}
2718 
2719 	/*
2720 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2721 	 * This together with the added IRE has the effect of
2722 	 * modifying an existing redirect.
2723 	 */
2724 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2725 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2726 	if (prev_ire != NULL) {
2727 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2728 			ire_delete(prev_ire);
2729 		ire_refrele(prev_ire);
2730 	}
2731 
2732 	freemsg(mp);
2733 }
2734 
2735 /*
2736  * Generate an ICMP parameter problem message.
2737  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2738  * constructed by the caller.
2739  */
2740 static void
2741 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2742 {
2743 	icmph_t	icmph;
2744 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2745 
2746 	mp = icmp_pkt_err_ok(mp, ira);
2747 	if (mp == NULL)
2748 		return;
2749 
2750 	bzero(&icmph, sizeof (icmph_t));
2751 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2752 	icmph.icmph_pp_ptr = ptr;
2753 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2754 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2755 }
2756 
2757 /*
2758  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2759  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2760  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2761  * an icmp error packet can be sent.
2762  * Assigns an appropriate source address to the packet. If ipha_dst is
2763  * one of our addresses use it for source. Otherwise let ip_output_simple
2764  * pick the source address.
2765  */
2766 static void
2767 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2768 {
2769 	ipaddr_t dst;
2770 	icmph_t	*icmph;
2771 	ipha_t	*ipha;
2772 	uint_t	len_needed;
2773 	size_t	msg_len;
2774 	mblk_t	*mp1;
2775 	ipaddr_t src;
2776 	ire_t	*ire;
2777 	ip_xmit_attr_t ixas;
2778 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2779 
2780 	ipha = (ipha_t *)mp->b_rptr;
2781 
2782 	bzero(&ixas, sizeof (ixas));
2783 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2784 	ixas.ixa_zoneid = ira->ira_zoneid;
2785 	ixas.ixa_ifindex = 0;
2786 	ixas.ixa_ipst = ipst;
2787 	ixas.ixa_cred = kcred;
2788 	ixas.ixa_cpid = NOPID;
2789 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2790 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2791 
2792 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2793 		/*
2794 		 * Apply IPsec based on how IPsec was applied to
2795 		 * the packet that had the error.
2796 		 *
2797 		 * If it was an outbound packet that caused the ICMP
2798 		 * error, then the caller will have setup the IRA
2799 		 * appropriately.
2800 		 */
2801 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2802 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2803 			/* Note: mp already consumed and ip_drop_packet done */
2804 			return;
2805 		}
2806 	} else {
2807 		/*
2808 		 * This is in clear. The icmp message we are building
2809 		 * here should go out in clear, independent of our policy.
2810 		 */
2811 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2812 	}
2813 
2814 	/* Remember our eventual destination */
2815 	dst = ipha->ipha_src;
2816 
2817 	/*
2818 	 * If the packet was for one of our unicast addresses, make
2819 	 * sure we respond with that as the source. Otherwise
2820 	 * have ip_output_simple pick the source address.
2821 	 */
2822 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2823 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2824 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2825 	if (ire != NULL) {
2826 		ire_refrele(ire);
2827 		src = ipha->ipha_dst;
2828 	} else {
2829 		src = INADDR_ANY;
2830 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2831 	}
2832 
2833 	/*
2834 	 * Check if we can send back more then 8 bytes in addition to
2835 	 * the IP header.  We try to send 64 bytes of data and the internal
2836 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2837 	 */
2838 	len_needed = IPH_HDR_LENGTH(ipha);
2839 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2840 	    ipha->ipha_protocol == IPPROTO_IPV6) {
2841 		if (!pullupmsg(mp, -1)) {
2842 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2843 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2844 			freemsg(mp);
2845 			return;
2846 		}
2847 		ipha = (ipha_t *)mp->b_rptr;
2848 
2849 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2850 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2851 			    len_needed));
2852 		} else {
2853 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2854 
2855 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2856 			len_needed += ip_hdr_length_v6(mp, ip6h);
2857 		}
2858 	}
2859 	len_needed += ipst->ips_ip_icmp_return;
2860 	msg_len = msgdsize(mp);
2861 	if (msg_len > len_needed) {
2862 		(void) adjmsg(mp, len_needed - msg_len);
2863 		msg_len = len_needed;
2864 	}
2865 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2866 	if (mp1 == NULL) {
2867 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2868 		freemsg(mp);
2869 		return;
2870 	}
2871 	mp1->b_cont = mp;
2872 	mp = mp1;
2873 
2874 	/*
2875 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2876 	 * node generates be accepted in peace by all on-host destinations.
2877 	 * If we do NOT assume that all on-host destinations trust
2878 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2879 	 * (Look for IXAF_TRUSTED_ICMP).
2880 	 */
2881 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2882 
2883 	ipha = (ipha_t *)mp->b_rptr;
2884 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2885 	*ipha = icmp_ipha;
2886 	ipha->ipha_src = src;
2887 	ipha->ipha_dst = dst;
2888 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2889 	msg_len += sizeof (icmp_ipha) + len;
2890 	if (msg_len > IP_MAXPACKET) {
2891 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
2892 		msg_len = IP_MAXPACKET;
2893 	}
2894 	ipha->ipha_length = htons((uint16_t)msg_len);
2895 	icmph = (icmph_t *)&ipha[1];
2896 	bcopy(stuff, icmph, len);
2897 	icmph->icmph_checksum = 0;
2898 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2899 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2900 
2901 	(void) ip_output_simple(mp, &ixas);
2902 	ixa_cleanup(&ixas);
2903 }
2904 
2905 /*
2906  * Determine if an ICMP error packet can be sent given the rate limit.
2907  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2908  * in milliseconds) and a burst size. Burst size number of packets can
2909  * be sent arbitrarely closely spaced.
2910  * The state is tracked using two variables to implement an approximate
2911  * token bucket filter:
2912  *	icmp_pkt_err_last - lbolt value when the last burst started
2913  *	icmp_pkt_err_sent - number of packets sent in current burst
2914  */
2915 boolean_t
2916 icmp_err_rate_limit(ip_stack_t *ipst)
2917 {
2918 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2919 	uint_t refilled; /* Number of packets refilled in tbf since last */
2920 	/* Guard against changes by loading into local variable */
2921 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2922 
2923 	if (err_interval == 0)
2924 		return (B_FALSE);
2925 
2926 	if (ipst->ips_icmp_pkt_err_last > now) {
2927 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2928 		ipst->ips_icmp_pkt_err_last = 0;
2929 		ipst->ips_icmp_pkt_err_sent = 0;
2930 	}
2931 	/*
2932 	 * If we are in a burst update the token bucket filter.
2933 	 * Update the "last" time to be close to "now" but make sure
2934 	 * we don't loose precision.
2935 	 */
2936 	if (ipst->ips_icmp_pkt_err_sent != 0) {
2937 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2938 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
2939 			ipst->ips_icmp_pkt_err_sent = 0;
2940 		} else {
2941 			ipst->ips_icmp_pkt_err_sent -= refilled;
2942 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2943 		}
2944 	}
2945 	if (ipst->ips_icmp_pkt_err_sent == 0) {
2946 		/* Start of new burst */
2947 		ipst->ips_icmp_pkt_err_last = now;
2948 	}
2949 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2950 		ipst->ips_icmp_pkt_err_sent++;
2951 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2952 		    ipst->ips_icmp_pkt_err_sent));
2953 		return (B_FALSE);
2954 	}
2955 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
2956 	return (B_TRUE);
2957 }
2958 
2959 /*
2960  * Check if it is ok to send an IPv4 ICMP error packet in
2961  * response to the IPv4 packet in mp.
2962  * Free the message and return null if no
2963  * ICMP error packet should be sent.
2964  */
2965 static mblk_t *
2966 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2967 {
2968 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2969 	icmph_t	*icmph;
2970 	ipha_t	*ipha;
2971 	uint_t	len_needed;
2972 
2973 	if (!mp)
2974 		return (NULL);
2975 	ipha = (ipha_t *)mp->b_rptr;
2976 	if (ip_csum_hdr(ipha)) {
2977 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2978 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2979 		freemsg(mp);
2980 		return (NULL);
2981 	}
2982 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2983 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2984 	    CLASSD(ipha->ipha_dst) ||
2985 	    CLASSD(ipha->ipha_src) ||
2986 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2987 		/* Note: only errors to the fragment with offset 0 */
2988 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2989 		freemsg(mp);
2990 		return (NULL);
2991 	}
2992 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
2993 		/*
2994 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
2995 		 * errors in response to any ICMP errors.
2996 		 */
2997 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
2998 		if (mp->b_wptr - mp->b_rptr < len_needed) {
2999 			if (!pullupmsg(mp, len_needed)) {
3000 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3001 				freemsg(mp);
3002 				return (NULL);
3003 			}
3004 			ipha = (ipha_t *)mp->b_rptr;
3005 		}
3006 		icmph = (icmph_t *)
3007 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3008 		switch (icmph->icmph_type) {
3009 		case ICMP_DEST_UNREACHABLE:
3010 		case ICMP_SOURCE_QUENCH:
3011 		case ICMP_TIME_EXCEEDED:
3012 		case ICMP_PARAM_PROBLEM:
3013 		case ICMP_REDIRECT:
3014 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3015 			freemsg(mp);
3016 			return (NULL);
3017 		default:
3018 			break;
3019 		}
3020 	}
3021 	/*
3022 	 * If this is a labeled system, then check to see if we're allowed to
3023 	 * send a response to this particular sender.  If not, then just drop.
3024 	 */
3025 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3026 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3027 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3028 		freemsg(mp);
3029 		return (NULL);
3030 	}
3031 	if (icmp_err_rate_limit(ipst)) {
3032 		/*
3033 		 * Only send ICMP error packets every so often.
3034 		 * This should be done on a per port/source basis,
3035 		 * but for now this will suffice.
3036 		 */
3037 		freemsg(mp);
3038 		return (NULL);
3039 	}
3040 	return (mp);
3041 }
3042 
3043 /*
3044  * Called when a packet was sent out the same link that it arrived on.
3045  * Check if it is ok to send a redirect and then send it.
3046  */
3047 void
3048 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3049     ip_recv_attr_t *ira)
3050 {
3051 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3052 	ipaddr_t	src, nhop;
3053 	mblk_t		*mp1;
3054 	ire_t		*nhop_ire;
3055 
3056 	/*
3057 	 * Check the source address to see if it originated
3058 	 * on the same logical subnet it is going back out on.
3059 	 * If so, we should be able to send it a redirect.
3060 	 * Avoid sending a redirect if the destination
3061 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3062 	 * or if the packet was source routed out this interface.
3063 	 *
3064 	 * We avoid sending a redirect if the
3065 	 * destination is directly connected
3066 	 * because it is possible that multiple
3067 	 * IP subnets may have been configured on
3068 	 * the link, and the source may not
3069 	 * be on the same subnet as ip destination,
3070 	 * even though they are on the same
3071 	 * physical link.
3072 	 */
3073 	if ((ire->ire_type & IRE_ONLINK) ||
3074 	    ip_source_routed(ipha, ipst))
3075 		return;
3076 
3077 	nhop_ire = ire_nexthop(ire);
3078 	if (nhop_ire == NULL)
3079 		return;
3080 
3081 	nhop = nhop_ire->ire_addr;
3082 
3083 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3084 		ire_t	*ire2;
3085 
3086 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3087 		mutex_enter(&nhop_ire->ire_lock);
3088 		ire2 = nhop_ire->ire_dep_parent;
3089 		if (ire2 != NULL)
3090 			ire_refhold(ire2);
3091 		mutex_exit(&nhop_ire->ire_lock);
3092 		ire_refrele(nhop_ire);
3093 		nhop_ire = ire2;
3094 	}
3095 	if (nhop_ire == NULL)
3096 		return;
3097 
3098 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3099 
3100 	src = ipha->ipha_src;
3101 
3102 	/*
3103 	 * We look at the interface ire for the nexthop,
3104 	 * to see if ipha_src is in the same subnet
3105 	 * as the nexthop.
3106 	 */
3107 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3108 		/*
3109 		 * The source is directly connected.
3110 		 */
3111 		mp1 = copymsg(mp);
3112 		if (mp1 != NULL) {
3113 			icmp_send_redirect(mp1, nhop, ira);
3114 		}
3115 	}
3116 	ire_refrele(nhop_ire);
3117 }
3118 
3119 /*
3120  * Generate an ICMP redirect message.
3121  */
3122 static void
3123 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3124 {
3125 	icmph_t	icmph;
3126 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3127 
3128 	mp = icmp_pkt_err_ok(mp, ira);
3129 	if (mp == NULL)
3130 		return;
3131 
3132 	bzero(&icmph, sizeof (icmph_t));
3133 	icmph.icmph_type = ICMP_REDIRECT;
3134 	icmph.icmph_code = 1;
3135 	icmph.icmph_rd_gateway = gateway;
3136 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3137 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3138 }
3139 
3140 /*
3141  * Generate an ICMP time exceeded message.
3142  */
3143 void
3144 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3145 {
3146 	icmph_t	icmph;
3147 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3148 
3149 	mp = icmp_pkt_err_ok(mp, ira);
3150 	if (mp == NULL)
3151 		return;
3152 
3153 	bzero(&icmph, sizeof (icmph_t));
3154 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3155 	icmph.icmph_code = code;
3156 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3157 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3158 }
3159 
3160 /*
3161  * Generate an ICMP unreachable message.
3162  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3163  * constructed by the caller.
3164  */
3165 void
3166 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3167 {
3168 	icmph_t	icmph;
3169 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3170 
3171 	mp = icmp_pkt_err_ok(mp, ira);
3172 	if (mp == NULL)
3173 		return;
3174 
3175 	bzero(&icmph, sizeof (icmph_t));
3176 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3177 	icmph.icmph_code = code;
3178 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3179 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3180 }
3181 
3182 /*
3183  * Latch in the IPsec state for a stream based the policy in the listener
3184  * and the actions in the ip_recv_attr_t.
3185  * Called directly from TCP and SCTP.
3186  */
3187 boolean_t
3188 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3189 {
3190 	ASSERT(lconnp->conn_policy != NULL);
3191 	ASSERT(connp->conn_policy == NULL);
3192 
3193 	IPPH_REFHOLD(lconnp->conn_policy);
3194 	connp->conn_policy = lconnp->conn_policy;
3195 
3196 	if (ira->ira_ipsec_action != NULL) {
3197 		if (connp->conn_latch == NULL) {
3198 			connp->conn_latch = iplatch_create();
3199 			if (connp->conn_latch == NULL)
3200 				return (B_FALSE);
3201 		}
3202 		ipsec_latch_inbound(connp, ira);
3203 	}
3204 	return (B_TRUE);
3205 }
3206 
3207 /*
3208  * Verify whether or not the IP address is a valid local address.
3209  * Could be a unicast, including one for a down interface.
3210  * If allow_mcbc then a multicast or broadcast address is also
3211  * acceptable.
3212  *
3213  * In the case of a broadcast/multicast address, however, the
3214  * upper protocol is expected to reset the src address
3215  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3216  * no packets are emitted with broadcast/multicast address as
3217  * source address (that violates hosts requirements RFC 1122)
3218  * The addresses valid for bind are:
3219  *	(1) - INADDR_ANY (0)
3220  *	(2) - IP address of an UP interface
3221  *	(3) - IP address of a DOWN interface
3222  *	(4) - valid local IP broadcast addresses. In this case
3223  *	the conn will only receive packets destined to
3224  *	the specified broadcast address.
3225  *	(5) - a multicast address. In this case
3226  *	the conn will only receive packets destined to
3227  *	the specified multicast address. Note: the
3228  *	application still has to issue an
3229  *	IP_ADD_MEMBERSHIP socket option.
3230  *
3231  * In all the above cases, the bound address must be valid in the current zone.
3232  * When the address is loopback, multicast or broadcast, there might be many
3233  * matching IREs so bind has to look up based on the zone.
3234  */
3235 ip_laddr_t
3236 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3237     ip_stack_t *ipst, boolean_t allow_mcbc)
3238 {
3239 	ire_t *src_ire;
3240 
3241 	ASSERT(src_addr != INADDR_ANY);
3242 
3243 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3244 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3245 
3246 	/*
3247 	 * If an address other than in6addr_any is requested,
3248 	 * we verify that it is a valid address for bind
3249 	 * Note: Following code is in if-else-if form for
3250 	 * readability compared to a condition check.
3251 	 */
3252 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3253 		/*
3254 		 * (2) Bind to address of local UP interface
3255 		 */
3256 		ire_refrele(src_ire);
3257 		return (IPVL_UNICAST_UP);
3258 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3259 		/*
3260 		 * (4) Bind to broadcast address
3261 		 */
3262 		ire_refrele(src_ire);
3263 		if (allow_mcbc)
3264 			return (IPVL_BCAST);
3265 		else
3266 			return (IPVL_BAD);
3267 	} else if (CLASSD(src_addr)) {
3268 		/* (5) bind to multicast address. */
3269 		if (src_ire != NULL)
3270 			ire_refrele(src_ire);
3271 
3272 		if (allow_mcbc)
3273 			return (IPVL_MCAST);
3274 		else
3275 			return (IPVL_BAD);
3276 	} else {
3277 		ipif_t *ipif;
3278 
3279 		/*
3280 		 * (3) Bind to address of local DOWN interface?
3281 		 * (ipif_lookup_addr() looks up all interfaces
3282 		 * but we do not get here for UP interfaces
3283 		 * - case (2) above)
3284 		 */
3285 		if (src_ire != NULL)
3286 			ire_refrele(src_ire);
3287 
3288 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3289 		if (ipif == NULL)
3290 			return (IPVL_BAD);
3291 
3292 		/* Not a useful source? */
3293 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3294 			ipif_refrele(ipif);
3295 			return (IPVL_BAD);
3296 		}
3297 		ipif_refrele(ipif);
3298 		return (IPVL_UNICAST_DOWN);
3299 	}
3300 }
3301 
3302 /*
3303  * Insert in the bind fanout for IPv4 and IPv6.
3304  * The caller should already have used ip_laddr_verify_v*() before calling
3305  * this.
3306  */
3307 int
3308 ip_laddr_fanout_insert(conn_t *connp)
3309 {
3310 	int		error;
3311 
3312 	/*
3313 	 * Allow setting new policies. For example, disconnects result
3314 	 * in us being called. As we would have set conn_policy_cached
3315 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3316 	 * can change after the disconnect.
3317 	 */
3318 	connp->conn_policy_cached = B_FALSE;
3319 
3320 	error = ipcl_bind_insert(connp);
3321 	if (error != 0) {
3322 		if (connp->conn_anon_port) {
3323 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3324 			    connp->conn_mlp_type, connp->conn_proto,
3325 			    ntohs(connp->conn_lport), B_FALSE);
3326 		}
3327 		connp->conn_mlp_type = mlptSingle;
3328 	}
3329 	return (error);
3330 }
3331 
3332 /*
3333  * Verify that both the source and destination addresses are valid. If
3334  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3335  * i.e. have no route to it.  Protocols like TCP want to verify destination
3336  * reachability, while tunnels do not.
3337  *
3338  * Determine the route, the interface, and (optionally) the source address
3339  * to use to reach a given destination.
3340  * Note that we allow connect to broadcast and multicast addresses when
3341  * IPDF_ALLOW_MCBC is set.
3342  * first_hop and dst_addr are normally the same, but if source routing
3343  * they will differ; in that case the first_hop is what we'll use for the
3344  * routing lookup but the dce and label checks will be done on dst_addr,
3345  *
3346  * If uinfo is set, then we fill in the best available information
3347  * we have for the destination. This is based on (in priority order) any
3348  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3349  * ill_mtu.
3350  *
3351  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3352  * always do the label check on dst_addr.
3353  */
3354 int
3355 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3356     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3357 {
3358 	ire_t		*ire = NULL;
3359 	int		error = 0;
3360 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3361 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3362 	ip_stack_t	*ipst = ixa->ixa_ipst;
3363 	dce_t		*dce;
3364 	uint_t		pmtu;
3365 	uint_t		generation;
3366 	nce_t		*nce;
3367 	ill_t		*ill = NULL;
3368 	boolean_t	multirt = B_FALSE;
3369 
3370 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3371 
3372 	/*
3373 	 * We never send to zero; the ULPs map it to the loopback address.
3374 	 * We can't allow it since we use zero to mean unitialized in some
3375 	 * places.
3376 	 */
3377 	ASSERT(dst_addr != INADDR_ANY);
3378 
3379 	if (is_system_labeled()) {
3380 		ts_label_t *tsl = NULL;
3381 
3382 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3383 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3384 		if (error != 0)
3385 			return (error);
3386 		if (tsl != NULL) {
3387 			/* Update the label */
3388 			ip_xmit_attr_replace_tsl(ixa, tsl);
3389 		}
3390 	}
3391 
3392 	setsrc = INADDR_ANY;
3393 	/*
3394 	 * Select a route; For IPMP interfaces, we would only select
3395 	 * a "hidden" route (i.e., going through a specific under_ill)
3396 	 * if ixa_ifindex has been specified.
3397 	 */
3398 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3399 	    &generation, &setsrc, &error, &multirt);
3400 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3401 	if (error != 0)
3402 		goto bad_addr;
3403 
3404 	/*
3405 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3406 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3407 	 * Otherwise the destination needn't be reachable.
3408 	 *
3409 	 * If we match on a reject or black hole, then we've got a
3410 	 * local failure.  May as well fail out the connect() attempt,
3411 	 * since it's never going to succeed.
3412 	 */
3413 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3414 		/*
3415 		 * If we're verifying destination reachability, we always want
3416 		 * to complain here.
3417 		 *
3418 		 * If we're not verifying destination reachability but the
3419 		 * destination has a route, we still want to fail on the
3420 		 * temporary address and broadcast address tests.
3421 		 *
3422 		 * In both cases do we let the code continue so some reasonable
3423 		 * information is returned to the caller. That enables the
3424 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3425 		 * use the generation mismatch path to check for the unreachable
3426 		 * case thereby avoiding any specific check in the main path.
3427 		 */
3428 		ASSERT(generation == IRE_GENERATION_VERIFY);
3429 		if (flags & IPDF_VERIFY_DST) {
3430 			/*
3431 			 * Set errno but continue to set up ixa_ire to be
3432 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3433 			 * That allows callers to use ip_output to get an
3434 			 * ICMP error back.
3435 			 */
3436 			if (!(ire->ire_type & IRE_HOST))
3437 				error = ENETUNREACH;
3438 			else
3439 				error = EHOSTUNREACH;
3440 		}
3441 	}
3442 
3443 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3444 	    !(flags & IPDF_ALLOW_MCBC)) {
3445 		ire_refrele(ire);
3446 		ire = ire_reject(ipst, B_FALSE);
3447 		generation = IRE_GENERATION_VERIFY;
3448 		error = ENETUNREACH;
3449 	}
3450 
3451 	/* Cache things */
3452 	if (ixa->ixa_ire != NULL)
3453 		ire_refrele_notr(ixa->ixa_ire);
3454 #ifdef DEBUG
3455 	ire_refhold_notr(ire);
3456 	ire_refrele(ire);
3457 #endif
3458 	ixa->ixa_ire = ire;
3459 	ixa->ixa_ire_generation = generation;
3460 
3461 	/*
3462 	 * Ensure that ixa_dce is always set any time that ixa_ire is set,
3463 	 * since some callers will send a packet to conn_ip_output() even if
3464 	 * there's an error.
3465 	 */
3466 	if (flags & IPDF_UNIQUE_DCE) {
3467 		/* Fallback to the default dce if allocation fails */
3468 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3469 		if (dce != NULL)
3470 			generation = dce->dce_generation;
3471 		else
3472 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3473 	} else {
3474 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3475 	}
3476 	ASSERT(dce != NULL);
3477 	if (ixa->ixa_dce != NULL)
3478 		dce_refrele_notr(ixa->ixa_dce);
3479 #ifdef DEBUG
3480 	dce_refhold_notr(dce);
3481 	dce_refrele(dce);
3482 #endif
3483 	ixa->ixa_dce = dce;
3484 	ixa->ixa_dce_generation = generation;
3485 
3486 	/*
3487 	 * For multicast with multirt we have a flag passed back from
3488 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3489 	 * possible multicast address.
3490 	 * We also need a flag for multicast since we can't check
3491 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3492 	 */
3493 	if (multirt) {
3494 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3495 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3496 	} else {
3497 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3498 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3499 	}
3500 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3501 		/* Get an nce to cache. */
3502 		nce = ire_to_nce(ire, firsthop, NULL);
3503 		if (nce == NULL) {
3504 			/* Allocation failure? */
3505 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3506 		} else {
3507 			if (ixa->ixa_nce != NULL)
3508 				nce_refrele(ixa->ixa_nce);
3509 			ixa->ixa_nce = nce;
3510 		}
3511 	}
3512 
3513 	/*
3514 	 * If the source address is a loopback address, the
3515 	 * destination had best be local or multicast.
3516 	 * If we are sending to an IRE_LOCAL using a loopback source then
3517 	 * it had better be the same zoneid.
3518 	 */
3519 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3520 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3521 			ire = NULL;	/* Stored in ixa_ire */
3522 			error = EADDRNOTAVAIL;
3523 			goto bad_addr;
3524 		}
3525 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3526 			ire = NULL;	/* Stored in ixa_ire */
3527 			error = EADDRNOTAVAIL;
3528 			goto bad_addr;
3529 		}
3530 	}
3531 	if (ire->ire_type & IRE_BROADCAST) {
3532 		/*
3533 		 * If the ULP didn't have a specified source, then we
3534 		 * make sure we reselect the source when sending
3535 		 * broadcasts out different interfaces.
3536 		 */
3537 		if (flags & IPDF_SELECT_SRC)
3538 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3539 		else
3540 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3541 	}
3542 
3543 	/*
3544 	 * Does the caller want us to pick a source address?
3545 	 */
3546 	if (flags & IPDF_SELECT_SRC) {
3547 		ipaddr_t	src_addr;
3548 
3549 		/*
3550 		 * We use use ire_nexthop_ill to avoid the under ipmp
3551 		 * interface for source address selection. Note that for ipmp
3552 		 * probe packets, ixa_ifindex would have been specified, and
3553 		 * the ip_select_route() invocation would have picked an ire
3554 		 * will ire_ill pointing at an under interface.
3555 		 */
3556 		ill = ire_nexthop_ill(ire);
3557 
3558 		/* If unreachable we have no ill but need some source */
3559 		if (ill == NULL) {
3560 			src_addr = htonl(INADDR_LOOPBACK);
3561 			/* Make sure we look for a better source address */
3562 			generation = SRC_GENERATION_VERIFY;
3563 		} else {
3564 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3565 			    ixa->ixa_multicast_ifaddr, zoneid,
3566 			    ipst, &src_addr, &generation, NULL);
3567 			if (error != 0) {
3568 				ire = NULL;	/* Stored in ixa_ire */
3569 				goto bad_addr;
3570 			}
3571 		}
3572 
3573 		/*
3574 		 * We allow the source address to to down.
3575 		 * However, we check that we don't use the loopback address
3576 		 * as a source when sending out on the wire.
3577 		 */
3578 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3579 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3580 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3581 			ire = NULL;	/* Stored in ixa_ire */
3582 			error = EADDRNOTAVAIL;
3583 			goto bad_addr;
3584 		}
3585 
3586 		*src_addrp = src_addr;
3587 		ixa->ixa_src_generation = generation;
3588 	}
3589 
3590 	/*
3591 	 * Make sure we don't leave an unreachable ixa_nce in place
3592 	 * since ip_select_route is used when we unplumb i.e., remove
3593 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3594 	 */
3595 	nce = ixa->ixa_nce;
3596 	if (nce != NULL && nce->nce_is_condemned) {
3597 		nce_refrele(nce);
3598 		ixa->ixa_nce = NULL;
3599 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3600 	}
3601 
3602 	/*
3603 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3604 	 * However, we can't do it for IPv4 multicast or broadcast.
3605 	 */
3606 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3607 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3608 
3609 	/*
3610 	 * Set initial value for fragmentation limit. Either conn_ip_output
3611 	 * or ULP might updates it when there are routing changes.
3612 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3613 	 */
3614 	pmtu = ip_get_pmtu(ixa);
3615 	ixa->ixa_fragsize = pmtu;
3616 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3617 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3618 		ixa->ixa_pmtu = pmtu;
3619 
3620 	/*
3621 	 * Extract information useful for some transports.
3622 	 * First we look for DCE metrics. Then we take what we have in
3623 	 * the metrics in the route, where the offlink is used if we have
3624 	 * one.
3625 	 */
3626 	if (uinfo != NULL) {
3627 		bzero(uinfo, sizeof (*uinfo));
3628 
3629 		if (dce->dce_flags & DCEF_UINFO)
3630 			*uinfo = dce->dce_uinfo;
3631 
3632 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3633 
3634 		/* Allow ire_metrics to decrease the path MTU from above */
3635 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3636 			uinfo->iulp_mtu = pmtu;
3637 
3638 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3639 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3640 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3641 	}
3642 
3643 	if (ill != NULL)
3644 		ill_refrele(ill);
3645 
3646 	return (error);
3647 
3648 bad_addr:
3649 	if (ire != NULL)
3650 		ire_refrele(ire);
3651 
3652 	if (ill != NULL)
3653 		ill_refrele(ill);
3654 
3655 	/*
3656 	 * Make sure we don't leave an unreachable ixa_nce in place
3657 	 * since ip_select_route is used when we unplumb i.e., remove
3658 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3659 	 */
3660 	nce = ixa->ixa_nce;
3661 	if (nce != NULL && nce->nce_is_condemned) {
3662 		nce_refrele(nce);
3663 		ixa->ixa_nce = NULL;
3664 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3665 	}
3666 
3667 	return (error);
3668 }
3669 
3670 
3671 /*
3672  * Get the base MTU for the case when path MTU discovery is not used.
3673  * Takes the MTU of the IRE into account.
3674  */
3675 uint_t
3676 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3677 {
3678 	uint_t mtu = ill->ill_mtu;
3679 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3680 
3681 	if (iremtu != 0 && iremtu < mtu)
3682 		mtu = iremtu;
3683 
3684 	return (mtu);
3685 }
3686 
3687 /*
3688  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3689  * Assumes that ixa_ire, dce, and nce have already been set up.
3690  *
3691  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3692  * We avoid path MTU discovery if it is disabled with ndd.
3693  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3694  *
3695  * NOTE: We also used to turn it off for source routed packets. That
3696  * is no longer required since the dce is per final destination.
3697  */
3698 uint_t
3699 ip_get_pmtu(ip_xmit_attr_t *ixa)
3700 {
3701 	ip_stack_t	*ipst = ixa->ixa_ipst;
3702 	dce_t		*dce;
3703 	nce_t		*nce;
3704 	ire_t		*ire;
3705 	uint_t		pmtu;
3706 
3707 	ire = ixa->ixa_ire;
3708 	dce = ixa->ixa_dce;
3709 	nce = ixa->ixa_nce;
3710 
3711 	/*
3712 	 * If path MTU discovery has been turned off by ndd, then we ignore
3713 	 * any dce_pmtu and for IPv4 we will not set DF.
3714 	 */
3715 	if (!ipst->ips_ip_path_mtu_discovery)
3716 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3717 
3718 	pmtu = IP_MAXPACKET;
3719 	/*
3720 	 * Decide whether whether IPv4 sets DF
3721 	 * For IPv6 "no DF" means to use the 1280 mtu
3722 	 */
3723 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3724 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3725 	} else {
3726 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3727 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3728 			pmtu = IPV6_MIN_MTU;
3729 	}
3730 
3731 	/* Check if the PMTU is to old before we use it */
3732 	if ((dce->dce_flags & DCEF_PMTU) &&
3733 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3734 	    ipst->ips_ip_pathmtu_interval) {
3735 		/*
3736 		 * Older than 20 minutes. Drop the path MTU information.
3737 		 */
3738 		mutex_enter(&dce->dce_lock);
3739 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3740 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3741 		mutex_exit(&dce->dce_lock);
3742 		dce_increment_generation(dce);
3743 	}
3744 
3745 	/* The metrics on the route can lower the path MTU */
3746 	if (ire->ire_metrics.iulp_mtu != 0 &&
3747 	    ire->ire_metrics.iulp_mtu < pmtu)
3748 		pmtu = ire->ire_metrics.iulp_mtu;
3749 
3750 	/*
3751 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3752 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3753 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3754 	 */
3755 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3756 		if (dce->dce_flags & DCEF_PMTU) {
3757 			if (dce->dce_pmtu < pmtu)
3758 				pmtu = dce->dce_pmtu;
3759 
3760 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3761 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3762 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3763 			} else {
3764 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3765 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3766 			}
3767 		} else {
3768 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3769 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3770 		}
3771 	}
3772 
3773 	/*
3774 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3775 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3776 	 * mtu as IRE_LOOPBACK.
3777 	 */
3778 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3779 		uint_t loopback_mtu;
3780 
3781 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3782 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3783 
3784 		if (loopback_mtu < pmtu)
3785 			pmtu = loopback_mtu;
3786 	} else if (nce != NULL) {
3787 		/*
3788 		 * Make sure we don't exceed the interface MTU.
3789 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3790 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3791 		 * to tell the transport something larger than zero.
3792 		 */
3793 		if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3794 			pmtu = nce->nce_common->ncec_ill->ill_mtu;
3795 		if (nce->nce_common->ncec_ill != nce->nce_ill &&
3796 		    nce->nce_ill->ill_mtu < pmtu) {
3797 			/*
3798 			 * for interfaces in an IPMP group, the mtu of
3799 			 * the nce_ill (under_ill) could be different
3800 			 * from the mtu of the ncec_ill, so we take the
3801 			 * min of the two.
3802 			 */
3803 			pmtu = nce->nce_ill->ill_mtu;
3804 		}
3805 	}
3806 
3807 	/*
3808 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3809 	 * Only applies to IPv6.
3810 	 */
3811 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3812 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3813 			switch (ixa->ixa_use_min_mtu) {
3814 			case IPV6_USE_MIN_MTU_MULTICAST:
3815 				if (ire->ire_type & IRE_MULTICAST)
3816 					pmtu = IPV6_MIN_MTU;
3817 				break;
3818 			case IPV6_USE_MIN_MTU_ALWAYS:
3819 				pmtu = IPV6_MIN_MTU;
3820 				break;
3821 			case IPV6_USE_MIN_MTU_NEVER:
3822 				break;
3823 			}
3824 		} else {
3825 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3826 			if (ire->ire_type & IRE_MULTICAST)
3827 				pmtu = IPV6_MIN_MTU;
3828 		}
3829 	}
3830 
3831 	/*
3832 	 * After receiving an ICMPv6 "packet too big" message with a
3833 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3834 	 * will insert a 8-byte fragment header in every packet. We compensate
3835 	 * for those cases by returning a smaller path MTU to the ULP.
3836 	 *
3837 	 * In the case of CGTP then ip_output will add a fragment header.
3838 	 * Make sure there is room for it by telling a smaller number
3839 	 * to the transport.
3840 	 *
3841 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3842 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3843 	 * which is the size of the packets it can send.
3844 	 */
3845 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3846 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
3847 		    (ire->ire_flags & RTF_MULTIRT) ||
3848 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3849 			pmtu -= sizeof (ip6_frag_t);
3850 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3851 		}
3852 	}
3853 
3854 	return (pmtu);
3855 }
3856 
3857 /*
3858  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3859  * the final piece where we don't.  Return a pointer to the first mblk in the
3860  * result, and update the pointer to the next mblk to chew on.  If anything
3861  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3862  * NULL pointer.
3863  */
3864 mblk_t *
3865 ip_carve_mp(mblk_t **mpp, ssize_t len)
3866 {
3867 	mblk_t	*mp0;
3868 	mblk_t	*mp1;
3869 	mblk_t	*mp2;
3870 
3871 	if (!len || !mpp || !(mp0 = *mpp))
3872 		return (NULL);
3873 	/* If we aren't going to consume the first mblk, we need a dup. */
3874 	if (mp0->b_wptr - mp0->b_rptr > len) {
3875 		mp1 = dupb(mp0);
3876 		if (mp1) {
3877 			/* Partition the data between the two mblks. */
3878 			mp1->b_wptr = mp1->b_rptr + len;
3879 			mp0->b_rptr = mp1->b_wptr;
3880 			/*
3881 			 * after adjustments if mblk not consumed is now
3882 			 * unaligned, try to align it. If this fails free
3883 			 * all messages and let upper layer recover.
3884 			 */
3885 			if (!OK_32PTR(mp0->b_rptr)) {
3886 				if (!pullupmsg(mp0, -1)) {
3887 					freemsg(mp0);
3888 					freemsg(mp1);
3889 					*mpp = NULL;
3890 					return (NULL);
3891 				}
3892 			}
3893 		}
3894 		return (mp1);
3895 	}
3896 	/* Eat through as many mblks as we need to get len bytes. */
3897 	len -= mp0->b_wptr - mp0->b_rptr;
3898 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3899 		if (mp2->b_wptr - mp2->b_rptr > len) {
3900 			/*
3901 			 * We won't consume the entire last mblk.  Like
3902 			 * above, dup and partition it.
3903 			 */
3904 			mp1->b_cont = dupb(mp2);
3905 			mp1 = mp1->b_cont;
3906 			if (!mp1) {
3907 				/*
3908 				 * Trouble.  Rather than go to a lot of
3909 				 * trouble to clean up, we free the messages.
3910 				 * This won't be any worse than losing it on
3911 				 * the wire.
3912 				 */
3913 				freemsg(mp0);
3914 				freemsg(mp2);
3915 				*mpp = NULL;
3916 				return (NULL);
3917 			}
3918 			mp1->b_wptr = mp1->b_rptr + len;
3919 			mp2->b_rptr = mp1->b_wptr;
3920 			/*
3921 			 * after adjustments if mblk not consumed is now
3922 			 * unaligned, try to align it. If this fails free
3923 			 * all messages and let upper layer recover.
3924 			 */
3925 			if (!OK_32PTR(mp2->b_rptr)) {
3926 				if (!pullupmsg(mp2, -1)) {
3927 					freemsg(mp0);
3928 					freemsg(mp2);
3929 					*mpp = NULL;
3930 					return (NULL);
3931 				}
3932 			}
3933 			*mpp = mp2;
3934 			return (mp0);
3935 		}
3936 		/* Decrement len by the amount we just got. */
3937 		len -= mp2->b_wptr - mp2->b_rptr;
3938 	}
3939 	/*
3940 	 * len should be reduced to zero now.  If not our caller has
3941 	 * screwed up.
3942 	 */
3943 	if (len) {
3944 		/* Shouldn't happen! */
3945 		freemsg(mp0);
3946 		*mpp = NULL;
3947 		return (NULL);
3948 	}
3949 	/*
3950 	 * We consumed up to exactly the end of an mblk.  Detach the part
3951 	 * we are returning from the rest of the chain.
3952 	 */
3953 	mp1->b_cont = NULL;
3954 	*mpp = mp2;
3955 	return (mp0);
3956 }
3957 
3958 /* The ill stream is being unplumbed. Called from ip_close */
3959 int
3960 ip_modclose(ill_t *ill)
3961 {
3962 	boolean_t success;
3963 	ipsq_t	*ipsq;
3964 	ipif_t	*ipif;
3965 	queue_t	*q = ill->ill_rq;
3966 	ip_stack_t	*ipst = ill->ill_ipst;
3967 	int	i;
3968 	arl_ill_common_t *ai = ill->ill_common;
3969 
3970 	/*
3971 	 * The punlink prior to this may have initiated a capability
3972 	 * negotiation. But ipsq_enter will block until that finishes or
3973 	 * times out.
3974 	 */
3975 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
3976 
3977 	/*
3978 	 * Open/close/push/pop is guaranteed to be single threaded
3979 	 * per stream by STREAMS. FS guarantees that all references
3980 	 * from top are gone before close is called. So there can't
3981 	 * be another close thread that has set CONDEMNED on this ill.
3982 	 * and cause ipsq_enter to return failure.
3983 	 */
3984 	ASSERT(success);
3985 	ipsq = ill->ill_phyint->phyint_ipsq;
3986 
3987 	/*
3988 	 * Mark it condemned. No new reference will be made to this ill.
3989 	 * Lookup functions will return an error. Threads that try to
3990 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
3991 	 * that the refcnt will drop down to zero.
3992 	 */
3993 	mutex_enter(&ill->ill_lock);
3994 	ill->ill_state_flags |= ILL_CONDEMNED;
3995 	for (ipif = ill->ill_ipif; ipif != NULL;
3996 	    ipif = ipif->ipif_next) {
3997 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
3998 	}
3999 	/*
4000 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4001 	 * returns  error if ILL_CONDEMNED is set
4002 	 */
4003 	cv_broadcast(&ill->ill_cv);
4004 	mutex_exit(&ill->ill_lock);
4005 
4006 	/*
4007 	 * Send all the deferred DLPI messages downstream which came in
4008 	 * during the small window right before ipsq_enter(). We do this
4009 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4010 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4011 	 */
4012 	ill_dlpi_send_deferred(ill);
4013 
4014 	/*
4015 	 * Shut down fragmentation reassembly.
4016 	 * ill_frag_timer won't start a timer again.
4017 	 * Now cancel any existing timer
4018 	 */
4019 	(void) untimeout(ill->ill_frag_timer_id);
4020 	(void) ill_frag_timeout(ill, 0);
4021 
4022 	/*
4023 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4024 	 * this ill. Then wait for the refcnts to drop to zero.
4025 	 * ill_is_freeable checks whether the ill is really quiescent.
4026 	 * Then make sure that threads that are waiting to enter the
4027 	 * ipsq have seen the error returned by ipsq_enter and have
4028 	 * gone away. Then we call ill_delete_tail which does the
4029 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4030 	 */
4031 	ill_delete(ill);
4032 	mutex_enter(&ill->ill_lock);
4033 	while (!ill_is_freeable(ill))
4034 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4035 
4036 	while (ill->ill_waiters)
4037 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4038 
4039 	mutex_exit(&ill->ill_lock);
4040 
4041 	/*
4042 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4043 	 * it held until the end of the function since the cleanup
4044 	 * below needs to be able to use the ip_stack_t.
4045 	 */
4046 	netstack_hold(ipst->ips_netstack);
4047 
4048 	/* qprocsoff is done via ill_delete_tail */
4049 	ill_delete_tail(ill);
4050 	/*
4051 	 * synchronously wait for arp stream to unbind. After this, we
4052 	 * cannot get any data packets up from the driver.
4053 	 */
4054 	arp_unbind_complete(ill);
4055 	ASSERT(ill->ill_ipst == NULL);
4056 
4057 	/*
4058 	 * Walk through all conns and qenable those that have queued data.
4059 	 * Close synchronization needs this to
4060 	 * be done to ensure that all upper layers blocked
4061 	 * due to flow control to the closing device
4062 	 * get unblocked.
4063 	 */
4064 	ip1dbg(("ip_wsrv: walking\n"));
4065 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4066 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4067 	}
4068 
4069 	/*
4070 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4071 	 * stream is being torn down before ARP was plumbed (e.g.,
4072 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4073 	 * an error
4074 	 */
4075 	if (ai != NULL) {
4076 		ASSERT(!ill->ill_isv6);
4077 		mutex_enter(&ai->ai_lock);
4078 		ai->ai_ill = NULL;
4079 		if (ai->ai_arl == NULL) {
4080 			mutex_destroy(&ai->ai_lock);
4081 			kmem_free(ai, sizeof (*ai));
4082 		} else {
4083 			cv_signal(&ai->ai_ill_unplumb_done);
4084 			mutex_exit(&ai->ai_lock);
4085 		}
4086 	}
4087 
4088 	mutex_enter(&ipst->ips_ip_mi_lock);
4089 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4090 	mutex_exit(&ipst->ips_ip_mi_lock);
4091 
4092 	/*
4093 	 * credp could be null if the open didn't succeed and ip_modopen
4094 	 * itself calls ip_close.
4095 	 */
4096 	if (ill->ill_credp != NULL)
4097 		crfree(ill->ill_credp);
4098 
4099 	mutex_destroy(&ill->ill_saved_ire_lock);
4100 	mutex_destroy(&ill->ill_lock);
4101 	rw_destroy(&ill->ill_mcast_lock);
4102 	mutex_destroy(&ill->ill_mcast_serializer);
4103 	list_destroy(&ill->ill_nce);
4104 
4105 	/*
4106 	 * Now we are done with the module close pieces that
4107 	 * need the netstack_t.
4108 	 */
4109 	netstack_rele(ipst->ips_netstack);
4110 
4111 	mi_close_free((IDP)ill);
4112 	q->q_ptr = WR(q)->q_ptr = NULL;
4113 
4114 	ipsq_exit(ipsq);
4115 
4116 	return (0);
4117 }
4118 
4119 /*
4120  * This is called as part of close() for IP, UDP, ICMP, and RTS
4121  * in order to quiesce the conn.
4122  */
4123 void
4124 ip_quiesce_conn(conn_t *connp)
4125 {
4126 	boolean_t	drain_cleanup_reqd = B_FALSE;
4127 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4128 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4129 	ip_stack_t	*ipst;
4130 
4131 	ASSERT(!IPCL_IS_TCP(connp));
4132 	ipst = connp->conn_netstack->netstack_ip;
4133 
4134 	/*
4135 	 * Mark the conn as closing, and this conn must not be
4136 	 * inserted in future into any list. Eg. conn_drain_insert(),
4137 	 * won't insert this conn into the conn_drain_list.
4138 	 *
4139 	 * conn_idl, and conn_ilg cannot get set henceforth.
4140 	 */
4141 	mutex_enter(&connp->conn_lock);
4142 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4143 	connp->conn_state_flags |= CONN_CLOSING;
4144 	if (connp->conn_idl != NULL)
4145 		drain_cleanup_reqd = B_TRUE;
4146 	if (connp->conn_oper_pending_ill != NULL)
4147 		conn_ioctl_cleanup_reqd = B_TRUE;
4148 	if (connp->conn_dhcpinit_ill != NULL) {
4149 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4150 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4151 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4152 		connp->conn_dhcpinit_ill = NULL;
4153 	}
4154 	if (connp->conn_ilg != NULL)
4155 		ilg_cleanup_reqd = B_TRUE;
4156 	mutex_exit(&connp->conn_lock);
4157 
4158 	if (conn_ioctl_cleanup_reqd)
4159 		conn_ioctl_cleanup(connp);
4160 
4161 	if (is_system_labeled() && connp->conn_anon_port) {
4162 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4163 		    connp->conn_mlp_type, connp->conn_proto,
4164 		    ntohs(connp->conn_lport), B_FALSE);
4165 		connp->conn_anon_port = 0;
4166 	}
4167 	connp->conn_mlp_type = mlptSingle;
4168 
4169 	/*
4170 	 * Remove this conn from any fanout list it is on.
4171 	 * and then wait for any threads currently operating
4172 	 * on this endpoint to finish
4173 	 */
4174 	ipcl_hash_remove(connp);
4175 
4176 	/*
4177 	 * Remove this conn from the drain list, and do any other cleanup that
4178 	 * may be required.  (TCP conns are never flow controlled, and
4179 	 * conn_idl will be NULL.)
4180 	 */
4181 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4182 		idl_t *idl = connp->conn_idl;
4183 
4184 		mutex_enter(&idl->idl_lock);
4185 		conn_drain(connp, B_TRUE);
4186 		mutex_exit(&idl->idl_lock);
4187 	}
4188 
4189 	if (connp == ipst->ips_ip_g_mrouter)
4190 		(void) ip_mrouter_done(ipst);
4191 
4192 	if (ilg_cleanup_reqd)
4193 		ilg_delete_all(connp);
4194 
4195 	/*
4196 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4197 	 * callers from write side can't be there now because close
4198 	 * is in progress. The only other caller is ipcl_walk
4199 	 * which checks for the condemned flag.
4200 	 */
4201 	mutex_enter(&connp->conn_lock);
4202 	connp->conn_state_flags |= CONN_CONDEMNED;
4203 	while (connp->conn_ref != 1)
4204 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4205 	connp->conn_state_flags |= CONN_QUIESCED;
4206 	mutex_exit(&connp->conn_lock);
4207 }
4208 
4209 /* ARGSUSED */
4210 int
4211 ip_close(queue_t *q, int flags)
4212 {
4213 	conn_t		*connp;
4214 
4215 	/*
4216 	 * Call the appropriate delete routine depending on whether this is
4217 	 * a module or device.
4218 	 */
4219 	if (WR(q)->q_next != NULL) {
4220 		/* This is a module close */
4221 		return (ip_modclose((ill_t *)q->q_ptr));
4222 	}
4223 
4224 	connp = q->q_ptr;
4225 	ip_quiesce_conn(connp);
4226 
4227 	qprocsoff(q);
4228 
4229 	/*
4230 	 * Now we are truly single threaded on this stream, and can
4231 	 * delete the things hanging off the connp, and finally the connp.
4232 	 * We removed this connp from the fanout list, it cannot be
4233 	 * accessed thru the fanouts, and we already waited for the
4234 	 * conn_ref to drop to 0. We are already in close, so
4235 	 * there cannot be any other thread from the top. qprocsoff
4236 	 * has completed, and service has completed or won't run in
4237 	 * future.
4238 	 */
4239 	ASSERT(connp->conn_ref == 1);
4240 
4241 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4242 
4243 	connp->conn_ref--;
4244 	ipcl_conn_destroy(connp);
4245 
4246 	q->q_ptr = WR(q)->q_ptr = NULL;
4247 	return (0);
4248 }
4249 
4250 /*
4251  * Wapper around putnext() so that ip_rts_request can merely use
4252  * conn_recv.
4253  */
4254 /*ARGSUSED2*/
4255 static void
4256 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4257 {
4258 	conn_t *connp = (conn_t *)arg1;
4259 
4260 	putnext(connp->conn_rq, mp);
4261 }
4262 
4263 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4264 /* ARGSUSED */
4265 static void
4266 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4267 {
4268 	freemsg(mp);
4269 }
4270 
4271 /*
4272  * Called when the module is about to be unloaded
4273  */
4274 void
4275 ip_ddi_destroy(void)
4276 {
4277 	tnet_fini();
4278 
4279 	icmp_ddi_g_destroy();
4280 	rts_ddi_g_destroy();
4281 	udp_ddi_g_destroy();
4282 	sctp_ddi_g_destroy();
4283 	tcp_ddi_g_destroy();
4284 	ilb_ddi_g_destroy();
4285 	dce_g_destroy();
4286 	ipsec_policy_g_destroy();
4287 	ipcl_g_destroy();
4288 	ip_net_g_destroy();
4289 	ip_ire_g_fini();
4290 	inet_minor_destroy(ip_minor_arena_sa);
4291 #if defined(_LP64)
4292 	inet_minor_destroy(ip_minor_arena_la);
4293 #endif
4294 
4295 #ifdef DEBUG
4296 	list_destroy(&ip_thread_list);
4297 	rw_destroy(&ip_thread_rwlock);
4298 	tsd_destroy(&ip_thread_data);
4299 #endif
4300 
4301 	netstack_unregister(NS_IP);
4302 }
4303 
4304 /*
4305  * First step in cleanup.
4306  */
4307 /* ARGSUSED */
4308 static void
4309 ip_stack_shutdown(netstackid_t stackid, void *arg)
4310 {
4311 	ip_stack_t *ipst = (ip_stack_t *)arg;
4312 
4313 #ifdef NS_DEBUG
4314 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4315 #endif
4316 
4317 	/*
4318 	 * Perform cleanup for special interfaces (loopback and IPMP).
4319 	 */
4320 	ip_interface_cleanup(ipst);
4321 
4322 	/*
4323 	 * The *_hook_shutdown()s start the process of notifying any
4324 	 * consumers that things are going away.... nothing is destroyed.
4325 	 */
4326 	ipv4_hook_shutdown(ipst);
4327 	ipv6_hook_shutdown(ipst);
4328 	arp_hook_shutdown(ipst);
4329 
4330 	mutex_enter(&ipst->ips_capab_taskq_lock);
4331 	ipst->ips_capab_taskq_quit = B_TRUE;
4332 	cv_signal(&ipst->ips_capab_taskq_cv);
4333 	mutex_exit(&ipst->ips_capab_taskq_lock);
4334 }
4335 
4336 /*
4337  * Free the IP stack instance.
4338  */
4339 static void
4340 ip_stack_fini(netstackid_t stackid, void *arg)
4341 {
4342 	ip_stack_t *ipst = (ip_stack_t *)arg;
4343 	int ret;
4344 
4345 #ifdef NS_DEBUG
4346 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4347 #endif
4348 	/*
4349 	 * At this point, all of the notifications that the events and
4350 	 * protocols are going away have been run, meaning that we can
4351 	 * now set about starting to clean things up.
4352 	 */
4353 	ipobs_fini(ipst);
4354 	ipv4_hook_destroy(ipst);
4355 	ipv6_hook_destroy(ipst);
4356 	arp_hook_destroy(ipst);
4357 	ip_net_destroy(ipst);
4358 
4359 	ipmp_destroy(ipst);
4360 
4361 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4362 	ipst->ips_ip_mibkp = NULL;
4363 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4364 	ipst->ips_icmp_mibkp = NULL;
4365 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4366 	ipst->ips_ip_kstat = NULL;
4367 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4368 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4369 	ipst->ips_ip6_kstat = NULL;
4370 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4371 
4372 	kmem_free(ipst->ips_propinfo_tbl,
4373 	    ip_propinfo_count * sizeof (mod_prop_info_t));
4374 	ipst->ips_propinfo_tbl = NULL;
4375 
4376 	dce_stack_destroy(ipst);
4377 	ip_mrouter_stack_destroy(ipst);
4378 
4379 	ret = untimeout(ipst->ips_igmp_timeout_id);
4380 	if (ret == -1) {
4381 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4382 	} else {
4383 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4384 		ipst->ips_igmp_timeout_id = 0;
4385 	}
4386 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4387 	if (ret == -1) {
4388 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4389 	} else {
4390 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4391 		ipst->ips_igmp_slowtimeout_id = 0;
4392 	}
4393 	ret = untimeout(ipst->ips_mld_timeout_id);
4394 	if (ret == -1) {
4395 		ASSERT(ipst->ips_mld_timeout_id == 0);
4396 	} else {
4397 		ASSERT(ipst->ips_mld_timeout_id != 0);
4398 		ipst->ips_mld_timeout_id = 0;
4399 	}
4400 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4401 	if (ret == -1) {
4402 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4403 	} else {
4404 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4405 		ipst->ips_mld_slowtimeout_id = 0;
4406 	}
4407 
4408 	ip_ire_fini(ipst);
4409 	ip6_asp_free(ipst);
4410 	conn_drain_fini(ipst);
4411 	ipcl_destroy(ipst);
4412 
4413 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4414 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4415 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4416 	ipst->ips_ndp4 = NULL;
4417 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4418 	ipst->ips_ndp6 = NULL;
4419 
4420 	if (ipst->ips_loopback_ksp != NULL) {
4421 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4422 		ipst->ips_loopback_ksp = NULL;
4423 	}
4424 
4425 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4426 	cv_destroy(&ipst->ips_capab_taskq_cv);
4427 
4428 	rw_destroy(&ipst->ips_srcid_lock);
4429 
4430 	mutex_destroy(&ipst->ips_ip_mi_lock);
4431 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4432 
4433 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4434 	mutex_destroy(&ipst->ips_mld_timer_lock);
4435 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4436 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4437 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4438 	rw_destroy(&ipst->ips_ill_g_lock);
4439 
4440 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4441 	ipst->ips_phyint_g_list = NULL;
4442 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4443 	ipst->ips_ill_g_heads = NULL;
4444 
4445 	ldi_ident_release(ipst->ips_ldi_ident);
4446 	kmem_free(ipst, sizeof (*ipst));
4447 }
4448 
4449 /*
4450  * This function is called from the TSD destructor, and is used to debug
4451  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4452  * details.
4453  */
4454 static void
4455 ip_thread_exit(void *phash)
4456 {
4457 	th_hash_t *thh = phash;
4458 
4459 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4460 	list_remove(&ip_thread_list, thh);
4461 	rw_exit(&ip_thread_rwlock);
4462 	mod_hash_destroy_hash(thh->thh_hash);
4463 	kmem_free(thh, sizeof (*thh));
4464 }
4465 
4466 /*
4467  * Called when the IP kernel module is loaded into the kernel
4468  */
4469 void
4470 ip_ddi_init(void)
4471 {
4472 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4473 
4474 	/*
4475 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4476 	 * initial devices: ip, ip6, tcp, tcp6.
4477 	 */
4478 	/*
4479 	 * If this is a 64-bit kernel, then create two separate arenas -
4480 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4481 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4482 	 */
4483 	ip_minor_arena_la = NULL;
4484 	ip_minor_arena_sa = NULL;
4485 #if defined(_LP64)
4486 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4487 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4488 		cmn_err(CE_PANIC,
4489 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4490 	}
4491 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4492 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4493 		cmn_err(CE_PANIC,
4494 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4495 	}
4496 #else
4497 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4498 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4499 		cmn_err(CE_PANIC,
4500 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4501 	}
4502 #endif
4503 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4504 
4505 	ipcl_g_init();
4506 	ip_ire_g_init();
4507 	ip_net_g_init();
4508 
4509 #ifdef DEBUG
4510 	tsd_create(&ip_thread_data, ip_thread_exit);
4511 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4512 	list_create(&ip_thread_list, sizeof (th_hash_t),
4513 	    offsetof(th_hash_t, thh_link));
4514 #endif
4515 	ipsec_policy_g_init();
4516 	tcp_ddi_g_init();
4517 	sctp_ddi_g_init();
4518 	dce_g_init();
4519 
4520 	/*
4521 	 * We want to be informed each time a stack is created or
4522 	 * destroyed in the kernel, so we can maintain the
4523 	 * set of udp_stack_t's.
4524 	 */
4525 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4526 	    ip_stack_fini);
4527 
4528 	tnet_init();
4529 
4530 	udp_ddi_g_init();
4531 	rts_ddi_g_init();
4532 	icmp_ddi_g_init();
4533 	ilb_ddi_g_init();
4534 }
4535 
4536 /*
4537  * Initialize the IP stack instance.
4538  */
4539 static void *
4540 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4541 {
4542 	ip_stack_t	*ipst;
4543 	size_t		arrsz;
4544 	major_t		major;
4545 
4546 #ifdef NS_DEBUG
4547 	printf("ip_stack_init(stack %d)\n", stackid);
4548 #endif
4549 
4550 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4551 	ipst->ips_netstack = ns;
4552 
4553 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4554 	    KM_SLEEP);
4555 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4556 	    KM_SLEEP);
4557 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4558 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4559 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4560 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4561 
4562 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4563 	ipst->ips_igmp_deferred_next = INFINITY;
4564 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4565 	ipst->ips_mld_deferred_next = INFINITY;
4566 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4567 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4568 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4569 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4570 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4571 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4572 
4573 	ipcl_init(ipst);
4574 	ip_ire_init(ipst);
4575 	ip6_asp_init(ipst);
4576 	ipif_init(ipst);
4577 	conn_drain_init(ipst);
4578 	ip_mrouter_stack_init(ipst);
4579 	dce_stack_init(ipst);
4580 
4581 	ipst->ips_ip_multirt_log_interval = 1000;
4582 
4583 	ipst->ips_ill_index = 1;
4584 
4585 	ipst->ips_saved_ip_forwarding = -1;
4586 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4587 
4588 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4589 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4590 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4591 
4592 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4593 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4594 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4595 	ipst->ips_ip6_kstat =
4596 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4597 
4598 	ipst->ips_ip_src_id = 1;
4599 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4600 
4601 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4602 
4603 	ip_net_init(ipst, ns);
4604 	ipv4_hook_init(ipst);
4605 	ipv6_hook_init(ipst);
4606 	arp_hook_init(ipst);
4607 	ipmp_init(ipst);
4608 	ipobs_init(ipst);
4609 
4610 	/*
4611 	 * Create the taskq dispatcher thread and initialize related stuff.
4612 	 */
4613 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4614 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4615 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4616 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4617 
4618 	major = mod_name_to_major(INET_NAME);
4619 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4620 	return (ipst);
4621 }
4622 
4623 /*
4624  * Allocate and initialize a DLPI template of the specified length.  (May be
4625  * called as writer.)
4626  */
4627 mblk_t *
4628 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4629 {
4630 	mblk_t	*mp;
4631 
4632 	mp = allocb(len, BPRI_MED);
4633 	if (!mp)
4634 		return (NULL);
4635 
4636 	/*
4637 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4638 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4639 	 * that other DLPI are M_PROTO.
4640 	 */
4641 	if (prim == DL_INFO_REQ) {
4642 		mp->b_datap->db_type = M_PCPROTO;
4643 	} else {
4644 		mp->b_datap->db_type = M_PROTO;
4645 	}
4646 
4647 	mp->b_wptr = mp->b_rptr + len;
4648 	bzero(mp->b_rptr, len);
4649 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4650 	return (mp);
4651 }
4652 
4653 /*
4654  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4655  */
4656 mblk_t *
4657 ip_dlnotify_alloc(uint_t notification, uint_t data)
4658 {
4659 	dl_notify_ind_t	*notifyp;
4660 	mblk_t		*mp;
4661 
4662 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4663 		return (NULL);
4664 
4665 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4666 	notifyp->dl_notification = notification;
4667 	notifyp->dl_data = data;
4668 	return (mp);
4669 }
4670 
4671 /*
4672  * Debug formatting routine.  Returns a character string representation of the
4673  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4674  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4675  *
4676  * Once the ndd table-printing interfaces are removed, this can be changed to
4677  * standard dotted-decimal form.
4678  */
4679 char *
4680 ip_dot_addr(ipaddr_t addr, char *buf)
4681 {
4682 	uint8_t *ap = (uint8_t *)&addr;
4683 
4684 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4685 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4686 	return (buf);
4687 }
4688 
4689 /*
4690  * Write the given MAC address as a printable string in the usual colon-
4691  * separated format.
4692  */
4693 const char *
4694 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4695 {
4696 	char *bp;
4697 
4698 	if (alen == 0 || buflen < 4)
4699 		return ("?");
4700 	bp = buf;
4701 	for (;;) {
4702 		/*
4703 		 * If there are more MAC address bytes available, but we won't
4704 		 * have any room to print them, then add "..." to the string
4705 		 * instead.  See below for the 'magic number' explanation.
4706 		 */
4707 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4708 			(void) strcpy(bp, "...");
4709 			break;
4710 		}
4711 		(void) sprintf(bp, "%02x", *addr++);
4712 		bp += 2;
4713 		if (--alen == 0)
4714 			break;
4715 		*bp++ = ':';
4716 		buflen -= 3;
4717 		/*
4718 		 * At this point, based on the first 'if' statement above,
4719 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4720 		 * buflen >= 4.  The first case leaves room for the final "xx"
4721 		 * number and trailing NUL byte.  The second leaves room for at
4722 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4723 		 * that statement.
4724 		 */
4725 	}
4726 	return (buf);
4727 }
4728 
4729 /*
4730  * Called when it is conceptually a ULP that would sent the packet
4731  * e.g., port unreachable and protocol unreachable. Check that the packet
4732  * would have passed the IPsec global policy before sending the error.
4733  *
4734  * Send an ICMP error after patching up the packet appropriately.
4735  * Uses ip_drop_input and bumps the appropriate MIB.
4736  */
4737 void
4738 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4739     ip_recv_attr_t *ira)
4740 {
4741 	ipha_t		*ipha;
4742 	boolean_t	secure;
4743 	ill_t		*ill = ira->ira_ill;
4744 	ip_stack_t	*ipst = ill->ill_ipst;
4745 	netstack_t	*ns = ipst->ips_netstack;
4746 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4747 
4748 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4749 
4750 	/*
4751 	 * We are generating an icmp error for some inbound packet.
4752 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4753 	 * Before we generate an error, check with global policy
4754 	 * to see whether this is allowed to enter the system. As
4755 	 * there is no "conn", we are checking with global policy.
4756 	 */
4757 	ipha = (ipha_t *)mp->b_rptr;
4758 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4759 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4760 		if (mp == NULL)
4761 			return;
4762 	}
4763 
4764 	/* We never send errors for protocols that we do implement */
4765 	if (ira->ira_protocol == IPPROTO_ICMP ||
4766 	    ira->ira_protocol == IPPROTO_IGMP) {
4767 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4768 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4769 		freemsg(mp);
4770 		return;
4771 	}
4772 	/*
4773 	 * Have to correct checksum since
4774 	 * the packet might have been
4775 	 * fragmented and the reassembly code in ip_rput
4776 	 * does not restore the IP checksum.
4777 	 */
4778 	ipha->ipha_hdr_checksum = 0;
4779 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4780 
4781 	switch (icmp_type) {
4782 	case ICMP_DEST_UNREACHABLE:
4783 		switch (icmp_code) {
4784 		case ICMP_PROTOCOL_UNREACHABLE:
4785 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4786 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4787 			break;
4788 		case ICMP_PORT_UNREACHABLE:
4789 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4790 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4791 			break;
4792 		}
4793 
4794 		icmp_unreachable(mp, icmp_code, ira);
4795 		break;
4796 	default:
4797 #ifdef DEBUG
4798 		panic("ip_fanout_send_icmp_v4: wrong type");
4799 		/*NOTREACHED*/
4800 #else
4801 		freemsg(mp);
4802 		break;
4803 #endif
4804 	}
4805 }
4806 
4807 /*
4808  * Used to send an ICMP error message when a packet is received for
4809  * a protocol that is not supported. The mblk passed as argument
4810  * is consumed by this function.
4811  */
4812 void
4813 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4814 {
4815 	ipha_t		*ipha;
4816 
4817 	ipha = (ipha_t *)mp->b_rptr;
4818 	if (ira->ira_flags & IRAF_IS_IPV4) {
4819 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4820 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4821 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4822 	} else {
4823 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4824 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4825 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4826 	}
4827 }
4828 
4829 /*
4830  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4831  * Handles IPv4 and IPv6.
4832  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4833  * Caller is responsible for dropping references to the conn.
4834  */
4835 void
4836 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4837     ip_recv_attr_t *ira)
4838 {
4839 	ill_t		*ill = ira->ira_ill;
4840 	ip_stack_t	*ipst = ill->ill_ipst;
4841 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4842 	boolean_t	secure;
4843 	uint_t		protocol = ira->ira_protocol;
4844 	iaflags_t	iraflags = ira->ira_flags;
4845 	queue_t		*rq;
4846 
4847 	secure = iraflags & IRAF_IPSEC_SECURE;
4848 
4849 	rq = connp->conn_rq;
4850 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4851 		switch (protocol) {
4852 		case IPPROTO_ICMPV6:
4853 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4854 			break;
4855 		case IPPROTO_ICMP:
4856 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4857 			break;
4858 		default:
4859 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4860 			break;
4861 		}
4862 		freemsg(mp);
4863 		return;
4864 	}
4865 
4866 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4867 
4868 	if (((iraflags & IRAF_IS_IPV4) ?
4869 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4870 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4871 	    secure) {
4872 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4873 		    ip6h, ira);
4874 		if (mp == NULL) {
4875 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4876 			/* Note that mp is NULL */
4877 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4878 			return;
4879 		}
4880 	}
4881 
4882 	if (iraflags & IRAF_ICMP_ERROR) {
4883 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4884 	} else {
4885 		ill_t *rill = ira->ira_rill;
4886 
4887 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4888 		ira->ira_ill = ira->ira_rill = NULL;
4889 		/* Send it upstream */
4890 		(connp->conn_recv)(connp, mp, NULL, ira);
4891 		ira->ira_ill = ill;
4892 		ira->ira_rill = rill;
4893 	}
4894 }
4895 
4896 /*
4897  * Handle protocols with which IP is less intimate.  There
4898  * can be more than one stream bound to a particular
4899  * protocol.  When this is the case, normally each one gets a copy
4900  * of any incoming packets.
4901  *
4902  * IPsec NOTE :
4903  *
4904  * Don't allow a secure packet going up a non-secure connection.
4905  * We don't allow this because
4906  *
4907  * 1) Reply might go out in clear which will be dropped at
4908  *    the sending side.
4909  * 2) If the reply goes out in clear it will give the
4910  *    adversary enough information for getting the key in
4911  *    most of the cases.
4912  *
4913  * Moreover getting a secure packet when we expect clear
4914  * implies that SA's were added without checking for
4915  * policy on both ends. This should not happen once ISAKMP
4916  * is used to negotiate SAs as SAs will be added only after
4917  * verifying the policy.
4918  *
4919  * Zones notes:
4920  * Earlier in ip_input on a system with multiple shared-IP zones we
4921  * duplicate the multicast and broadcast packets and send them up
4922  * with each explicit zoneid that exists on that ill.
4923  * This means that here we can match the zoneid with SO_ALLZONES being special.
4924  */
4925 void
4926 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
4927 {
4928 	mblk_t		*mp1;
4929 	ipaddr_t	laddr;
4930 	conn_t		*connp, *first_connp, *next_connp;
4931 	connf_t		*connfp;
4932 	ill_t		*ill = ira->ira_ill;
4933 	ip_stack_t	*ipst = ill->ill_ipst;
4934 
4935 	laddr = ipha->ipha_dst;
4936 
4937 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
4938 	mutex_enter(&connfp->connf_lock);
4939 	connp = connfp->connf_head;
4940 	for (connp = connfp->connf_head; connp != NULL;
4941 	    connp = connp->conn_next) {
4942 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4943 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4944 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4945 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
4946 			break;
4947 		}
4948 	}
4949 
4950 	if (connp == NULL) {
4951 		/*
4952 		 * No one bound to these addresses.  Is
4953 		 * there a client that wants all
4954 		 * unclaimed datagrams?
4955 		 */
4956 		mutex_exit(&connfp->connf_lock);
4957 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4958 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4959 		return;
4960 	}
4961 
4962 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
4963 
4964 	CONN_INC_REF(connp);
4965 	first_connp = connp;
4966 	connp = connp->conn_next;
4967 
4968 	for (;;) {
4969 		while (connp != NULL) {
4970 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4971 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4972 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4973 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
4974 			    ira, connp)))
4975 				break;
4976 			connp = connp->conn_next;
4977 		}
4978 
4979 		if (connp == NULL) {
4980 			/* No more interested clients */
4981 			connp = first_connp;
4982 			break;
4983 		}
4984 		if (((mp1 = dupmsg(mp)) == NULL) &&
4985 		    ((mp1 = copymsg(mp)) == NULL)) {
4986 			/* Memory allocation failed */
4987 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4988 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4989 			connp = first_connp;
4990 			break;
4991 		}
4992 
4993 		CONN_INC_REF(connp);
4994 		mutex_exit(&connfp->connf_lock);
4995 
4996 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
4997 		    ira);
4998 
4999 		mutex_enter(&connfp->connf_lock);
5000 		/* Follow the next pointer before releasing the conn. */
5001 		next_connp = connp->conn_next;
5002 		CONN_DEC_REF(connp);
5003 		connp = next_connp;
5004 	}
5005 
5006 	/* Last one.  Send it upstream. */
5007 	mutex_exit(&connfp->connf_lock);
5008 
5009 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5010 
5011 	CONN_DEC_REF(connp);
5012 }
5013 
5014 /*
5015  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5016  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5017  * is not consumed.
5018  *
5019  * One of three things can happen, all of which affect the passed-in mblk:
5020  *
5021  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5022  *
5023  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5024  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5025  *
5026  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5027  */
5028 mblk_t *
5029 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5030 {
5031 	int shift, plen, iph_len;
5032 	ipha_t *ipha;
5033 	udpha_t *udpha;
5034 	uint32_t *spi;
5035 	uint32_t esp_ports;
5036 	uint8_t *orptr;
5037 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5038 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5039 
5040 	ipha = (ipha_t *)mp->b_rptr;
5041 	iph_len = ira->ira_ip_hdr_length;
5042 	plen = ira->ira_pktlen;
5043 
5044 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5045 		/*
5046 		 * Most likely a keepalive for the benefit of an intervening
5047 		 * NAT.  These aren't for us, per se, so drop it.
5048 		 *
5049 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5050 		 * byte packets (keepalives are 1-byte), but we'll drop them
5051 		 * also.
5052 		 */
5053 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5054 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5055 		return (NULL);
5056 	}
5057 
5058 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5059 		/* might as well pull it all up - it might be ESP. */
5060 		if (!pullupmsg(mp, -1)) {
5061 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5062 			    DROPPER(ipss, ipds_esp_nomem),
5063 			    &ipss->ipsec_dropper);
5064 			return (NULL);
5065 		}
5066 
5067 		ipha = (ipha_t *)mp->b_rptr;
5068 	}
5069 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5070 	if (*spi == 0) {
5071 		/* UDP packet - remove 0-spi. */
5072 		shift = sizeof (uint32_t);
5073 	} else {
5074 		/* ESP-in-UDP packet - reduce to ESP. */
5075 		ipha->ipha_protocol = IPPROTO_ESP;
5076 		shift = sizeof (udpha_t);
5077 	}
5078 
5079 	/* Fix IP header */
5080 	ira->ira_pktlen = (plen - shift);
5081 	ipha->ipha_length = htons(ira->ira_pktlen);
5082 	ipha->ipha_hdr_checksum = 0;
5083 
5084 	orptr = mp->b_rptr;
5085 	mp->b_rptr += shift;
5086 
5087 	udpha = (udpha_t *)(orptr + iph_len);
5088 	if (*spi == 0) {
5089 		ASSERT((uint8_t *)ipha == orptr);
5090 		udpha->uha_length = htons(plen - shift - iph_len);
5091 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5092 		esp_ports = 0;
5093 	} else {
5094 		esp_ports = *((uint32_t *)udpha);
5095 		ASSERT(esp_ports != 0);
5096 	}
5097 	ovbcopy(orptr, orptr + shift, iph_len);
5098 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5099 		ipha = (ipha_t *)(orptr + shift);
5100 
5101 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5102 		ira->ira_esp_udp_ports = esp_ports;
5103 		ip_fanout_v4(mp, ipha, ira);
5104 		return (NULL);
5105 	}
5106 	return (mp);
5107 }
5108 
5109 /*
5110  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5111  * Handles IPv4 and IPv6.
5112  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5113  * Caller is responsible for dropping references to the conn.
5114  */
5115 void
5116 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5117     ip_recv_attr_t *ira)
5118 {
5119 	ill_t		*ill = ira->ira_ill;
5120 	ip_stack_t	*ipst = ill->ill_ipst;
5121 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5122 	boolean_t	secure;
5123 	iaflags_t	iraflags = ira->ira_flags;
5124 
5125 	secure = iraflags & IRAF_IPSEC_SECURE;
5126 
5127 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5128 	    !canputnext(connp->conn_rq)) {
5129 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5130 		freemsg(mp);
5131 		return;
5132 	}
5133 
5134 	if (((iraflags & IRAF_IS_IPV4) ?
5135 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5136 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5137 	    secure) {
5138 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5139 		    ip6h, ira);
5140 		if (mp == NULL) {
5141 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5142 			/* Note that mp is NULL */
5143 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5144 			return;
5145 		}
5146 	}
5147 
5148 	/*
5149 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5150 	 * check. Only ip_fanout_v4 has that check.
5151 	 */
5152 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5153 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5154 	} else {
5155 		ill_t *rill = ira->ira_rill;
5156 
5157 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5158 		ira->ira_ill = ira->ira_rill = NULL;
5159 		/* Send it upstream */
5160 		(connp->conn_recv)(connp, mp, NULL, ira);
5161 		ira->ira_ill = ill;
5162 		ira->ira_rill = rill;
5163 	}
5164 }
5165 
5166 /*
5167  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5168  * (Unicast fanout is handled in ip_input_v4.)
5169  *
5170  * If SO_REUSEADDR is set all multicast and broadcast packets
5171  * will be delivered to all conns bound to the same port.
5172  *
5173  * If there is at least one matching AF_INET receiver, then we will
5174  * ignore any AF_INET6 receivers.
5175  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5176  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5177  * packets.
5178  *
5179  * Zones notes:
5180  * Earlier in ip_input on a system with multiple shared-IP zones we
5181  * duplicate the multicast and broadcast packets and send them up
5182  * with each explicit zoneid that exists on that ill.
5183  * This means that here we can match the zoneid with SO_ALLZONES being special.
5184  */
5185 void
5186 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5187     ip_recv_attr_t *ira)
5188 {
5189 	ipaddr_t	laddr;
5190 	in6_addr_t	v6faddr;
5191 	conn_t		*connp;
5192 	connf_t		*connfp;
5193 	ipaddr_t	faddr;
5194 	ill_t		*ill = ira->ira_ill;
5195 	ip_stack_t	*ipst = ill->ill_ipst;
5196 
5197 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5198 
5199 	laddr = ipha->ipha_dst;
5200 	faddr = ipha->ipha_src;
5201 
5202 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5203 	mutex_enter(&connfp->connf_lock);
5204 	connp = connfp->connf_head;
5205 
5206 	/*
5207 	 * If SO_REUSEADDR has been set on the first we send the
5208 	 * packet to all clients that have joined the group and
5209 	 * match the port.
5210 	 */
5211 	while (connp != NULL) {
5212 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5213 		    conn_wantpacket(connp, ira, ipha) &&
5214 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5215 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5216 			break;
5217 		connp = connp->conn_next;
5218 	}
5219 
5220 	if (connp == NULL)
5221 		goto notfound;
5222 
5223 	CONN_INC_REF(connp);
5224 
5225 	if (connp->conn_reuseaddr) {
5226 		conn_t		*first_connp = connp;
5227 		conn_t		*next_connp;
5228 		mblk_t		*mp1;
5229 
5230 		connp = connp->conn_next;
5231 		for (;;) {
5232 			while (connp != NULL) {
5233 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5234 				    fport, faddr) &&
5235 				    conn_wantpacket(connp, ira, ipha) &&
5236 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5237 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5238 				    ira, connp)))
5239 					break;
5240 				connp = connp->conn_next;
5241 			}
5242 			if (connp == NULL) {
5243 				/* No more interested clients */
5244 				connp = first_connp;
5245 				break;
5246 			}
5247 			if (((mp1 = dupmsg(mp)) == NULL) &&
5248 			    ((mp1 = copymsg(mp)) == NULL)) {
5249 				/* Memory allocation failed */
5250 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5251 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5252 				connp = first_connp;
5253 				break;
5254 			}
5255 			CONN_INC_REF(connp);
5256 			mutex_exit(&connfp->connf_lock);
5257 
5258 			IP_STAT(ipst, ip_udp_fanmb);
5259 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5260 			    NULL, ira);
5261 			mutex_enter(&connfp->connf_lock);
5262 			/* Follow the next pointer before releasing the conn */
5263 			next_connp = connp->conn_next;
5264 			CONN_DEC_REF(connp);
5265 			connp = next_connp;
5266 		}
5267 	}
5268 
5269 	/* Last one.  Send it upstream. */
5270 	mutex_exit(&connfp->connf_lock);
5271 	IP_STAT(ipst, ip_udp_fanmb);
5272 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5273 	CONN_DEC_REF(connp);
5274 	return;
5275 
5276 notfound:
5277 	mutex_exit(&connfp->connf_lock);
5278 	/*
5279 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5280 	 * have already been matched above, since they live in the IPv4
5281 	 * fanout tables. This implies we only need to
5282 	 * check for IPv6 in6addr_any endpoints here.
5283 	 * Thus we compare using ipv6_all_zeros instead of the destination
5284 	 * address, except for the multicast group membership lookup which
5285 	 * uses the IPv4 destination.
5286 	 */
5287 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5288 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5289 	mutex_enter(&connfp->connf_lock);
5290 	connp = connfp->connf_head;
5291 	/*
5292 	 * IPv4 multicast packet being delivered to an AF_INET6
5293 	 * in6addr_any endpoint.
5294 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5295 	 * and not conn_wantpacket_v6() since any multicast membership is
5296 	 * for an IPv4-mapped multicast address.
5297 	 */
5298 	while (connp != NULL) {
5299 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5300 		    fport, v6faddr) &&
5301 		    conn_wantpacket(connp, ira, ipha) &&
5302 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5303 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5304 			break;
5305 		connp = connp->conn_next;
5306 	}
5307 
5308 	if (connp == NULL) {
5309 		/*
5310 		 * No one bound to this port.  Is
5311 		 * there a client that wants all
5312 		 * unclaimed datagrams?
5313 		 */
5314 		mutex_exit(&connfp->connf_lock);
5315 
5316 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5317 		    NULL) {
5318 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5319 			ip_fanout_proto_v4(mp, ipha, ira);
5320 		} else {
5321 			/*
5322 			 * We used to attempt to send an icmp error here, but
5323 			 * since this is known to be a multicast packet
5324 			 * and we don't send icmp errors in response to
5325 			 * multicast, just drop the packet and give up sooner.
5326 			 */
5327 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5328 			freemsg(mp);
5329 		}
5330 		return;
5331 	}
5332 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5333 
5334 	/*
5335 	 * If SO_REUSEADDR has been set on the first we send the
5336 	 * packet to all clients that have joined the group and
5337 	 * match the port.
5338 	 */
5339 	if (connp->conn_reuseaddr) {
5340 		conn_t		*first_connp = connp;
5341 		conn_t		*next_connp;
5342 		mblk_t		*mp1;
5343 
5344 		CONN_INC_REF(connp);
5345 		connp = connp->conn_next;
5346 		for (;;) {
5347 			while (connp != NULL) {
5348 				if (IPCL_UDP_MATCH_V6(connp, lport,
5349 				    ipv6_all_zeros, fport, v6faddr) &&
5350 				    conn_wantpacket(connp, ira, ipha) &&
5351 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5352 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5353 				    ira, connp)))
5354 					break;
5355 				connp = connp->conn_next;
5356 			}
5357 			if (connp == NULL) {
5358 				/* No more interested clients */
5359 				connp = first_connp;
5360 				break;
5361 			}
5362 			if (((mp1 = dupmsg(mp)) == NULL) &&
5363 			    ((mp1 = copymsg(mp)) == NULL)) {
5364 				/* Memory allocation failed */
5365 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5366 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5367 				connp = first_connp;
5368 				break;
5369 			}
5370 			CONN_INC_REF(connp);
5371 			mutex_exit(&connfp->connf_lock);
5372 
5373 			IP_STAT(ipst, ip_udp_fanmb);
5374 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5375 			    NULL, ira);
5376 			mutex_enter(&connfp->connf_lock);
5377 			/* Follow the next pointer before releasing the conn */
5378 			next_connp = connp->conn_next;
5379 			CONN_DEC_REF(connp);
5380 			connp = next_connp;
5381 		}
5382 	}
5383 
5384 	/* Last one.  Send it upstream. */
5385 	mutex_exit(&connfp->connf_lock);
5386 	IP_STAT(ipst, ip_udp_fanmb);
5387 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5388 	CONN_DEC_REF(connp);
5389 }
5390 
5391 /*
5392  * Split an incoming packet's IPv4 options into the label and the other options.
5393  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5394  * clearing out any leftover label or options.
5395  * Otherwise it just makes ipp point into the packet.
5396  *
5397  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5398  */
5399 int
5400 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5401 {
5402 	uchar_t		*opt;
5403 	uint32_t	totallen;
5404 	uint32_t	optval;
5405 	uint32_t	optlen;
5406 
5407 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5408 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5409 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5410 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5411 
5412 	/*
5413 	 * Get length (in 4 byte octets) of IP header options.
5414 	 */
5415 	totallen = ipha->ipha_version_and_hdr_length -
5416 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5417 
5418 	if (totallen == 0) {
5419 		if (!allocate)
5420 			return (0);
5421 
5422 		/* Clear out anything from a previous packet */
5423 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5424 			kmem_free(ipp->ipp_ipv4_options,
5425 			    ipp->ipp_ipv4_options_len);
5426 			ipp->ipp_ipv4_options = NULL;
5427 			ipp->ipp_ipv4_options_len = 0;
5428 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5429 		}
5430 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5431 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5432 			ipp->ipp_label_v4 = NULL;
5433 			ipp->ipp_label_len_v4 = 0;
5434 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5435 		}
5436 		return (0);
5437 	}
5438 
5439 	totallen <<= 2;
5440 	opt = (uchar_t *)&ipha[1];
5441 	if (!is_system_labeled()) {
5442 
5443 	copyall:
5444 		if (!allocate) {
5445 			if (totallen != 0) {
5446 				ipp->ipp_ipv4_options = opt;
5447 				ipp->ipp_ipv4_options_len = totallen;
5448 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5449 			}
5450 			return (0);
5451 		}
5452 		/* Just copy all of options */
5453 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5454 			if (totallen == ipp->ipp_ipv4_options_len) {
5455 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5456 				return (0);
5457 			}
5458 			kmem_free(ipp->ipp_ipv4_options,
5459 			    ipp->ipp_ipv4_options_len);
5460 			ipp->ipp_ipv4_options = NULL;
5461 			ipp->ipp_ipv4_options_len = 0;
5462 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5463 		}
5464 		if (totallen == 0)
5465 			return (0);
5466 
5467 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5468 		if (ipp->ipp_ipv4_options == NULL)
5469 			return (ENOMEM);
5470 		ipp->ipp_ipv4_options_len = totallen;
5471 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5472 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5473 		return (0);
5474 	}
5475 
5476 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5477 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5478 		ipp->ipp_label_v4 = NULL;
5479 		ipp->ipp_label_len_v4 = 0;
5480 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5481 	}
5482 
5483 	/*
5484 	 * Search for CIPSO option.
5485 	 * We assume CIPSO is first in options if it is present.
5486 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5487 	 * prior to the CIPSO option.
5488 	 */
5489 	while (totallen != 0) {
5490 		switch (optval = opt[IPOPT_OPTVAL]) {
5491 		case IPOPT_EOL:
5492 			return (0);
5493 		case IPOPT_NOP:
5494 			optlen = 1;
5495 			break;
5496 		default:
5497 			if (totallen <= IPOPT_OLEN)
5498 				return (EINVAL);
5499 			optlen = opt[IPOPT_OLEN];
5500 			if (optlen < 2)
5501 				return (EINVAL);
5502 		}
5503 		if (optlen > totallen)
5504 			return (EINVAL);
5505 
5506 		switch (optval) {
5507 		case IPOPT_COMSEC:
5508 			if (!allocate) {
5509 				ipp->ipp_label_v4 = opt;
5510 				ipp->ipp_label_len_v4 = optlen;
5511 				ipp->ipp_fields |= IPPF_LABEL_V4;
5512 			} else {
5513 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5514 				    KM_NOSLEEP);
5515 				if (ipp->ipp_label_v4 == NULL)
5516 					return (ENOMEM);
5517 				ipp->ipp_label_len_v4 = optlen;
5518 				ipp->ipp_fields |= IPPF_LABEL_V4;
5519 				bcopy(opt, ipp->ipp_label_v4, optlen);
5520 			}
5521 			totallen -= optlen;
5522 			opt += optlen;
5523 
5524 			/* Skip padding bytes until we get to a multiple of 4 */
5525 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5526 				totallen--;
5527 				opt++;
5528 			}
5529 			/* Remaining as ipp_ipv4_options */
5530 			goto copyall;
5531 		}
5532 		totallen -= optlen;
5533 		opt += optlen;
5534 	}
5535 	/* No CIPSO found; return everything as ipp_ipv4_options */
5536 	totallen = ipha->ipha_version_and_hdr_length -
5537 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5538 	totallen <<= 2;
5539 	opt = (uchar_t *)&ipha[1];
5540 	goto copyall;
5541 }
5542 
5543 /*
5544  * Efficient versions of lookup for an IRE when we only
5545  * match the address.
5546  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5547  * Does not handle multicast addresses.
5548  */
5549 uint_t
5550 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5551 {
5552 	ire_t *ire;
5553 	uint_t result;
5554 
5555 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5556 	ASSERT(ire != NULL);
5557 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5558 		result = IRE_NOROUTE;
5559 	else
5560 		result = ire->ire_type;
5561 	ire_refrele(ire);
5562 	return (result);
5563 }
5564 
5565 /*
5566  * Efficient versions of lookup for an IRE when we only
5567  * match the address.
5568  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5569  * Does not handle multicast addresses.
5570  */
5571 uint_t
5572 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5573 {
5574 	ire_t *ire;
5575 	uint_t result;
5576 
5577 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5578 	ASSERT(ire != NULL);
5579 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5580 		result = IRE_NOROUTE;
5581 	else
5582 		result = ire->ire_type;
5583 	ire_refrele(ire);
5584 	return (result);
5585 }
5586 
5587 /*
5588  * Nobody should be sending
5589  * packets up this stream
5590  */
5591 static void
5592 ip_lrput(queue_t *q, mblk_t *mp)
5593 {
5594 	switch (mp->b_datap->db_type) {
5595 	case M_FLUSH:
5596 		/* Turn around */
5597 		if (*mp->b_rptr & FLUSHW) {
5598 			*mp->b_rptr &= ~FLUSHR;
5599 			qreply(q, mp);
5600 			return;
5601 		}
5602 		break;
5603 	}
5604 	freemsg(mp);
5605 }
5606 
5607 /* Nobody should be sending packets down this stream */
5608 /* ARGSUSED */
5609 void
5610 ip_lwput(queue_t *q, mblk_t *mp)
5611 {
5612 	freemsg(mp);
5613 }
5614 
5615 /*
5616  * Move the first hop in any source route to ipha_dst and remove that part of
5617  * the source route.  Called by other protocols.  Errors in option formatting
5618  * are ignored - will be handled by ip_output_options. Return the final
5619  * destination (either ipha_dst or the last entry in a source route.)
5620  */
5621 ipaddr_t
5622 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5623 {
5624 	ipoptp_t	opts;
5625 	uchar_t		*opt;
5626 	uint8_t		optval;
5627 	uint8_t		optlen;
5628 	ipaddr_t	dst;
5629 	int		i;
5630 	ip_stack_t	*ipst = ns->netstack_ip;
5631 
5632 	ip2dbg(("ip_massage_options\n"));
5633 	dst = ipha->ipha_dst;
5634 	for (optval = ipoptp_first(&opts, ipha);
5635 	    optval != IPOPT_EOL;
5636 	    optval = ipoptp_next(&opts)) {
5637 		opt = opts.ipoptp_cur;
5638 		switch (optval) {
5639 			uint8_t off;
5640 		case IPOPT_SSRR:
5641 		case IPOPT_LSRR:
5642 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5643 				ip1dbg(("ip_massage_options: bad src route\n"));
5644 				break;
5645 			}
5646 			optlen = opts.ipoptp_len;
5647 			off = opt[IPOPT_OFFSET];
5648 			off--;
5649 		redo_srr:
5650 			if (optlen < IP_ADDR_LEN ||
5651 			    off > optlen - IP_ADDR_LEN) {
5652 				/* End of source route */
5653 				ip1dbg(("ip_massage_options: end of SR\n"));
5654 				break;
5655 			}
5656 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5657 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5658 			    ntohl(dst)));
5659 			/*
5660 			 * Check if our address is present more than
5661 			 * once as consecutive hops in source route.
5662 			 * XXX verify per-interface ip_forwarding
5663 			 * for source route?
5664 			 */
5665 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5666 				off += IP_ADDR_LEN;
5667 				goto redo_srr;
5668 			}
5669 			if (dst == htonl(INADDR_LOOPBACK)) {
5670 				ip1dbg(("ip_massage_options: loopback addr in "
5671 				    "source route!\n"));
5672 				break;
5673 			}
5674 			/*
5675 			 * Update ipha_dst to be the first hop and remove the
5676 			 * first hop from the source route (by overwriting
5677 			 * part of the option with NOP options).
5678 			 */
5679 			ipha->ipha_dst = dst;
5680 			/* Put the last entry in dst */
5681 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5682 			    3;
5683 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5684 
5685 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5686 			    ntohl(dst)));
5687 			/* Move down and overwrite */
5688 			opt[IP_ADDR_LEN] = opt[0];
5689 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5690 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5691 			for (i = 0; i < IP_ADDR_LEN; i++)
5692 				opt[i] = IPOPT_NOP;
5693 			break;
5694 		}
5695 	}
5696 	return (dst);
5697 }
5698 
5699 /*
5700  * Return the network mask
5701  * associated with the specified address.
5702  */
5703 ipaddr_t
5704 ip_net_mask(ipaddr_t addr)
5705 {
5706 	uchar_t	*up = (uchar_t *)&addr;
5707 	ipaddr_t mask = 0;
5708 	uchar_t	*maskp = (uchar_t *)&mask;
5709 
5710 #if defined(__i386) || defined(__amd64)
5711 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5712 #endif
5713 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5714 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5715 #endif
5716 	if (CLASSD(addr)) {
5717 		maskp[0] = 0xF0;
5718 		return (mask);
5719 	}
5720 
5721 	/* We assume Class E default netmask to be 32 */
5722 	if (CLASSE(addr))
5723 		return (0xffffffffU);
5724 
5725 	if (addr == 0)
5726 		return (0);
5727 	maskp[0] = 0xFF;
5728 	if ((up[0] & 0x80) == 0)
5729 		return (mask);
5730 
5731 	maskp[1] = 0xFF;
5732 	if ((up[0] & 0xC0) == 0x80)
5733 		return (mask);
5734 
5735 	maskp[2] = 0xFF;
5736 	if ((up[0] & 0xE0) == 0xC0)
5737 		return (mask);
5738 
5739 	/* Otherwise return no mask */
5740 	return ((ipaddr_t)0);
5741 }
5742 
5743 /* Name/Value Table Lookup Routine */
5744 char *
5745 ip_nv_lookup(nv_t *nv, int value)
5746 {
5747 	if (!nv)
5748 		return (NULL);
5749 	for (; nv->nv_name; nv++) {
5750 		if (nv->nv_value == value)
5751 			return (nv->nv_name);
5752 	}
5753 	return ("unknown");
5754 }
5755 
5756 static int
5757 ip_wait_for_info_ack(ill_t *ill)
5758 {
5759 	int err;
5760 
5761 	mutex_enter(&ill->ill_lock);
5762 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5763 		/*
5764 		 * Return value of 0 indicates a pending signal.
5765 		 */
5766 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5767 		if (err == 0) {
5768 			mutex_exit(&ill->ill_lock);
5769 			return (EINTR);
5770 		}
5771 	}
5772 	mutex_exit(&ill->ill_lock);
5773 	/*
5774 	 * ip_rput_other could have set an error  in ill_error on
5775 	 * receipt of M_ERROR.
5776 	 */
5777 	return (ill->ill_error);
5778 }
5779 
5780 /*
5781  * This is a module open, i.e. this is a control stream for access
5782  * to a DLPI device.  We allocate an ill_t as the instance data in
5783  * this case.
5784  */
5785 static int
5786 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5787 {
5788 	ill_t	*ill;
5789 	int	err;
5790 	zoneid_t zoneid;
5791 	netstack_t *ns;
5792 	ip_stack_t *ipst;
5793 
5794 	/*
5795 	 * Prevent unprivileged processes from pushing IP so that
5796 	 * they can't send raw IP.
5797 	 */
5798 	if (secpolicy_net_rawaccess(credp) != 0)
5799 		return (EPERM);
5800 
5801 	ns = netstack_find_by_cred(credp);
5802 	ASSERT(ns != NULL);
5803 	ipst = ns->netstack_ip;
5804 	ASSERT(ipst != NULL);
5805 
5806 	/*
5807 	 * For exclusive stacks we set the zoneid to zero
5808 	 * to make IP operate as if in the global zone.
5809 	 */
5810 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5811 		zoneid = GLOBAL_ZONEID;
5812 	else
5813 		zoneid = crgetzoneid(credp);
5814 
5815 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5816 	q->q_ptr = WR(q)->q_ptr = ill;
5817 	ill->ill_ipst = ipst;
5818 	ill->ill_zoneid = zoneid;
5819 
5820 	/*
5821 	 * ill_init initializes the ill fields and then sends down
5822 	 * down a DL_INFO_REQ after calling qprocson.
5823 	 */
5824 	err = ill_init(q, ill);
5825 
5826 	if (err != 0) {
5827 		mi_free(ill);
5828 		netstack_rele(ipst->ips_netstack);
5829 		q->q_ptr = NULL;
5830 		WR(q)->q_ptr = NULL;
5831 		return (err);
5832 	}
5833 
5834 	/*
5835 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5836 	 *
5837 	 * ill_init initializes the ipsq marking this thread as
5838 	 * writer
5839 	 */
5840 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5841 	err = ip_wait_for_info_ack(ill);
5842 	if (err == 0)
5843 		ill->ill_credp = credp;
5844 	else
5845 		goto fail;
5846 
5847 	crhold(credp);
5848 
5849 	mutex_enter(&ipst->ips_ip_mi_lock);
5850 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5851 	    sflag, credp);
5852 	mutex_exit(&ipst->ips_ip_mi_lock);
5853 fail:
5854 	if (err) {
5855 		(void) ip_close(q, 0);
5856 		return (err);
5857 	}
5858 	return (0);
5859 }
5860 
5861 /* For /dev/ip aka AF_INET open */
5862 int
5863 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5864 {
5865 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5866 }
5867 
5868 /* For /dev/ip6 aka AF_INET6 open */
5869 int
5870 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5871 {
5872 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5873 }
5874 
5875 /* IP open routine. */
5876 int
5877 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5878     boolean_t isv6)
5879 {
5880 	conn_t 		*connp;
5881 	major_t		maj;
5882 	zoneid_t	zoneid;
5883 	netstack_t	*ns;
5884 	ip_stack_t	*ipst;
5885 
5886 	/* Allow reopen. */
5887 	if (q->q_ptr != NULL)
5888 		return (0);
5889 
5890 	if (sflag & MODOPEN) {
5891 		/* This is a module open */
5892 		return (ip_modopen(q, devp, flag, sflag, credp));
5893 	}
5894 
5895 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5896 		/*
5897 		 * Non streams based socket looking for a stream
5898 		 * to access IP
5899 		 */
5900 		return (ip_helper_stream_setup(q, devp, flag, sflag,
5901 		    credp, isv6));
5902 	}
5903 
5904 	ns = netstack_find_by_cred(credp);
5905 	ASSERT(ns != NULL);
5906 	ipst = ns->netstack_ip;
5907 	ASSERT(ipst != NULL);
5908 
5909 	/*
5910 	 * For exclusive stacks we set the zoneid to zero
5911 	 * to make IP operate as if in the global zone.
5912 	 */
5913 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5914 		zoneid = GLOBAL_ZONEID;
5915 	else
5916 		zoneid = crgetzoneid(credp);
5917 
5918 	/*
5919 	 * We are opening as a device. This is an IP client stream, and we
5920 	 * allocate an conn_t as the instance data.
5921 	 */
5922 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
5923 
5924 	/*
5925 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
5926 	 * done by netstack_find_by_cred()
5927 	 */
5928 	netstack_rele(ipst->ips_netstack);
5929 
5930 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
5931 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
5932 	connp->conn_ixa->ixa_zoneid = zoneid;
5933 	connp->conn_zoneid = zoneid;
5934 
5935 	connp->conn_rq = q;
5936 	q->q_ptr = WR(q)->q_ptr = connp;
5937 
5938 	/* Minor tells us which /dev entry was opened */
5939 	if (isv6) {
5940 		connp->conn_family = AF_INET6;
5941 		connp->conn_ipversion = IPV6_VERSION;
5942 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
5943 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
5944 	} else {
5945 		connp->conn_family = AF_INET;
5946 		connp->conn_ipversion = IPV4_VERSION;
5947 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
5948 	}
5949 
5950 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
5951 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
5952 		connp->conn_minor_arena = ip_minor_arena_la;
5953 	} else {
5954 		/*
5955 		 * Either minor numbers in the large arena were exhausted
5956 		 * or a non socket application is doing the open.
5957 		 * Try to allocate from the small arena.
5958 		 */
5959 		if ((connp->conn_dev =
5960 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
5961 			/* CONN_DEC_REF takes care of netstack_rele() */
5962 			q->q_ptr = WR(q)->q_ptr = NULL;
5963 			CONN_DEC_REF(connp);
5964 			return (EBUSY);
5965 		}
5966 		connp->conn_minor_arena = ip_minor_arena_sa;
5967 	}
5968 
5969 	maj = getemajor(*devp);
5970 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
5971 
5972 	/*
5973 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
5974 	 */
5975 	connp->conn_cred = credp;
5976 	connp->conn_cpid = curproc->p_pid;
5977 	/* Cache things in ixa without an extra refhold */
5978 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
5979 	connp->conn_ixa->ixa_cred = connp->conn_cred;
5980 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
5981 	if (is_system_labeled())
5982 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
5983 
5984 	/*
5985 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
5986 	 */
5987 	connp->conn_recv = ip_conn_input;
5988 	connp->conn_recvicmp = ip_conn_input_icmp;
5989 
5990 	crhold(connp->conn_cred);
5991 
5992 	/*
5993 	 * If the caller has the process-wide flag set, then default to MAC
5994 	 * exempt mode.  This allows read-down to unlabeled hosts.
5995 	 */
5996 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5997 		connp->conn_mac_mode = CONN_MAC_AWARE;
5998 
5999 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6000 
6001 	connp->conn_rq = q;
6002 	connp->conn_wq = WR(q);
6003 
6004 	/* Non-zero default values */
6005 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6006 
6007 	/*
6008 	 * Make the conn globally visible to walkers
6009 	 */
6010 	ASSERT(connp->conn_ref == 1);
6011 	mutex_enter(&connp->conn_lock);
6012 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6013 	mutex_exit(&connp->conn_lock);
6014 
6015 	qprocson(q);
6016 
6017 	return (0);
6018 }
6019 
6020 /*
6021  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6022  * all of them are copied to the conn_t. If the req is "zero", the policy is
6023  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6024  * fields.
6025  * We keep only the latest setting of the policy and thus policy setting
6026  * is not incremental/cumulative.
6027  *
6028  * Requests to set policies with multiple alternative actions will
6029  * go through a different API.
6030  */
6031 int
6032 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6033 {
6034 	uint_t ah_req = 0;
6035 	uint_t esp_req = 0;
6036 	uint_t se_req = 0;
6037 	ipsec_act_t *actp = NULL;
6038 	uint_t nact;
6039 	ipsec_policy_head_t *ph;
6040 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6041 	int error = 0;
6042 	netstack_t	*ns = connp->conn_netstack;
6043 	ip_stack_t	*ipst = ns->netstack_ip;
6044 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6045 
6046 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6047 
6048 	/*
6049 	 * The IP_SEC_OPT option does not allow variable length parameters,
6050 	 * hence a request cannot be NULL.
6051 	 */
6052 	if (req == NULL)
6053 		return (EINVAL);
6054 
6055 	ah_req = req->ipsr_ah_req;
6056 	esp_req = req->ipsr_esp_req;
6057 	se_req = req->ipsr_self_encap_req;
6058 
6059 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6060 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6061 		return (EINVAL);
6062 
6063 	/*
6064 	 * Are we dealing with a request to reset the policy (i.e.
6065 	 * zero requests).
6066 	 */
6067 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6068 	    (esp_req & REQ_MASK) == 0 &&
6069 	    (se_req & REQ_MASK) == 0);
6070 
6071 	if (!is_pol_reset) {
6072 		/*
6073 		 * If we couldn't load IPsec, fail with "protocol
6074 		 * not supported".
6075 		 * IPsec may not have been loaded for a request with zero
6076 		 * policies, so we don't fail in this case.
6077 		 */
6078 		mutex_enter(&ipss->ipsec_loader_lock);
6079 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6080 			mutex_exit(&ipss->ipsec_loader_lock);
6081 			return (EPROTONOSUPPORT);
6082 		}
6083 		mutex_exit(&ipss->ipsec_loader_lock);
6084 
6085 		/*
6086 		 * Test for valid requests. Invalid algorithms
6087 		 * need to be tested by IPsec code because new
6088 		 * algorithms can be added dynamically.
6089 		 */
6090 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6091 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6092 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6093 			return (EINVAL);
6094 		}
6095 
6096 		/*
6097 		 * Only privileged users can issue these
6098 		 * requests.
6099 		 */
6100 		if (((ah_req & IPSEC_PREF_NEVER) ||
6101 		    (esp_req & IPSEC_PREF_NEVER) ||
6102 		    (se_req & IPSEC_PREF_NEVER)) &&
6103 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6104 			return (EPERM);
6105 		}
6106 
6107 		/*
6108 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6109 		 * are mutually exclusive.
6110 		 */
6111 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6112 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6113 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6114 			/* Both of them are set */
6115 			return (EINVAL);
6116 		}
6117 	}
6118 
6119 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6120 
6121 	/*
6122 	 * If we have already cached policies in conn_connect(), don't
6123 	 * let them change now. We cache policies for connections
6124 	 * whose src,dst [addr, port] is known.
6125 	 */
6126 	if (connp->conn_policy_cached) {
6127 		return (EINVAL);
6128 	}
6129 
6130 	/*
6131 	 * We have a zero policies, reset the connection policy if already
6132 	 * set. This will cause the connection to inherit the
6133 	 * global policy, if any.
6134 	 */
6135 	if (is_pol_reset) {
6136 		if (connp->conn_policy != NULL) {
6137 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6138 			connp->conn_policy = NULL;
6139 		}
6140 		connp->conn_in_enforce_policy = B_FALSE;
6141 		connp->conn_out_enforce_policy = B_FALSE;
6142 		return (0);
6143 	}
6144 
6145 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6146 	    ipst->ips_netstack);
6147 	if (ph == NULL)
6148 		goto enomem;
6149 
6150 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6151 	if (actp == NULL)
6152 		goto enomem;
6153 
6154 	/*
6155 	 * Always insert IPv4 policy entries, since they can also apply to
6156 	 * ipv6 sockets being used in ipv4-compat mode.
6157 	 */
6158 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6159 	    IPSEC_TYPE_INBOUND, ns))
6160 		goto enomem;
6161 	is_pol_inserted = B_TRUE;
6162 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6163 	    IPSEC_TYPE_OUTBOUND, ns))
6164 		goto enomem;
6165 
6166 	/*
6167 	 * We're looking at a v6 socket, also insert the v6-specific
6168 	 * entries.
6169 	 */
6170 	if (connp->conn_family == AF_INET6) {
6171 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6172 		    IPSEC_TYPE_INBOUND, ns))
6173 			goto enomem;
6174 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6175 		    IPSEC_TYPE_OUTBOUND, ns))
6176 			goto enomem;
6177 	}
6178 
6179 	ipsec_actvec_free(actp, nact);
6180 
6181 	/*
6182 	 * If the requests need security, set enforce_policy.
6183 	 * If the requests are IPSEC_PREF_NEVER, one should
6184 	 * still set conn_out_enforce_policy so that ip_set_destination
6185 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6186 	 * for connections that we don't cache policy in at connect time,
6187 	 * if global policy matches in ip_output_attach_policy, we
6188 	 * don't wrongly inherit global policy. Similarly, we need
6189 	 * to set conn_in_enforce_policy also so that we don't verify
6190 	 * policy wrongly.
6191 	 */
6192 	if ((ah_req & REQ_MASK) != 0 ||
6193 	    (esp_req & REQ_MASK) != 0 ||
6194 	    (se_req & REQ_MASK) != 0) {
6195 		connp->conn_in_enforce_policy = B_TRUE;
6196 		connp->conn_out_enforce_policy = B_TRUE;
6197 	}
6198 
6199 	return (error);
6200 #undef REQ_MASK
6201 
6202 	/*
6203 	 * Common memory-allocation-failure exit path.
6204 	 */
6205 enomem:
6206 	if (actp != NULL)
6207 		ipsec_actvec_free(actp, nact);
6208 	if (is_pol_inserted)
6209 		ipsec_polhead_flush(ph, ns);
6210 	return (ENOMEM);
6211 }
6212 
6213 /*
6214  * Set socket options for joining and leaving multicast groups.
6215  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6216  * The caller has already check that the option name is consistent with
6217  * the address family of the socket.
6218  */
6219 int
6220 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6221     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6222 {
6223 	int		*i1 = (int *)invalp;
6224 	int		error = 0;
6225 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6226 	struct ip_mreq	*v4_mreqp;
6227 	struct ipv6_mreq *v6_mreqp;
6228 	struct group_req *greqp;
6229 	ire_t *ire;
6230 	boolean_t done = B_FALSE;
6231 	ipaddr_t ifaddr;
6232 	in6_addr_t v6group;
6233 	uint_t ifindex;
6234 	boolean_t mcast_opt = B_TRUE;
6235 	mcast_record_t fmode;
6236 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6237 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6238 
6239 	switch (name) {
6240 	case IP_ADD_MEMBERSHIP:
6241 	case IPV6_JOIN_GROUP:
6242 		mcast_opt = B_FALSE;
6243 		/* FALLTHRU */
6244 	case MCAST_JOIN_GROUP:
6245 		fmode = MODE_IS_EXCLUDE;
6246 		optfn = ip_opt_add_group;
6247 		break;
6248 
6249 	case IP_DROP_MEMBERSHIP:
6250 	case IPV6_LEAVE_GROUP:
6251 		mcast_opt = B_FALSE;
6252 		/* FALLTHRU */
6253 	case MCAST_LEAVE_GROUP:
6254 		fmode = MODE_IS_INCLUDE;
6255 		optfn = ip_opt_delete_group;
6256 		break;
6257 	default:
6258 		ASSERT(0);
6259 	}
6260 
6261 	if (mcast_opt) {
6262 		struct sockaddr_in *sin;
6263 		struct sockaddr_in6 *sin6;
6264 
6265 		greqp = (struct group_req *)i1;
6266 		if (greqp->gr_group.ss_family == AF_INET) {
6267 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6268 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6269 		} else {
6270 			if (!inet6)
6271 				return (EINVAL);	/* Not on INET socket */
6272 
6273 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6274 			v6group = sin6->sin6_addr;
6275 		}
6276 		ifaddr = INADDR_ANY;
6277 		ifindex = greqp->gr_interface;
6278 	} else if (inet6) {
6279 		v6_mreqp = (struct ipv6_mreq *)i1;
6280 		v6group = v6_mreqp->ipv6mr_multiaddr;
6281 		ifaddr = INADDR_ANY;
6282 		ifindex = v6_mreqp->ipv6mr_interface;
6283 	} else {
6284 		v4_mreqp = (struct ip_mreq *)i1;
6285 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6286 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6287 		ifindex = 0;
6288 	}
6289 
6290 	/*
6291 	 * In the multirouting case, we need to replicate
6292 	 * the request on all interfaces that will take part
6293 	 * in replication.  We do so because multirouting is
6294 	 * reflective, thus we will probably receive multi-
6295 	 * casts on those interfaces.
6296 	 * The ip_multirt_apply_membership() succeeds if
6297 	 * the operation succeeds on at least one interface.
6298 	 */
6299 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6300 		ipaddr_t group;
6301 
6302 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6303 
6304 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6305 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6306 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6307 	} else {
6308 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6309 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6310 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6311 	}
6312 	if (ire != NULL) {
6313 		if (ire->ire_flags & RTF_MULTIRT) {
6314 			error = ip_multirt_apply_membership(optfn, ire, connp,
6315 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6316 			done = B_TRUE;
6317 		}
6318 		ire_refrele(ire);
6319 	}
6320 
6321 	if (!done) {
6322 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6323 		    fmode, &ipv6_all_zeros);
6324 	}
6325 	return (error);
6326 }
6327 
6328 /*
6329  * Set socket options for joining and leaving multicast groups
6330  * for specific sources.
6331  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6332  * The caller has already check that the option name is consistent with
6333  * the address family of the socket.
6334  */
6335 int
6336 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6337     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6338 {
6339 	int		*i1 = (int *)invalp;
6340 	int		error = 0;
6341 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6342 	struct ip_mreq_source *imreqp;
6343 	struct group_source_req *gsreqp;
6344 	in6_addr_t v6group, v6src;
6345 	uint32_t ifindex;
6346 	ipaddr_t ifaddr;
6347 	boolean_t mcast_opt = B_TRUE;
6348 	mcast_record_t fmode;
6349 	ire_t *ire;
6350 	boolean_t done = B_FALSE;
6351 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6352 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6353 
6354 	switch (name) {
6355 	case IP_BLOCK_SOURCE:
6356 		mcast_opt = B_FALSE;
6357 		/* FALLTHRU */
6358 	case MCAST_BLOCK_SOURCE:
6359 		fmode = MODE_IS_EXCLUDE;
6360 		optfn = ip_opt_add_group;
6361 		break;
6362 
6363 	case IP_UNBLOCK_SOURCE:
6364 		mcast_opt = B_FALSE;
6365 		/* FALLTHRU */
6366 	case MCAST_UNBLOCK_SOURCE:
6367 		fmode = MODE_IS_EXCLUDE;
6368 		optfn = ip_opt_delete_group;
6369 		break;
6370 
6371 	case IP_ADD_SOURCE_MEMBERSHIP:
6372 		mcast_opt = B_FALSE;
6373 		/* FALLTHRU */
6374 	case MCAST_JOIN_SOURCE_GROUP:
6375 		fmode = MODE_IS_INCLUDE;
6376 		optfn = ip_opt_add_group;
6377 		break;
6378 
6379 	case IP_DROP_SOURCE_MEMBERSHIP:
6380 		mcast_opt = B_FALSE;
6381 		/* FALLTHRU */
6382 	case MCAST_LEAVE_SOURCE_GROUP:
6383 		fmode = MODE_IS_INCLUDE;
6384 		optfn = ip_opt_delete_group;
6385 		break;
6386 	default:
6387 		ASSERT(0);
6388 	}
6389 
6390 	if (mcast_opt) {
6391 		gsreqp = (struct group_source_req *)i1;
6392 		ifindex = gsreqp->gsr_interface;
6393 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6394 			struct sockaddr_in *s;
6395 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6396 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6397 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6398 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6399 		} else {
6400 			struct sockaddr_in6 *s6;
6401 
6402 			if (!inet6)
6403 				return (EINVAL);	/* Not on INET socket */
6404 
6405 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6406 			v6group = s6->sin6_addr;
6407 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6408 			v6src = s6->sin6_addr;
6409 		}
6410 		ifaddr = INADDR_ANY;
6411 	} else {
6412 		imreqp = (struct ip_mreq_source *)i1;
6413 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6414 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6415 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6416 		ifindex = 0;
6417 	}
6418 
6419 	/*
6420 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6421 	 */
6422 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6423 		v6src = ipv6_all_zeros;
6424 
6425 	/*
6426 	 * In the multirouting case, we need to replicate
6427 	 * the request as noted in the mcast cases above.
6428 	 */
6429 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6430 		ipaddr_t group;
6431 
6432 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6433 
6434 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6435 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6436 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6437 	} else {
6438 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6439 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6440 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6441 	}
6442 	if (ire != NULL) {
6443 		if (ire->ire_flags & RTF_MULTIRT) {
6444 			error = ip_multirt_apply_membership(optfn, ire, connp,
6445 			    checkonly, &v6group, fmode, &v6src);
6446 			done = B_TRUE;
6447 		}
6448 		ire_refrele(ire);
6449 	}
6450 	if (!done) {
6451 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6452 		    fmode, &v6src);
6453 	}
6454 	return (error);
6455 }
6456 
6457 /*
6458  * Given a destination address and a pointer to where to put the information
6459  * this routine fills in the mtuinfo.
6460  * The socket must be connected.
6461  * For sctp conn_faddr is the primary address.
6462  */
6463 int
6464 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6465 {
6466 	uint32_t	pmtu = IP_MAXPACKET;
6467 	uint_t		scopeid;
6468 
6469 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6470 		return (-1);
6471 
6472 	/* In case we never sent or called ip_set_destination_v4/v6 */
6473 	if (ixa->ixa_ire != NULL)
6474 		pmtu = ip_get_pmtu(ixa);
6475 
6476 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6477 		scopeid = ixa->ixa_scopeid;
6478 	else
6479 		scopeid = 0;
6480 
6481 	bzero(mtuinfo, sizeof (*mtuinfo));
6482 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6483 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6484 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6485 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6486 	mtuinfo->ip6m_mtu = pmtu;
6487 
6488 	return (sizeof (struct ip6_mtuinfo));
6489 }
6490 
6491 /*
6492  * When the src multihoming is changed from weak to [strong, preferred]
6493  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6494  * and identify routes that were created by user-applications in the
6495  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6496  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6497  * is selected by finding an interface route for the gateway.
6498  */
6499 /* ARGSUSED */
6500 void
6501 ip_ire_rebind_walker(ire_t *ire, void *notused)
6502 {
6503 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6504 		return;
6505 	ire_rebind(ire);
6506 	ire_delete(ire);
6507 }
6508 
6509 /*
6510  * When the src multihoming is changed from  [strong, preferred] to weak,
6511  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6512  * set any entries that were created by user-applications in the unbound state
6513  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6514  */
6515 /* ARGSUSED */
6516 void
6517 ip_ire_unbind_walker(ire_t *ire, void *notused)
6518 {
6519 	ire_t *new_ire;
6520 
6521 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6522 		return;
6523 	if (ire->ire_ipversion == IPV6_VERSION) {
6524 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6525 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6526 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6527 	} else {
6528 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6529 		    (uchar_t *)&ire->ire_mask,
6530 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6531 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6532 	}
6533 	if (new_ire == NULL)
6534 		return;
6535 	new_ire->ire_unbound = B_TRUE;
6536 	/*
6537 	 * The bound ire must first be deleted so that we don't return
6538 	 * the existing one on the attempt to add the unbound new_ire.
6539 	 */
6540 	ire_delete(ire);
6541 	new_ire = ire_add(new_ire);
6542 	if (new_ire != NULL)
6543 		ire_refrele(new_ire);
6544 }
6545 
6546 /*
6547  * When the settings of ip*_strict_src_multihoming tunables are changed,
6548  * all cached routes need to be recomputed. This recomputation needs to be
6549  * done when going from weaker to stronger modes so that the cached ire
6550  * for the connection does not violate the current ip*_strict_src_multihoming
6551  * setting. It also needs to be done when going from stronger to weaker modes,
6552  * so that we fall back to matching on the longest-matching-route (as opposed
6553  * to a shorter match that may have been selected in the strong mode
6554  * to satisfy src_multihoming settings).
6555  *
6556  * The cached ixa_ire entires for all conn_t entries are marked as
6557  * "verify" so that they will be recomputed for the next packet.
6558  */
6559 void
6560 conn_ire_revalidate(conn_t *connp, void *arg)
6561 {
6562 	boolean_t isv6 = (boolean_t)arg;
6563 
6564 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6565 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6566 		return;
6567 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6568 }
6569 
6570 /*
6571  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6572  * When an ipf is passed here for the first time, if
6573  * we already have in-order fragments on the queue, we convert from the fast-
6574  * path reassembly scheme to the hard-case scheme.  From then on, additional
6575  * fragments are reassembled here.  We keep track of the start and end offsets
6576  * of each piece, and the number of holes in the chain.  When the hole count
6577  * goes to zero, we are done!
6578  *
6579  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6580  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6581  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6582  * after the call to ip_reassemble().
6583  */
6584 int
6585 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6586     size_t msg_len)
6587 {
6588 	uint_t	end;
6589 	mblk_t	*next_mp;
6590 	mblk_t	*mp1;
6591 	uint_t	offset;
6592 	boolean_t incr_dups = B_TRUE;
6593 	boolean_t offset_zero_seen = B_FALSE;
6594 	boolean_t pkt_boundary_checked = B_FALSE;
6595 
6596 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6597 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6598 
6599 	/* Add in byte count */
6600 	ipf->ipf_count += msg_len;
6601 	if (ipf->ipf_end) {
6602 		/*
6603 		 * We were part way through in-order reassembly, but now there
6604 		 * is a hole.  We walk through messages already queued, and
6605 		 * mark them for hard case reassembly.  We know that up till
6606 		 * now they were in order starting from offset zero.
6607 		 */
6608 		offset = 0;
6609 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6610 			IP_REASS_SET_START(mp1, offset);
6611 			if (offset == 0) {
6612 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6613 				offset = -ipf->ipf_nf_hdr_len;
6614 			}
6615 			offset += mp1->b_wptr - mp1->b_rptr;
6616 			IP_REASS_SET_END(mp1, offset);
6617 		}
6618 		/* One hole at the end. */
6619 		ipf->ipf_hole_cnt = 1;
6620 		/* Brand it as a hard case, forever. */
6621 		ipf->ipf_end = 0;
6622 	}
6623 	/* Walk through all the new pieces. */
6624 	do {
6625 		end = start + (mp->b_wptr - mp->b_rptr);
6626 		/*
6627 		 * If start is 0, decrease 'end' only for the first mblk of
6628 		 * the fragment. Otherwise 'end' can get wrong value in the
6629 		 * second pass of the loop if first mblk is exactly the
6630 		 * size of ipf_nf_hdr_len.
6631 		 */
6632 		if (start == 0 && !offset_zero_seen) {
6633 			/* First segment */
6634 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6635 			end -= ipf->ipf_nf_hdr_len;
6636 			offset_zero_seen = B_TRUE;
6637 		}
6638 		next_mp = mp->b_cont;
6639 		/*
6640 		 * We are checking to see if there is any interesing data
6641 		 * to process.  If there isn't and the mblk isn't the
6642 		 * one which carries the unfragmentable header then we
6643 		 * drop it.  It's possible to have just the unfragmentable
6644 		 * header come through without any data.  That needs to be
6645 		 * saved.
6646 		 *
6647 		 * If the assert at the top of this function holds then the
6648 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6649 		 * is infrequently traveled enough that the test is left in
6650 		 * to protect against future code changes which break that
6651 		 * invariant.
6652 		 */
6653 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6654 			/* Empty.  Blast it. */
6655 			IP_REASS_SET_START(mp, 0);
6656 			IP_REASS_SET_END(mp, 0);
6657 			/*
6658 			 * If the ipf points to the mblk we are about to free,
6659 			 * update ipf to point to the next mblk (or NULL
6660 			 * if none).
6661 			 */
6662 			if (ipf->ipf_mp->b_cont == mp)
6663 				ipf->ipf_mp->b_cont = next_mp;
6664 			freeb(mp);
6665 			continue;
6666 		}
6667 		mp->b_cont = NULL;
6668 		IP_REASS_SET_START(mp, start);
6669 		IP_REASS_SET_END(mp, end);
6670 		if (!ipf->ipf_tail_mp) {
6671 			ipf->ipf_tail_mp = mp;
6672 			ipf->ipf_mp->b_cont = mp;
6673 			if (start == 0 || !more) {
6674 				ipf->ipf_hole_cnt = 1;
6675 				/*
6676 				 * if the first fragment comes in more than one
6677 				 * mblk, this loop will be executed for each
6678 				 * mblk. Need to adjust hole count so exiting
6679 				 * this routine will leave hole count at 1.
6680 				 */
6681 				if (next_mp)
6682 					ipf->ipf_hole_cnt++;
6683 			} else
6684 				ipf->ipf_hole_cnt = 2;
6685 			continue;
6686 		} else if (ipf->ipf_last_frag_seen && !more &&
6687 		    !pkt_boundary_checked) {
6688 			/*
6689 			 * We check datagram boundary only if this fragment
6690 			 * claims to be the last fragment and we have seen a
6691 			 * last fragment in the past too. We do this only
6692 			 * once for a given fragment.
6693 			 *
6694 			 * start cannot be 0 here as fragments with start=0
6695 			 * and MF=0 gets handled as a complete packet. These
6696 			 * fragments should not reach here.
6697 			 */
6698 
6699 			if (start + msgdsize(mp) !=
6700 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6701 				/*
6702 				 * We have two fragments both of which claim
6703 				 * to be the last fragment but gives conflicting
6704 				 * information about the whole datagram size.
6705 				 * Something fishy is going on. Drop the
6706 				 * fragment and free up the reassembly list.
6707 				 */
6708 				return (IP_REASS_FAILED);
6709 			}
6710 
6711 			/*
6712 			 * We shouldn't come to this code block again for this
6713 			 * particular fragment.
6714 			 */
6715 			pkt_boundary_checked = B_TRUE;
6716 		}
6717 
6718 		/* New stuff at or beyond tail? */
6719 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6720 		if (start >= offset) {
6721 			if (ipf->ipf_last_frag_seen) {
6722 				/* current fragment is beyond last fragment */
6723 				return (IP_REASS_FAILED);
6724 			}
6725 			/* Link it on end. */
6726 			ipf->ipf_tail_mp->b_cont = mp;
6727 			ipf->ipf_tail_mp = mp;
6728 			if (more) {
6729 				if (start != offset)
6730 					ipf->ipf_hole_cnt++;
6731 			} else if (start == offset && next_mp == NULL)
6732 					ipf->ipf_hole_cnt--;
6733 			continue;
6734 		}
6735 		mp1 = ipf->ipf_mp->b_cont;
6736 		offset = IP_REASS_START(mp1);
6737 		/* New stuff at the front? */
6738 		if (start < offset) {
6739 			if (start == 0) {
6740 				if (end >= offset) {
6741 					/* Nailed the hole at the begining. */
6742 					ipf->ipf_hole_cnt--;
6743 				}
6744 			} else if (end < offset) {
6745 				/*
6746 				 * A hole, stuff, and a hole where there used
6747 				 * to be just a hole.
6748 				 */
6749 				ipf->ipf_hole_cnt++;
6750 			}
6751 			mp->b_cont = mp1;
6752 			/* Check for overlap. */
6753 			while (end > offset) {
6754 				if (end < IP_REASS_END(mp1)) {
6755 					mp->b_wptr -= end - offset;
6756 					IP_REASS_SET_END(mp, offset);
6757 					BUMP_MIB(ill->ill_ip_mib,
6758 					    ipIfStatsReasmPartDups);
6759 					break;
6760 				}
6761 				/* Did we cover another hole? */
6762 				if ((mp1->b_cont &&
6763 				    IP_REASS_END(mp1) !=
6764 				    IP_REASS_START(mp1->b_cont) &&
6765 				    end >= IP_REASS_START(mp1->b_cont)) ||
6766 				    (!ipf->ipf_last_frag_seen && !more)) {
6767 					ipf->ipf_hole_cnt--;
6768 				}
6769 				/* Clip out mp1. */
6770 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6771 					/*
6772 					 * After clipping out mp1, this guy
6773 					 * is now hanging off the end.
6774 					 */
6775 					ipf->ipf_tail_mp = mp;
6776 				}
6777 				IP_REASS_SET_START(mp1, 0);
6778 				IP_REASS_SET_END(mp1, 0);
6779 				/* Subtract byte count */
6780 				ipf->ipf_count -= mp1->b_datap->db_lim -
6781 				    mp1->b_datap->db_base;
6782 				freeb(mp1);
6783 				BUMP_MIB(ill->ill_ip_mib,
6784 				    ipIfStatsReasmPartDups);
6785 				mp1 = mp->b_cont;
6786 				if (!mp1)
6787 					break;
6788 				offset = IP_REASS_START(mp1);
6789 			}
6790 			ipf->ipf_mp->b_cont = mp;
6791 			continue;
6792 		}
6793 		/*
6794 		 * The new piece starts somewhere between the start of the head
6795 		 * and before the end of the tail.
6796 		 */
6797 		for (; mp1; mp1 = mp1->b_cont) {
6798 			offset = IP_REASS_END(mp1);
6799 			if (start < offset) {
6800 				if (end <= offset) {
6801 					/* Nothing new. */
6802 					IP_REASS_SET_START(mp, 0);
6803 					IP_REASS_SET_END(mp, 0);
6804 					/* Subtract byte count */
6805 					ipf->ipf_count -= mp->b_datap->db_lim -
6806 					    mp->b_datap->db_base;
6807 					if (incr_dups) {
6808 						ipf->ipf_num_dups++;
6809 						incr_dups = B_FALSE;
6810 					}
6811 					freeb(mp);
6812 					BUMP_MIB(ill->ill_ip_mib,
6813 					    ipIfStatsReasmDuplicates);
6814 					break;
6815 				}
6816 				/*
6817 				 * Trim redundant stuff off beginning of new
6818 				 * piece.
6819 				 */
6820 				IP_REASS_SET_START(mp, offset);
6821 				mp->b_rptr += offset - start;
6822 				BUMP_MIB(ill->ill_ip_mib,
6823 				    ipIfStatsReasmPartDups);
6824 				start = offset;
6825 				if (!mp1->b_cont) {
6826 					/*
6827 					 * After trimming, this guy is now
6828 					 * hanging off the end.
6829 					 */
6830 					mp1->b_cont = mp;
6831 					ipf->ipf_tail_mp = mp;
6832 					if (!more) {
6833 						ipf->ipf_hole_cnt--;
6834 					}
6835 					break;
6836 				}
6837 			}
6838 			if (start >= IP_REASS_START(mp1->b_cont))
6839 				continue;
6840 			/* Fill a hole */
6841 			if (start > offset)
6842 				ipf->ipf_hole_cnt++;
6843 			mp->b_cont = mp1->b_cont;
6844 			mp1->b_cont = mp;
6845 			mp1 = mp->b_cont;
6846 			offset = IP_REASS_START(mp1);
6847 			if (end >= offset) {
6848 				ipf->ipf_hole_cnt--;
6849 				/* Check for overlap. */
6850 				while (end > offset) {
6851 					if (end < IP_REASS_END(mp1)) {
6852 						mp->b_wptr -= end - offset;
6853 						IP_REASS_SET_END(mp, offset);
6854 						/*
6855 						 * TODO we might bump
6856 						 * this up twice if there is
6857 						 * overlap at both ends.
6858 						 */
6859 						BUMP_MIB(ill->ill_ip_mib,
6860 						    ipIfStatsReasmPartDups);
6861 						break;
6862 					}
6863 					/* Did we cover another hole? */
6864 					if ((mp1->b_cont &&
6865 					    IP_REASS_END(mp1)
6866 					    != IP_REASS_START(mp1->b_cont) &&
6867 					    end >=
6868 					    IP_REASS_START(mp1->b_cont)) ||
6869 					    (!ipf->ipf_last_frag_seen &&
6870 					    !more)) {
6871 						ipf->ipf_hole_cnt--;
6872 					}
6873 					/* Clip out mp1. */
6874 					if ((mp->b_cont = mp1->b_cont) ==
6875 					    NULL) {
6876 						/*
6877 						 * After clipping out mp1,
6878 						 * this guy is now hanging
6879 						 * off the end.
6880 						 */
6881 						ipf->ipf_tail_mp = mp;
6882 					}
6883 					IP_REASS_SET_START(mp1, 0);
6884 					IP_REASS_SET_END(mp1, 0);
6885 					/* Subtract byte count */
6886 					ipf->ipf_count -=
6887 					    mp1->b_datap->db_lim -
6888 					    mp1->b_datap->db_base;
6889 					freeb(mp1);
6890 					BUMP_MIB(ill->ill_ip_mib,
6891 					    ipIfStatsReasmPartDups);
6892 					mp1 = mp->b_cont;
6893 					if (!mp1)
6894 						break;
6895 					offset = IP_REASS_START(mp1);
6896 				}
6897 			}
6898 			break;
6899 		}
6900 	} while (start = end, mp = next_mp);
6901 
6902 	/* Fragment just processed could be the last one. Remember this fact */
6903 	if (!more)
6904 		ipf->ipf_last_frag_seen = B_TRUE;
6905 
6906 	/* Still got holes? */
6907 	if (ipf->ipf_hole_cnt)
6908 		return (IP_REASS_PARTIAL);
6909 	/* Clean up overloaded fields to avoid upstream disasters. */
6910 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6911 		IP_REASS_SET_START(mp1, 0);
6912 		IP_REASS_SET_END(mp1, 0);
6913 	}
6914 	return (IP_REASS_COMPLETE);
6915 }
6916 
6917 /*
6918  * Fragmentation reassembly.  Each ILL has a hash table for
6919  * queuing packets undergoing reassembly for all IPIFs
6920  * associated with the ILL.  The hash is based on the packet
6921  * IP ident field.  The ILL frag hash table was allocated
6922  * as a timer block at the time the ILL was created.  Whenever
6923  * there is anything on the reassembly queue, the timer will
6924  * be running.  Returns the reassembled packet if reassembly completes.
6925  */
6926 mblk_t *
6927 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
6928 {
6929 	uint32_t	frag_offset_flags;
6930 	mblk_t		*t_mp;
6931 	ipaddr_t	dst;
6932 	uint8_t		proto = ipha->ipha_protocol;
6933 	uint32_t	sum_val;
6934 	uint16_t	sum_flags;
6935 	ipf_t		*ipf;
6936 	ipf_t		**ipfp;
6937 	ipfb_t		*ipfb;
6938 	uint16_t	ident;
6939 	uint32_t	offset;
6940 	ipaddr_t	src;
6941 	uint_t		hdr_length;
6942 	uint32_t	end;
6943 	mblk_t		*mp1;
6944 	mblk_t		*tail_mp;
6945 	size_t		count;
6946 	size_t		msg_len;
6947 	uint8_t		ecn_info = 0;
6948 	uint32_t	packet_size;
6949 	boolean_t	pruned = B_FALSE;
6950 	ill_t		*ill = ira->ira_ill;
6951 	ip_stack_t	*ipst = ill->ill_ipst;
6952 
6953 	/*
6954 	 * Drop the fragmented as early as possible, if
6955 	 * we don't have resource(s) to re-assemble.
6956 	 */
6957 	if (ipst->ips_ip_reass_queue_bytes == 0) {
6958 		freemsg(mp);
6959 		return (NULL);
6960 	}
6961 
6962 	/* Check for fragmentation offset; return if there's none */
6963 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
6964 	    (IPH_MF | IPH_OFFSET)) == 0)
6965 		return (mp);
6966 
6967 	/*
6968 	 * We utilize hardware computed checksum info only for UDP since
6969 	 * IP fragmentation is a normal occurrence for the protocol.  In
6970 	 * addition, checksum offload support for IP fragments carrying
6971 	 * UDP payload is commonly implemented across network adapters.
6972 	 */
6973 	ASSERT(ira->ira_rill != NULL);
6974 	if (proto == IPPROTO_UDP && dohwcksum &&
6975 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
6976 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
6977 		mblk_t *mp1 = mp->b_cont;
6978 		int32_t len;
6979 
6980 		/* Record checksum information from the packet */
6981 		sum_val = (uint32_t)DB_CKSUM16(mp);
6982 		sum_flags = DB_CKSUMFLAGS(mp);
6983 
6984 		/* IP payload offset from beginning of mblk */
6985 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
6986 
6987 		if ((sum_flags & HCK_PARTIALCKSUM) &&
6988 		    (mp1 == NULL || mp1->b_cont == NULL) &&
6989 		    offset >= DB_CKSUMSTART(mp) &&
6990 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
6991 			uint32_t adj;
6992 			/*
6993 			 * Partial checksum has been calculated by hardware
6994 			 * and attached to the packet; in addition, any
6995 			 * prepended extraneous data is even byte aligned.
6996 			 * If any such data exists, we adjust the checksum;
6997 			 * this would also handle any postpended data.
6998 			 */
6999 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7000 			    mp, mp1, len, adj);
7001 
7002 			/* One's complement subtract extraneous checksum */
7003 			if (adj >= sum_val)
7004 				sum_val = ~(adj - sum_val) & 0xFFFF;
7005 			else
7006 				sum_val -= adj;
7007 		}
7008 	} else {
7009 		sum_val = 0;
7010 		sum_flags = 0;
7011 	}
7012 
7013 	/* Clear hardware checksumming flag */
7014 	DB_CKSUMFLAGS(mp) = 0;
7015 
7016 	ident = ipha->ipha_ident;
7017 	offset = (frag_offset_flags << 3) & 0xFFFF;
7018 	src = ipha->ipha_src;
7019 	dst = ipha->ipha_dst;
7020 	hdr_length = IPH_HDR_LENGTH(ipha);
7021 	end = ntohs(ipha->ipha_length) - hdr_length;
7022 
7023 	/* If end == 0 then we have a packet with no data, so just free it */
7024 	if (end == 0) {
7025 		freemsg(mp);
7026 		return (NULL);
7027 	}
7028 
7029 	/* Record the ECN field info. */
7030 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7031 	if (offset != 0) {
7032 		/*
7033 		 * If this isn't the first piece, strip the header, and
7034 		 * add the offset to the end value.
7035 		 */
7036 		mp->b_rptr += hdr_length;
7037 		end += offset;
7038 	}
7039 
7040 	/* Handle vnic loopback of fragments */
7041 	if (mp->b_datap->db_ref > 2)
7042 		msg_len = 0;
7043 	else
7044 		msg_len = MBLKSIZE(mp);
7045 
7046 	tail_mp = mp;
7047 	while (tail_mp->b_cont != NULL) {
7048 		tail_mp = tail_mp->b_cont;
7049 		if (tail_mp->b_datap->db_ref <= 2)
7050 			msg_len += MBLKSIZE(tail_mp);
7051 	}
7052 
7053 	/* If the reassembly list for this ILL will get too big, prune it */
7054 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7055 	    ipst->ips_ip_reass_queue_bytes) {
7056 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7057 		    uint_t, ill->ill_frag_count,
7058 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7059 		ill_frag_prune(ill,
7060 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7061 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7062 		pruned = B_TRUE;
7063 	}
7064 
7065 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7066 	mutex_enter(&ipfb->ipfb_lock);
7067 
7068 	ipfp = &ipfb->ipfb_ipf;
7069 	/* Try to find an existing fragment queue for this packet. */
7070 	for (;;) {
7071 		ipf = ipfp[0];
7072 		if (ipf != NULL) {
7073 			/*
7074 			 * It has to match on ident and src/dst address.
7075 			 */
7076 			if (ipf->ipf_ident == ident &&
7077 			    ipf->ipf_src == src &&
7078 			    ipf->ipf_dst == dst &&
7079 			    ipf->ipf_protocol == proto) {
7080 				/*
7081 				 * If we have received too many
7082 				 * duplicate fragments for this packet
7083 				 * free it.
7084 				 */
7085 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7086 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7087 					freemsg(mp);
7088 					mutex_exit(&ipfb->ipfb_lock);
7089 					return (NULL);
7090 				}
7091 				/* Found it. */
7092 				break;
7093 			}
7094 			ipfp = &ipf->ipf_hash_next;
7095 			continue;
7096 		}
7097 
7098 		/*
7099 		 * If we pruned the list, do we want to store this new
7100 		 * fragment?. We apply an optimization here based on the
7101 		 * fact that most fragments will be received in order.
7102 		 * So if the offset of this incoming fragment is zero,
7103 		 * it is the first fragment of a new packet. We will
7104 		 * keep it.  Otherwise drop the fragment, as we have
7105 		 * probably pruned the packet already (since the
7106 		 * packet cannot be found).
7107 		 */
7108 		if (pruned && offset != 0) {
7109 			mutex_exit(&ipfb->ipfb_lock);
7110 			freemsg(mp);
7111 			return (NULL);
7112 		}
7113 
7114 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7115 			/*
7116 			 * Too many fragmented packets in this hash
7117 			 * bucket. Free the oldest.
7118 			 */
7119 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7120 		}
7121 
7122 		/* New guy.  Allocate a frag message. */
7123 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7124 		if (mp1 == NULL) {
7125 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7126 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7127 			freemsg(mp);
7128 reass_done:
7129 			mutex_exit(&ipfb->ipfb_lock);
7130 			return (NULL);
7131 		}
7132 
7133 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7134 		mp1->b_cont = mp;
7135 
7136 		/* Initialize the fragment header. */
7137 		ipf = (ipf_t *)mp1->b_rptr;
7138 		ipf->ipf_mp = mp1;
7139 		ipf->ipf_ptphn = ipfp;
7140 		ipfp[0] = ipf;
7141 		ipf->ipf_hash_next = NULL;
7142 		ipf->ipf_ident = ident;
7143 		ipf->ipf_protocol = proto;
7144 		ipf->ipf_src = src;
7145 		ipf->ipf_dst = dst;
7146 		ipf->ipf_nf_hdr_len = 0;
7147 		/* Record reassembly start time. */
7148 		ipf->ipf_timestamp = gethrestime_sec();
7149 		/* Record ipf generation and account for frag header */
7150 		ipf->ipf_gen = ill->ill_ipf_gen++;
7151 		ipf->ipf_count = MBLKSIZE(mp1);
7152 		ipf->ipf_last_frag_seen = B_FALSE;
7153 		ipf->ipf_ecn = ecn_info;
7154 		ipf->ipf_num_dups = 0;
7155 		ipfb->ipfb_frag_pkts++;
7156 		ipf->ipf_checksum = 0;
7157 		ipf->ipf_checksum_flags = 0;
7158 
7159 		/* Store checksum value in fragment header */
7160 		if (sum_flags != 0) {
7161 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7162 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7163 			ipf->ipf_checksum = sum_val;
7164 			ipf->ipf_checksum_flags = sum_flags;
7165 		}
7166 
7167 		/*
7168 		 * We handle reassembly two ways.  In the easy case,
7169 		 * where all the fragments show up in order, we do
7170 		 * minimal bookkeeping, and just clip new pieces on
7171 		 * the end.  If we ever see a hole, then we go off
7172 		 * to ip_reassemble which has to mark the pieces and
7173 		 * keep track of the number of holes, etc.  Obviously,
7174 		 * the point of having both mechanisms is so we can
7175 		 * handle the easy case as efficiently as possible.
7176 		 */
7177 		if (offset == 0) {
7178 			/* Easy case, in-order reassembly so far. */
7179 			ipf->ipf_count += msg_len;
7180 			ipf->ipf_tail_mp = tail_mp;
7181 			/*
7182 			 * Keep track of next expected offset in
7183 			 * ipf_end.
7184 			 */
7185 			ipf->ipf_end = end;
7186 			ipf->ipf_nf_hdr_len = hdr_length;
7187 		} else {
7188 			/* Hard case, hole at the beginning. */
7189 			ipf->ipf_tail_mp = NULL;
7190 			/*
7191 			 * ipf_end == 0 means that we have given up
7192 			 * on easy reassembly.
7193 			 */
7194 			ipf->ipf_end = 0;
7195 
7196 			/* Forget checksum offload from now on */
7197 			ipf->ipf_checksum_flags = 0;
7198 
7199 			/*
7200 			 * ipf_hole_cnt is set by ip_reassemble.
7201 			 * ipf_count is updated by ip_reassemble.
7202 			 * No need to check for return value here
7203 			 * as we don't expect reassembly to complete
7204 			 * or fail for the first fragment itself.
7205 			 */
7206 			(void) ip_reassemble(mp, ipf,
7207 			    (frag_offset_flags & IPH_OFFSET) << 3,
7208 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7209 		}
7210 		/* Update per ipfb and ill byte counts */
7211 		ipfb->ipfb_count += ipf->ipf_count;
7212 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7213 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7214 		/* If the frag timer wasn't already going, start it. */
7215 		mutex_enter(&ill->ill_lock);
7216 		ill_frag_timer_start(ill);
7217 		mutex_exit(&ill->ill_lock);
7218 		goto reass_done;
7219 	}
7220 
7221 	/*
7222 	 * If the packet's flag has changed (it could be coming up
7223 	 * from an interface different than the previous, therefore
7224 	 * possibly different checksum capability), then forget about
7225 	 * any stored checksum states.  Otherwise add the value to
7226 	 * the existing one stored in the fragment header.
7227 	 */
7228 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7229 		sum_val += ipf->ipf_checksum;
7230 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7231 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7232 		ipf->ipf_checksum = sum_val;
7233 	} else if (ipf->ipf_checksum_flags != 0) {
7234 		/* Forget checksum offload from now on */
7235 		ipf->ipf_checksum_flags = 0;
7236 	}
7237 
7238 	/*
7239 	 * We have a new piece of a datagram which is already being
7240 	 * reassembled.  Update the ECN info if all IP fragments
7241 	 * are ECN capable.  If there is one which is not, clear
7242 	 * all the info.  If there is at least one which has CE
7243 	 * code point, IP needs to report that up to transport.
7244 	 */
7245 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7246 		if (ecn_info == IPH_ECN_CE)
7247 			ipf->ipf_ecn = IPH_ECN_CE;
7248 	} else {
7249 		ipf->ipf_ecn = IPH_ECN_NECT;
7250 	}
7251 	if (offset && ipf->ipf_end == offset) {
7252 		/* The new fragment fits at the end */
7253 		ipf->ipf_tail_mp->b_cont = mp;
7254 		/* Update the byte count */
7255 		ipf->ipf_count += msg_len;
7256 		/* Update per ipfb and ill byte counts */
7257 		ipfb->ipfb_count += msg_len;
7258 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7259 		atomic_add_32(&ill->ill_frag_count, msg_len);
7260 		if (frag_offset_flags & IPH_MF) {
7261 			/* More to come. */
7262 			ipf->ipf_end = end;
7263 			ipf->ipf_tail_mp = tail_mp;
7264 			goto reass_done;
7265 		}
7266 	} else {
7267 		/* Go do the hard cases. */
7268 		int ret;
7269 
7270 		if (offset == 0)
7271 			ipf->ipf_nf_hdr_len = hdr_length;
7272 
7273 		/* Save current byte count */
7274 		count = ipf->ipf_count;
7275 		ret = ip_reassemble(mp, ipf,
7276 		    (frag_offset_flags & IPH_OFFSET) << 3,
7277 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7278 		/* Count of bytes added and subtracted (freeb()ed) */
7279 		count = ipf->ipf_count - count;
7280 		if (count) {
7281 			/* Update per ipfb and ill byte counts */
7282 			ipfb->ipfb_count += count;
7283 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7284 			atomic_add_32(&ill->ill_frag_count, count);
7285 		}
7286 		if (ret == IP_REASS_PARTIAL) {
7287 			goto reass_done;
7288 		} else if (ret == IP_REASS_FAILED) {
7289 			/* Reassembly failed. Free up all resources */
7290 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7291 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7292 				IP_REASS_SET_START(t_mp, 0);
7293 				IP_REASS_SET_END(t_mp, 0);
7294 			}
7295 			freemsg(mp);
7296 			goto reass_done;
7297 		}
7298 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7299 	}
7300 	/*
7301 	 * We have completed reassembly.  Unhook the frag header from
7302 	 * the reassembly list.
7303 	 *
7304 	 * Before we free the frag header, record the ECN info
7305 	 * to report back to the transport.
7306 	 */
7307 	ecn_info = ipf->ipf_ecn;
7308 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7309 	ipfp = ipf->ipf_ptphn;
7310 
7311 	/* We need to supply these to caller */
7312 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7313 		sum_val = ipf->ipf_checksum;
7314 	else
7315 		sum_val = 0;
7316 
7317 	mp1 = ipf->ipf_mp;
7318 	count = ipf->ipf_count;
7319 	ipf = ipf->ipf_hash_next;
7320 	if (ipf != NULL)
7321 		ipf->ipf_ptphn = ipfp;
7322 	ipfp[0] = ipf;
7323 	atomic_add_32(&ill->ill_frag_count, -count);
7324 	ASSERT(ipfb->ipfb_count >= count);
7325 	ipfb->ipfb_count -= count;
7326 	ipfb->ipfb_frag_pkts--;
7327 	mutex_exit(&ipfb->ipfb_lock);
7328 	/* Ditch the frag header. */
7329 	mp = mp1->b_cont;
7330 
7331 	freeb(mp1);
7332 
7333 	/* Restore original IP length in header. */
7334 	packet_size = (uint32_t)msgdsize(mp);
7335 	if (packet_size > IP_MAXPACKET) {
7336 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7337 		ip_drop_input("Reassembled packet too large", mp, ill);
7338 		freemsg(mp);
7339 		return (NULL);
7340 	}
7341 
7342 	if (DB_REF(mp) > 1) {
7343 		mblk_t *mp2 = copymsg(mp);
7344 
7345 		if (mp2 == NULL) {
7346 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7347 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7348 			freemsg(mp);
7349 			return (NULL);
7350 		}
7351 		freemsg(mp);
7352 		mp = mp2;
7353 	}
7354 	ipha = (ipha_t *)mp->b_rptr;
7355 
7356 	ipha->ipha_length = htons((uint16_t)packet_size);
7357 	/* We're now complete, zip the frag state */
7358 	ipha->ipha_fragment_offset_and_flags = 0;
7359 	/* Record the ECN info. */
7360 	ipha->ipha_type_of_service &= 0xFC;
7361 	ipha->ipha_type_of_service |= ecn_info;
7362 
7363 	/* Update the receive attributes */
7364 	ira->ira_pktlen = packet_size;
7365 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7366 
7367 	/* Reassembly is successful; set checksum information in packet */
7368 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7369 	DB_CKSUMFLAGS(mp) = sum_flags;
7370 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7371 
7372 	return (mp);
7373 }
7374 
7375 /*
7376  * Pullup function that should be used for IP input in order to
7377  * ensure we do not loose the L2 source address; we need the l2 source
7378  * address for IP_RECVSLLA and for ndp_input.
7379  *
7380  * We return either NULL or b_rptr.
7381  */
7382 void *
7383 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7384 {
7385 	ill_t		*ill = ira->ira_ill;
7386 
7387 	if (ip_rput_pullups++ == 0) {
7388 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7389 		    "ip_pullup: %s forced us to "
7390 		    " pullup pkt, hdr len %ld, hdr addr %p",
7391 		    ill->ill_name, len, (void *)mp->b_rptr);
7392 	}
7393 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7394 		ip_setl2src(mp, ira, ira->ira_rill);
7395 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7396 	if (!pullupmsg(mp, len))
7397 		return (NULL);
7398 	else
7399 		return (mp->b_rptr);
7400 }
7401 
7402 /*
7403  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7404  * When called from the ULP ira_rill will be NULL hence the caller has to
7405  * pass in the ill.
7406  */
7407 /* ARGSUSED */
7408 void
7409 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7410 {
7411 	const uchar_t *addr;
7412 	int alen;
7413 
7414 	if (ira->ira_flags & IRAF_L2SRC_SET)
7415 		return;
7416 
7417 	ASSERT(ill != NULL);
7418 	alen = ill->ill_phys_addr_length;
7419 	ASSERT(alen <= sizeof (ira->ira_l2src));
7420 	if (ira->ira_mhip != NULL &&
7421 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7422 		bcopy(addr, ira->ira_l2src, alen);
7423 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7424 	    (addr = ill->ill_phys_addr) != NULL) {
7425 		bcopy(addr, ira->ira_l2src, alen);
7426 	} else {
7427 		bzero(ira->ira_l2src, alen);
7428 	}
7429 	ira->ira_flags |= IRAF_L2SRC_SET;
7430 }
7431 
7432 /*
7433  * check ip header length and align it.
7434  */
7435 mblk_t *
7436 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7437 {
7438 	ill_t	*ill = ira->ira_ill;
7439 	ssize_t len;
7440 
7441 	len = MBLKL(mp);
7442 
7443 	if (!OK_32PTR(mp->b_rptr))
7444 		IP_STAT(ill->ill_ipst, ip_notaligned);
7445 	else
7446 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7447 
7448 	/* Guard against bogus device drivers */
7449 	if (len < 0) {
7450 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7451 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7452 		freemsg(mp);
7453 		return (NULL);
7454 	}
7455 
7456 	if (len == 0) {
7457 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7458 		mblk_t *mp1 = mp->b_cont;
7459 
7460 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7461 			ip_setl2src(mp, ira, ira->ira_rill);
7462 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7463 
7464 		freeb(mp);
7465 		mp = mp1;
7466 		if (mp == NULL)
7467 			return (NULL);
7468 
7469 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7470 			return (mp);
7471 	}
7472 	if (ip_pullup(mp, min_size, ira) == NULL) {
7473 		if (msgdsize(mp) < min_size) {
7474 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7475 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7476 		} else {
7477 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7478 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7479 		}
7480 		freemsg(mp);
7481 		return (NULL);
7482 	}
7483 	return (mp);
7484 }
7485 
7486 /*
7487  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7488  */
7489 mblk_t *
7490 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7491     uint_t min_size, ip_recv_attr_t *ira)
7492 {
7493 	ill_t	*ill = ira->ira_ill;
7494 
7495 	/*
7496 	 * Make sure we have data length consistent
7497 	 * with the IP header.
7498 	 */
7499 	if (mp->b_cont == NULL) {
7500 		/* pkt_len is based on ipha_len, not the mblk length */
7501 		if (pkt_len < min_size) {
7502 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7503 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7504 			freemsg(mp);
7505 			return (NULL);
7506 		}
7507 		if (len < 0) {
7508 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7509 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7510 			freemsg(mp);
7511 			return (NULL);
7512 		}
7513 		/* Drop any pad */
7514 		mp->b_wptr = rptr + pkt_len;
7515 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7516 		ASSERT(pkt_len >= min_size);
7517 		if (pkt_len < min_size) {
7518 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7519 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7520 			freemsg(mp);
7521 			return (NULL);
7522 		}
7523 		if (len < 0) {
7524 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7525 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7526 			freemsg(mp);
7527 			return (NULL);
7528 		}
7529 		/* Drop any pad */
7530 		(void) adjmsg(mp, -len);
7531 		/*
7532 		 * adjmsg may have freed an mblk from the chain, hence
7533 		 * invalidate any hw checksum here. This will force IP to
7534 		 * calculate the checksum in sw, but only for this packet.
7535 		 */
7536 		DB_CKSUMFLAGS(mp) = 0;
7537 		IP_STAT(ill->ill_ipst, ip_multimblk);
7538 	}
7539 	return (mp);
7540 }
7541 
7542 /*
7543  * Check that the IPv4 opt_len is consistent with the packet and pullup
7544  * the options.
7545  */
7546 mblk_t *
7547 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7548     ip_recv_attr_t *ira)
7549 {
7550 	ill_t	*ill = ira->ira_ill;
7551 	ssize_t len;
7552 
7553 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7554 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7555 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7556 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7557 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7558 		freemsg(mp);
7559 		return (NULL);
7560 	}
7561 
7562 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7563 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7564 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7565 		freemsg(mp);
7566 		return (NULL);
7567 	}
7568 	/*
7569 	 * Recompute complete header length and make sure we
7570 	 * have access to all of it.
7571 	 */
7572 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7573 	if (len > (mp->b_wptr - mp->b_rptr)) {
7574 		if (len > pkt_len) {
7575 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7576 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7577 			freemsg(mp);
7578 			return (NULL);
7579 		}
7580 		if (ip_pullup(mp, len, ira) == NULL) {
7581 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7582 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7583 			freemsg(mp);
7584 			return (NULL);
7585 		}
7586 	}
7587 	return (mp);
7588 }
7589 
7590 /*
7591  * Returns a new ire, or the same ire, or NULL.
7592  * If a different IRE is returned, then it is held; the caller
7593  * needs to release it.
7594  * In no case is there any hold/release on the ire argument.
7595  */
7596 ire_t *
7597 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7598 {
7599 	ire_t		*new_ire;
7600 	ill_t		*ire_ill;
7601 	uint_t		ifindex;
7602 	ip_stack_t	*ipst = ill->ill_ipst;
7603 	boolean_t	strict_check = B_FALSE;
7604 
7605 	/*
7606 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7607 	 * issue (e.g. packet received on an underlying interface matched an
7608 	 * IRE_LOCAL on its associated group interface).
7609 	 */
7610 	ASSERT(ire->ire_ill != NULL);
7611 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7612 		return (ire);
7613 
7614 	/*
7615 	 * Do another ire lookup here, using the ingress ill, to see if the
7616 	 * interface is in a usesrc group.
7617 	 * As long as the ills belong to the same group, we don't consider
7618 	 * them to be arriving on the wrong interface. Thus, if the switch
7619 	 * is doing inbound load spreading, we won't drop packets when the
7620 	 * ip*_strict_dst_multihoming switch is on.
7621 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7622 	 * where the local address may not be unique. In this case we were
7623 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7624 	 * actually returned. The new lookup, which is more specific, should
7625 	 * only find the IRE_LOCAL associated with the ingress ill if one
7626 	 * exists.
7627 	 */
7628 	if (ire->ire_ipversion == IPV4_VERSION) {
7629 		if (ipst->ips_ip_strict_dst_multihoming)
7630 			strict_check = B_TRUE;
7631 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7632 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7633 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7634 	} else {
7635 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7636 		if (ipst->ips_ipv6_strict_dst_multihoming)
7637 			strict_check = B_TRUE;
7638 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7639 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7640 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7641 	}
7642 	/*
7643 	 * If the same ire that was returned in ip_input() is found then this
7644 	 * is an indication that usesrc groups are in use. The packet
7645 	 * arrived on a different ill in the group than the one associated with
7646 	 * the destination address.  If a different ire was found then the same
7647 	 * IP address must be hosted on multiple ills. This is possible with
7648 	 * unnumbered point2point interfaces. We switch to use this new ire in
7649 	 * order to have accurate interface statistics.
7650 	 */
7651 	if (new_ire != NULL) {
7652 		/* Note: held in one case but not the other? Caller handles */
7653 		if (new_ire != ire)
7654 			return (new_ire);
7655 		/* Unchanged */
7656 		ire_refrele(new_ire);
7657 		return (ire);
7658 	}
7659 
7660 	/*
7661 	 * Chase pointers once and store locally.
7662 	 */
7663 	ASSERT(ire->ire_ill != NULL);
7664 	ire_ill = ire->ire_ill;
7665 	ifindex = ill->ill_usesrc_ifindex;
7666 
7667 	/*
7668 	 * Check if it's a legal address on the 'usesrc' interface.
7669 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7670 	 * can just check phyint_ifindex.
7671 	 */
7672 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7673 		return (ire);
7674 	}
7675 
7676 	/*
7677 	 * If the ip*_strict_dst_multihoming switch is on then we can
7678 	 * only accept this packet if the interface is marked as routing.
7679 	 */
7680 	if (!(strict_check))
7681 		return (ire);
7682 
7683 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7684 		return (ire);
7685 	}
7686 	return (NULL);
7687 }
7688 
7689 /*
7690  * This function is used to construct a mac_header_info_s from a
7691  * DL_UNITDATA_IND message.
7692  * The address fields in the mhi structure points into the message,
7693  * thus the caller can't use those fields after freeing the message.
7694  *
7695  * We determine whether the packet received is a non-unicast packet
7696  * and in doing so, determine whether or not it is broadcast vs multicast.
7697  * For it to be a broadcast packet, we must have the appropriate mblk_t
7698  * hanging off the ill_t.  If this is either not present or doesn't match
7699  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7700  * to be multicast.  Thus NICs that have no broadcast address (or no
7701  * capability for one, such as point to point links) cannot return as
7702  * the packet being broadcast.
7703  */
7704 void
7705 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7706 {
7707 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7708 	mblk_t *bmp;
7709 	uint_t extra_offset;
7710 
7711 	bzero(mhip, sizeof (struct mac_header_info_s));
7712 
7713 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7714 
7715 	if (ill->ill_sap_length < 0)
7716 		extra_offset = 0;
7717 	else
7718 		extra_offset = ill->ill_sap_length;
7719 
7720 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7721 	    extra_offset;
7722 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7723 	    extra_offset;
7724 
7725 	if (!ind->dl_group_address)
7726 		return;
7727 
7728 	/* Multicast or broadcast */
7729 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7730 
7731 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7732 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7733 	    (bmp = ill->ill_bcast_mp) != NULL) {
7734 		dl_unitdata_req_t *dlur;
7735 		uint8_t *bphys_addr;
7736 
7737 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7738 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7739 		    extra_offset;
7740 
7741 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7742 		    ind->dl_dest_addr_length) == 0)
7743 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7744 	}
7745 }
7746 
7747 /*
7748  * This function is used to construct a mac_header_info_s from a
7749  * M_DATA fastpath message from a DLPI driver.
7750  * The address fields in the mhi structure points into the message,
7751  * thus the caller can't use those fields after freeing the message.
7752  *
7753  * We determine whether the packet received is a non-unicast packet
7754  * and in doing so, determine whether or not it is broadcast vs multicast.
7755  * For it to be a broadcast packet, we must have the appropriate mblk_t
7756  * hanging off the ill_t.  If this is either not present or doesn't match
7757  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7758  * to be multicast.  Thus NICs that have no broadcast address (or no
7759  * capability for one, such as point to point links) cannot return as
7760  * the packet being broadcast.
7761  */
7762 void
7763 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7764 {
7765 	mblk_t *bmp;
7766 	struct ether_header *pether;
7767 
7768 	bzero(mhip, sizeof (struct mac_header_info_s));
7769 
7770 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7771 
7772 	pether = (struct ether_header *)((char *)mp->b_rptr
7773 	    - sizeof (struct ether_header));
7774 
7775 	/*
7776 	 * Make sure the interface is an ethernet type, since we don't
7777 	 * know the header format for anything but Ethernet. Also make
7778 	 * sure we are pointing correctly above db_base.
7779 	 */
7780 	if (ill->ill_type != IFT_ETHER)
7781 		return;
7782 
7783 retry:
7784 	if ((uchar_t *)pether < mp->b_datap->db_base)
7785 		return;
7786 
7787 	/* Is there a VLAN tag? */
7788 	if (ill->ill_isv6) {
7789 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7790 			pether = (struct ether_header *)((char *)pether - 4);
7791 			goto retry;
7792 		}
7793 	} else {
7794 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7795 			pether = (struct ether_header *)((char *)pether - 4);
7796 			goto retry;
7797 		}
7798 	}
7799 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7800 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7801 
7802 	if (!(mhip->mhi_daddr[0] & 0x01))
7803 		return;
7804 
7805 	/* Multicast or broadcast */
7806 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7807 
7808 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7809 		dl_unitdata_req_t *dlur;
7810 		uint8_t *bphys_addr;
7811 		uint_t	addrlen;
7812 
7813 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7814 		addrlen = dlur->dl_dest_addr_length;
7815 		if (ill->ill_sap_length < 0) {
7816 			bphys_addr = (uchar_t *)dlur +
7817 			    dlur->dl_dest_addr_offset;
7818 			addrlen += ill->ill_sap_length;
7819 		} else {
7820 			bphys_addr = (uchar_t *)dlur +
7821 			    dlur->dl_dest_addr_offset +
7822 			    ill->ill_sap_length;
7823 			addrlen -= ill->ill_sap_length;
7824 		}
7825 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7826 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7827 	}
7828 }
7829 
7830 /*
7831  * Handle anything but M_DATA messages
7832  * We see the DL_UNITDATA_IND which are part
7833  * of the data path, and also the other messages from the driver.
7834  */
7835 void
7836 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7837 {
7838 	mblk_t		*first_mp;
7839 	struct iocblk   *iocp;
7840 	struct mac_header_info_s mhi;
7841 
7842 	switch (DB_TYPE(mp)) {
7843 	case M_PROTO:
7844 	case M_PCPROTO: {
7845 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7846 		    DL_UNITDATA_IND) {
7847 			/* Go handle anything other than data elsewhere. */
7848 			ip_rput_dlpi(ill, mp);
7849 			return;
7850 		}
7851 
7852 		first_mp = mp;
7853 		mp = first_mp->b_cont;
7854 		first_mp->b_cont = NULL;
7855 
7856 		if (mp == NULL) {
7857 			freeb(first_mp);
7858 			return;
7859 		}
7860 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7861 		if (ill->ill_isv6)
7862 			ip_input_v6(ill, NULL, mp, &mhi);
7863 		else
7864 			ip_input(ill, NULL, mp, &mhi);
7865 
7866 		/* Ditch the DLPI header. */
7867 		freeb(first_mp);
7868 		return;
7869 	}
7870 	case M_IOCACK:
7871 		iocp = (struct iocblk *)mp->b_rptr;
7872 		switch (iocp->ioc_cmd) {
7873 		case DL_IOC_HDR_INFO:
7874 			ill_fastpath_ack(ill, mp);
7875 			return;
7876 		default:
7877 			putnext(ill->ill_rq, mp);
7878 			return;
7879 		}
7880 		/* FALLTHRU */
7881 	case M_ERROR:
7882 	case M_HANGUP:
7883 		mutex_enter(&ill->ill_lock);
7884 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7885 			mutex_exit(&ill->ill_lock);
7886 			freemsg(mp);
7887 			return;
7888 		}
7889 		ill_refhold_locked(ill);
7890 		mutex_exit(&ill->ill_lock);
7891 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7892 		    B_FALSE);
7893 		return;
7894 	case M_CTL:
7895 		putnext(ill->ill_rq, mp);
7896 		return;
7897 	case M_IOCNAK:
7898 		ip1dbg(("got iocnak "));
7899 		iocp = (struct iocblk *)mp->b_rptr;
7900 		switch (iocp->ioc_cmd) {
7901 		case DL_IOC_HDR_INFO:
7902 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7903 			return;
7904 		default:
7905 			break;
7906 		}
7907 		/* FALLTHRU */
7908 	default:
7909 		putnext(ill->ill_rq, mp);
7910 		return;
7911 	}
7912 }
7913 
7914 /* Read side put procedure.  Packets coming from the wire arrive here. */
7915 void
7916 ip_rput(queue_t *q, mblk_t *mp)
7917 {
7918 	ill_t	*ill;
7919 	union DL_primitives *dl;
7920 
7921 	ill = (ill_t *)q->q_ptr;
7922 
7923 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
7924 		/*
7925 		 * If things are opening or closing, only accept high-priority
7926 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
7927 		 * created; on close, things hanging off the ill may have been
7928 		 * freed already.)
7929 		 */
7930 		dl = (union DL_primitives *)mp->b_rptr;
7931 		if (DB_TYPE(mp) != M_PCPROTO ||
7932 		    dl->dl_primitive == DL_UNITDATA_IND) {
7933 			inet_freemsg(mp);
7934 			return;
7935 		}
7936 	}
7937 	if (DB_TYPE(mp) == M_DATA) {
7938 		struct mac_header_info_s mhi;
7939 
7940 		ip_mdata_to_mhi(ill, mp, &mhi);
7941 		ip_input(ill, NULL, mp, &mhi);
7942 	} else {
7943 		ip_rput_notdata(ill, mp);
7944 	}
7945 }
7946 
7947 /*
7948  * Move the information to a copy.
7949  */
7950 mblk_t *
7951 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
7952 {
7953 	mblk_t		*mp1;
7954 	ill_t		*ill = ira->ira_ill;
7955 	ip_stack_t	*ipst = ill->ill_ipst;
7956 
7957 	IP_STAT(ipst, ip_db_ref);
7958 
7959 	/* Make sure we have ira_l2src before we loose the original mblk */
7960 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7961 		ip_setl2src(mp, ira, ira->ira_rill);
7962 
7963 	mp1 = copymsg(mp);
7964 	if (mp1 == NULL) {
7965 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7966 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
7967 		freemsg(mp);
7968 		return (NULL);
7969 	}
7970 	/* preserve the hardware checksum flags and data, if present */
7971 	if (DB_CKSUMFLAGS(mp) != 0) {
7972 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
7973 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
7974 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
7975 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
7976 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
7977 	}
7978 	freemsg(mp);
7979 	return (mp1);
7980 }
7981 
7982 static void
7983 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
7984     t_uscalar_t err)
7985 {
7986 	if (dl_err == DL_SYSERR) {
7987 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
7988 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
7989 		    ill->ill_name, dl_primstr(prim), err);
7990 		return;
7991 	}
7992 
7993 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
7994 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
7995 	    dl_errstr(dl_err));
7996 }
7997 
7998 /*
7999  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8000  * than DL_UNITDATA_IND messages. If we need to process this message
8001  * exclusively, we call qwriter_ip, in which case we also need to call
8002  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8003  */
8004 void
8005 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8006 {
8007 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8008 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8009 	queue_t		*q = ill->ill_rq;
8010 	t_uscalar_t	prim = dloa->dl_primitive;
8011 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8012 
8013 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8014 	    char *, dl_primstr(prim), ill_t *, ill);
8015 	ip1dbg(("ip_rput_dlpi"));
8016 
8017 	/*
8018 	 * If we received an ACK but didn't send a request for it, then it
8019 	 * can't be part of any pending operation; discard up-front.
8020 	 */
8021 	switch (prim) {
8022 	case DL_ERROR_ACK:
8023 		reqprim = dlea->dl_error_primitive;
8024 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8025 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8026 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8027 		    dlea->dl_unix_errno));
8028 		break;
8029 	case DL_OK_ACK:
8030 		reqprim = dloa->dl_correct_primitive;
8031 		break;
8032 	case DL_INFO_ACK:
8033 		reqprim = DL_INFO_REQ;
8034 		break;
8035 	case DL_BIND_ACK:
8036 		reqprim = DL_BIND_REQ;
8037 		break;
8038 	case DL_PHYS_ADDR_ACK:
8039 		reqprim = DL_PHYS_ADDR_REQ;
8040 		break;
8041 	case DL_NOTIFY_ACK:
8042 		reqprim = DL_NOTIFY_REQ;
8043 		break;
8044 	case DL_CAPABILITY_ACK:
8045 		reqprim = DL_CAPABILITY_REQ;
8046 		break;
8047 	}
8048 
8049 	if (prim != DL_NOTIFY_IND) {
8050 		if (reqprim == DL_PRIM_INVAL ||
8051 		    !ill_dlpi_pending(ill, reqprim)) {
8052 			/* Not a DLPI message we support or expected */
8053 			freemsg(mp);
8054 			return;
8055 		}
8056 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8057 		    dl_primstr(reqprim)));
8058 	}
8059 
8060 	switch (reqprim) {
8061 	case DL_UNBIND_REQ:
8062 		/*
8063 		 * NOTE: we mark the unbind as complete even if we got a
8064 		 * DL_ERROR_ACK, since there's not much else we can do.
8065 		 */
8066 		mutex_enter(&ill->ill_lock);
8067 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8068 		cv_signal(&ill->ill_cv);
8069 		mutex_exit(&ill->ill_lock);
8070 		break;
8071 
8072 	case DL_ENABMULTI_REQ:
8073 		if (prim == DL_OK_ACK) {
8074 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8075 				ill->ill_dlpi_multicast_state = IDS_OK;
8076 		}
8077 		break;
8078 	}
8079 
8080 	/*
8081 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8082 	 * need to become writer to continue to process it.  Because an
8083 	 * exclusive operation doesn't complete until replies to all queued
8084 	 * DLPI messages have been received, we know we're in the middle of an
8085 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8086 	 *
8087 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8088 	 * Since this is on the ill stream we unconditionally bump up the
8089 	 * refcount without doing ILL_CAN_LOOKUP().
8090 	 */
8091 	ill_refhold(ill);
8092 	if (prim == DL_NOTIFY_IND)
8093 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8094 	else
8095 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8096 }
8097 
8098 /*
8099  * Handling of DLPI messages that require exclusive access to the ipsq.
8100  *
8101  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8102  * happen here. (along with mi_copy_done)
8103  */
8104 /* ARGSUSED */
8105 static void
8106 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8107 {
8108 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8109 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8110 	int		err = 0;
8111 	ill_t		*ill = (ill_t *)q->q_ptr;
8112 	ipif_t		*ipif = NULL;
8113 	mblk_t		*mp1 = NULL;
8114 	conn_t		*connp = NULL;
8115 	t_uscalar_t	paddrreq;
8116 	mblk_t		*mp_hw;
8117 	boolean_t	success;
8118 	boolean_t	ioctl_aborted = B_FALSE;
8119 	boolean_t	log = B_TRUE;
8120 
8121 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8122 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8123 
8124 	ip1dbg(("ip_rput_dlpi_writer .."));
8125 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8126 	ASSERT(IAM_WRITER_ILL(ill));
8127 
8128 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8129 	/*
8130 	 * The current ioctl could have been aborted by the user and a new
8131 	 * ioctl to bring up another ill could have started. We could still
8132 	 * get a response from the driver later.
8133 	 */
8134 	if (ipif != NULL && ipif->ipif_ill != ill)
8135 		ioctl_aborted = B_TRUE;
8136 
8137 	switch (dloa->dl_primitive) {
8138 	case DL_ERROR_ACK:
8139 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8140 		    dl_primstr(dlea->dl_error_primitive)));
8141 
8142 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8143 		    char *, dl_primstr(dlea->dl_error_primitive),
8144 		    ill_t *, ill);
8145 
8146 		switch (dlea->dl_error_primitive) {
8147 		case DL_DISABMULTI_REQ:
8148 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8149 			break;
8150 		case DL_PROMISCON_REQ:
8151 		case DL_PROMISCOFF_REQ:
8152 		case DL_UNBIND_REQ:
8153 		case DL_ATTACH_REQ:
8154 		case DL_INFO_REQ:
8155 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8156 			break;
8157 		case DL_NOTIFY_REQ:
8158 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8159 			log = B_FALSE;
8160 			break;
8161 		case DL_PHYS_ADDR_REQ:
8162 			/*
8163 			 * For IPv6 only, there are two additional
8164 			 * phys_addr_req's sent to the driver to get the
8165 			 * IPv6 token and lla. This allows IP to acquire
8166 			 * the hardware address format for a given interface
8167 			 * without having built in knowledge of the hardware
8168 			 * address. ill_phys_addr_pend keeps track of the last
8169 			 * DL_PAR sent so we know which response we are
8170 			 * dealing with. ill_dlpi_done will update
8171 			 * ill_phys_addr_pend when it sends the next req.
8172 			 * We don't complete the IOCTL until all three DL_PARs
8173 			 * have been attempted, so set *_len to 0 and break.
8174 			 */
8175 			paddrreq = ill->ill_phys_addr_pend;
8176 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8177 			if (paddrreq == DL_IPV6_TOKEN) {
8178 				ill->ill_token_length = 0;
8179 				log = B_FALSE;
8180 				break;
8181 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8182 				ill->ill_nd_lla_len = 0;
8183 				log = B_FALSE;
8184 				break;
8185 			}
8186 			/*
8187 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8188 			 * We presumably have an IOCTL hanging out waiting
8189 			 * for completion. Find it and complete the IOCTL
8190 			 * with the error noted.
8191 			 * However, ill_dl_phys was called on an ill queue
8192 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8193 			 * set. But the ioctl is known to be pending on ill_wq.
8194 			 */
8195 			if (!ill->ill_ifname_pending)
8196 				break;
8197 			ill->ill_ifname_pending = 0;
8198 			if (!ioctl_aborted)
8199 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8200 			if (mp1 != NULL) {
8201 				/*
8202 				 * This operation (SIOCSLIFNAME) must have
8203 				 * happened on the ill. Assert there is no conn
8204 				 */
8205 				ASSERT(connp == NULL);
8206 				q = ill->ill_wq;
8207 			}
8208 			break;
8209 		case DL_BIND_REQ:
8210 			ill_dlpi_done(ill, DL_BIND_REQ);
8211 			if (ill->ill_ifname_pending)
8212 				break;
8213 			/*
8214 			 * Something went wrong with the bind.  We presumably
8215 			 * have an IOCTL hanging out waiting for completion.
8216 			 * Find it, take down the interface that was coming
8217 			 * up, and complete the IOCTL with the error noted.
8218 			 */
8219 			if (!ioctl_aborted)
8220 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8221 			if (mp1 != NULL) {
8222 				/*
8223 				 * This might be a result of a DL_NOTE_REPLUMB
8224 				 * notification. In that case, connp is NULL.
8225 				 */
8226 				if (connp != NULL)
8227 					q = CONNP_TO_WQ(connp);
8228 
8229 				(void) ipif_down(ipif, NULL, NULL);
8230 				/* error is set below the switch */
8231 			}
8232 			break;
8233 		case DL_ENABMULTI_REQ:
8234 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8235 
8236 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8237 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8238 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8239 
8240 				printf("ip: joining multicasts failed (%d)"
8241 				    " on %s - will use link layer "
8242 				    "broadcasts for multicast\n",
8243 				    dlea->dl_errno, ill->ill_name);
8244 
8245 				/*
8246 				 * Set up for multi_bcast; We are the
8247 				 * writer, so ok to access ill->ill_ipif
8248 				 * without any lock.
8249 				 */
8250 				mutex_enter(&ill->ill_phyint->phyint_lock);
8251 				ill->ill_phyint->phyint_flags |=
8252 				    PHYI_MULTI_BCAST;
8253 				mutex_exit(&ill->ill_phyint->phyint_lock);
8254 
8255 			}
8256 			freemsg(mp);	/* Don't want to pass this up */
8257 			return;
8258 		case DL_CAPABILITY_REQ:
8259 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8260 			    "DL_CAPABILITY REQ\n"));
8261 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8262 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8263 			ill_capability_done(ill);
8264 			freemsg(mp);
8265 			return;
8266 		}
8267 		/*
8268 		 * Note the error for IOCTL completion (mp1 is set when
8269 		 * ready to complete ioctl). If ill_ifname_pending_err is
8270 		 * set, an error occured during plumbing (ill_ifname_pending),
8271 		 * so we want to report that error.
8272 		 *
8273 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8274 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8275 		 * expected to get errack'd if the driver doesn't support
8276 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8277 		 * if these error conditions are encountered.
8278 		 */
8279 		if (mp1 != NULL) {
8280 			if (ill->ill_ifname_pending_err != 0)  {
8281 				err = ill->ill_ifname_pending_err;
8282 				ill->ill_ifname_pending_err = 0;
8283 			} else {
8284 				err = dlea->dl_unix_errno ?
8285 				    dlea->dl_unix_errno : ENXIO;
8286 			}
8287 		/*
8288 		 * If we're plumbing an interface and an error hasn't already
8289 		 * been saved, set ill_ifname_pending_err to the error passed
8290 		 * up. Ignore the error if log is B_FALSE (see comment above).
8291 		 */
8292 		} else if (log && ill->ill_ifname_pending &&
8293 		    ill->ill_ifname_pending_err == 0) {
8294 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8295 			    dlea->dl_unix_errno : ENXIO;
8296 		}
8297 
8298 		if (log)
8299 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8300 			    dlea->dl_errno, dlea->dl_unix_errno);
8301 		break;
8302 	case DL_CAPABILITY_ACK:
8303 		ill_capability_ack(ill, mp);
8304 		/*
8305 		 * The message has been handed off to ill_capability_ack
8306 		 * and must not be freed below
8307 		 */
8308 		mp = NULL;
8309 		break;
8310 
8311 	case DL_INFO_ACK:
8312 		/* Call a routine to handle this one. */
8313 		ill_dlpi_done(ill, DL_INFO_REQ);
8314 		ip_ll_subnet_defaults(ill, mp);
8315 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8316 		return;
8317 	case DL_BIND_ACK:
8318 		/*
8319 		 * We should have an IOCTL waiting on this unless
8320 		 * sent by ill_dl_phys, in which case just return
8321 		 */
8322 		ill_dlpi_done(ill, DL_BIND_REQ);
8323 		if (ill->ill_ifname_pending) {
8324 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8325 			    ill_t *, ill, mblk_t *, mp);
8326 			break;
8327 		}
8328 		if (!ioctl_aborted)
8329 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8330 		if (mp1 == NULL) {
8331 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8332 			break;
8333 		}
8334 		/*
8335 		 * mp1 was added by ill_dl_up(). if that is a result of
8336 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8337 		 */
8338 		if (connp != NULL)
8339 			q = CONNP_TO_WQ(connp);
8340 		/*
8341 		 * We are exclusive. So nothing can change even after
8342 		 * we get the pending mp.
8343 		 */
8344 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8345 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8346 
8347 		mutex_enter(&ill->ill_lock);
8348 		ill->ill_dl_up = 1;
8349 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8350 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8351 		mutex_exit(&ill->ill_lock);
8352 
8353 		/*
8354 		 * Now bring up the resolver; when that is complete, we'll
8355 		 * create IREs.  Note that we intentionally mirror what
8356 		 * ipif_up() would have done, because we got here by way of
8357 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8358 		 */
8359 		if (ill->ill_isv6) {
8360 			/*
8361 			 * v6 interfaces.
8362 			 * Unlike ARP which has to do another bind
8363 			 * and attach, once we get here we are
8364 			 * done with NDP
8365 			 */
8366 			(void) ipif_resolver_up(ipif, Res_act_initial);
8367 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8368 				err = ipif_up_done_v6(ipif);
8369 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8370 			/*
8371 			 * ARP and other v4 external resolvers.
8372 			 * Leave the pending mblk intact so that
8373 			 * the ioctl completes in ip_rput().
8374 			 */
8375 			if (connp != NULL)
8376 				mutex_enter(&connp->conn_lock);
8377 			mutex_enter(&ill->ill_lock);
8378 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8379 			mutex_exit(&ill->ill_lock);
8380 			if (connp != NULL)
8381 				mutex_exit(&connp->conn_lock);
8382 			if (success) {
8383 				err = ipif_resolver_up(ipif, Res_act_initial);
8384 				if (err == EINPROGRESS) {
8385 					freemsg(mp);
8386 					return;
8387 				}
8388 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8389 			} else {
8390 				/* The conn has started closing */
8391 				err = EINTR;
8392 			}
8393 		} else {
8394 			/*
8395 			 * This one is complete. Reply to pending ioctl.
8396 			 */
8397 			(void) ipif_resolver_up(ipif, Res_act_initial);
8398 			err = ipif_up_done(ipif);
8399 		}
8400 
8401 		if ((err == 0) && (ill->ill_up_ipifs)) {
8402 			err = ill_up_ipifs(ill, q, mp1);
8403 			if (err == EINPROGRESS) {
8404 				freemsg(mp);
8405 				return;
8406 			}
8407 		}
8408 
8409 		/*
8410 		 * If we have a moved ipif to bring up, and everything has
8411 		 * succeeded to this point, bring it up on the IPMP ill.
8412 		 * Otherwise, leave it down -- the admin can try to bring it
8413 		 * up by hand if need be.
8414 		 */
8415 		if (ill->ill_move_ipif != NULL) {
8416 			if (err != 0) {
8417 				ill->ill_move_ipif = NULL;
8418 			} else {
8419 				ipif = ill->ill_move_ipif;
8420 				ill->ill_move_ipif = NULL;
8421 				err = ipif_up(ipif, q, mp1);
8422 				if (err == EINPROGRESS) {
8423 					freemsg(mp);
8424 					return;
8425 				}
8426 			}
8427 		}
8428 		break;
8429 
8430 	case DL_NOTIFY_IND: {
8431 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8432 		uint_t orig_mtu;
8433 
8434 		switch (notify->dl_notification) {
8435 		case DL_NOTE_PHYS_ADDR:
8436 			err = ill_set_phys_addr(ill, mp);
8437 			break;
8438 
8439 		case DL_NOTE_REPLUMB:
8440 			/*
8441 			 * Directly return after calling ill_replumb().
8442 			 * Note that we should not free mp as it is reused
8443 			 * in the ill_replumb() function.
8444 			 */
8445 			err = ill_replumb(ill, mp);
8446 			return;
8447 
8448 		case DL_NOTE_FASTPATH_FLUSH:
8449 			nce_flush(ill, B_FALSE);
8450 			break;
8451 
8452 		case DL_NOTE_SDU_SIZE:
8453 			/*
8454 			 * The dce and fragmentation code can cope with
8455 			 * this changing while packets are being sent.
8456 			 * When packets are sent ip_output will discover
8457 			 * a change.
8458 			 *
8459 			 * Change the MTU size of the interface.
8460 			 */
8461 			mutex_enter(&ill->ill_lock);
8462 			ill->ill_current_frag = (uint_t)notify->dl_data;
8463 			if (ill->ill_current_frag > ill->ill_max_frag)
8464 				ill->ill_max_frag = ill->ill_current_frag;
8465 
8466 			orig_mtu = ill->ill_mtu;
8467 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8468 				ill->ill_mtu = ill->ill_current_frag;
8469 
8470 				/*
8471 				 * If ill_user_mtu was set (via
8472 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8473 				 */
8474 				if (ill->ill_user_mtu != 0 &&
8475 				    ill->ill_user_mtu < ill->ill_mtu)
8476 					ill->ill_mtu = ill->ill_user_mtu;
8477 
8478 				if (ill->ill_isv6) {
8479 					if (ill->ill_mtu < IPV6_MIN_MTU)
8480 						ill->ill_mtu = IPV6_MIN_MTU;
8481 				} else {
8482 					if (ill->ill_mtu < IP_MIN_MTU)
8483 						ill->ill_mtu = IP_MIN_MTU;
8484 				}
8485 			}
8486 			mutex_exit(&ill->ill_lock);
8487 			/*
8488 			 * Make sure all dce_generation checks find out
8489 			 * that ill_mtu has changed.
8490 			 */
8491 			if (orig_mtu != ill->ill_mtu) {
8492 				dce_increment_all_generations(ill->ill_isv6,
8493 				    ill->ill_ipst);
8494 			}
8495 
8496 			/*
8497 			 * Refresh IPMP meta-interface MTU if necessary.
8498 			 */
8499 			if (IS_UNDER_IPMP(ill))
8500 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8501 			break;
8502 
8503 		case DL_NOTE_LINK_UP:
8504 		case DL_NOTE_LINK_DOWN: {
8505 			/*
8506 			 * We are writer. ill / phyint / ipsq assocs stable.
8507 			 * The RUNNING flag reflects the state of the link.
8508 			 */
8509 			phyint_t *phyint = ill->ill_phyint;
8510 			uint64_t new_phyint_flags;
8511 			boolean_t changed = B_FALSE;
8512 			boolean_t went_up;
8513 
8514 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8515 			mutex_enter(&phyint->phyint_lock);
8516 
8517 			new_phyint_flags = went_up ?
8518 			    phyint->phyint_flags | PHYI_RUNNING :
8519 			    phyint->phyint_flags & ~PHYI_RUNNING;
8520 
8521 			if (IS_IPMP(ill)) {
8522 				new_phyint_flags = went_up ?
8523 				    new_phyint_flags & ~PHYI_FAILED :
8524 				    new_phyint_flags | PHYI_FAILED;
8525 			}
8526 
8527 			if (new_phyint_flags != phyint->phyint_flags) {
8528 				phyint->phyint_flags = new_phyint_flags;
8529 				changed = B_TRUE;
8530 			}
8531 			mutex_exit(&phyint->phyint_lock);
8532 			/*
8533 			 * ill_restart_dad handles the DAD restart and routing
8534 			 * socket notification logic.
8535 			 */
8536 			if (changed) {
8537 				ill_restart_dad(phyint->phyint_illv4, went_up);
8538 				ill_restart_dad(phyint->phyint_illv6, went_up);
8539 			}
8540 			break;
8541 		}
8542 		case DL_NOTE_PROMISC_ON_PHYS: {
8543 			phyint_t *phyint = ill->ill_phyint;
8544 
8545 			mutex_enter(&phyint->phyint_lock);
8546 			phyint->phyint_flags |= PHYI_PROMISC;
8547 			mutex_exit(&phyint->phyint_lock);
8548 			break;
8549 		}
8550 		case DL_NOTE_PROMISC_OFF_PHYS: {
8551 			phyint_t *phyint = ill->ill_phyint;
8552 
8553 			mutex_enter(&phyint->phyint_lock);
8554 			phyint->phyint_flags &= ~PHYI_PROMISC;
8555 			mutex_exit(&phyint->phyint_lock);
8556 			break;
8557 		}
8558 		case DL_NOTE_CAPAB_RENEG:
8559 			/*
8560 			 * Something changed on the driver side.
8561 			 * It wants us to renegotiate the capabilities
8562 			 * on this ill. One possible cause is the aggregation
8563 			 * interface under us where a port got added or
8564 			 * went away.
8565 			 *
8566 			 * If the capability negotiation is already done
8567 			 * or is in progress, reset the capabilities and
8568 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8569 			 * so that when the ack comes back, we can start
8570 			 * the renegotiation process.
8571 			 *
8572 			 * Note that if ill_capab_reneg is already B_TRUE
8573 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8574 			 * the capability resetting request has been sent
8575 			 * and the renegotiation has not been started yet;
8576 			 * nothing needs to be done in this case.
8577 			 */
8578 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8579 			ill_capability_reset(ill, B_TRUE);
8580 			ipsq_current_finish(ipsq);
8581 			break;
8582 
8583 		case DL_NOTE_ALLOWED_IPS:
8584 			ill_set_allowed_ips(ill, mp);
8585 			break;
8586 		default:
8587 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8588 			    "type 0x%x for DL_NOTIFY_IND\n",
8589 			    notify->dl_notification));
8590 			break;
8591 		}
8592 
8593 		/*
8594 		 * As this is an asynchronous operation, we
8595 		 * should not call ill_dlpi_done
8596 		 */
8597 		break;
8598 	}
8599 	case DL_NOTIFY_ACK: {
8600 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8601 
8602 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8603 			ill->ill_note_link = 1;
8604 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8605 		break;
8606 	}
8607 	case DL_PHYS_ADDR_ACK: {
8608 		/*
8609 		 * As part of plumbing the interface via SIOCSLIFNAME,
8610 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8611 		 * whose answers we receive here.  As each answer is received,
8612 		 * we call ill_dlpi_done() to dispatch the next request as
8613 		 * we're processing the current one.  Once all answers have
8614 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8615 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8616 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8617 		 * available, but we know the ioctl is pending on ill_wq.)
8618 		 */
8619 		uint_t	paddrlen, paddroff;
8620 		uint8_t	*addr;
8621 
8622 		paddrreq = ill->ill_phys_addr_pend;
8623 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8624 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8625 		addr = mp->b_rptr + paddroff;
8626 
8627 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8628 		if (paddrreq == DL_IPV6_TOKEN) {
8629 			/*
8630 			 * bcopy to low-order bits of ill_token
8631 			 *
8632 			 * XXX Temporary hack - currently, all known tokens
8633 			 * are 64 bits, so I'll cheat for the moment.
8634 			 */
8635 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8636 			ill->ill_token_length = paddrlen;
8637 			break;
8638 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8639 			ASSERT(ill->ill_nd_lla_mp == NULL);
8640 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8641 			mp = NULL;
8642 			break;
8643 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8644 			ASSERT(ill->ill_dest_addr_mp == NULL);
8645 			ill->ill_dest_addr_mp = mp;
8646 			ill->ill_dest_addr = addr;
8647 			mp = NULL;
8648 			if (ill->ill_isv6) {
8649 				ill_setdesttoken(ill);
8650 				ipif_setdestlinklocal(ill->ill_ipif);
8651 			}
8652 			break;
8653 		}
8654 
8655 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8656 		ASSERT(ill->ill_phys_addr_mp == NULL);
8657 		if (!ill->ill_ifname_pending)
8658 			break;
8659 		ill->ill_ifname_pending = 0;
8660 		if (!ioctl_aborted)
8661 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8662 		if (mp1 != NULL) {
8663 			ASSERT(connp == NULL);
8664 			q = ill->ill_wq;
8665 		}
8666 		/*
8667 		 * If any error acks received during the plumbing sequence,
8668 		 * ill_ifname_pending_err will be set. Break out and send up
8669 		 * the error to the pending ioctl.
8670 		 */
8671 		if (ill->ill_ifname_pending_err != 0) {
8672 			err = ill->ill_ifname_pending_err;
8673 			ill->ill_ifname_pending_err = 0;
8674 			break;
8675 		}
8676 
8677 		ill->ill_phys_addr_mp = mp;
8678 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8679 		mp = NULL;
8680 
8681 		/*
8682 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8683 		 * provider doesn't support physical addresses.  We check both
8684 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8685 		 * not have physical addresses, but historically adversises a
8686 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8687 		 * its DL_PHYS_ADDR_ACK.
8688 		 */
8689 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8690 			ill->ill_phys_addr = NULL;
8691 		} else if (paddrlen != ill->ill_phys_addr_length) {
8692 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8693 			    paddrlen, ill->ill_phys_addr_length));
8694 			err = EINVAL;
8695 			break;
8696 		}
8697 
8698 		if (ill->ill_nd_lla_mp == NULL) {
8699 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8700 				err = ENOMEM;
8701 				break;
8702 			}
8703 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8704 		}
8705 
8706 		if (ill->ill_isv6) {
8707 			ill_setdefaulttoken(ill);
8708 			ipif_setlinklocal(ill->ill_ipif);
8709 		}
8710 		break;
8711 	}
8712 	case DL_OK_ACK:
8713 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8714 		    dl_primstr((int)dloa->dl_correct_primitive),
8715 		    dloa->dl_correct_primitive));
8716 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8717 		    char *, dl_primstr(dloa->dl_correct_primitive),
8718 		    ill_t *, ill);
8719 
8720 		switch (dloa->dl_correct_primitive) {
8721 		case DL_ENABMULTI_REQ:
8722 		case DL_DISABMULTI_REQ:
8723 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8724 			break;
8725 		case DL_PROMISCON_REQ:
8726 		case DL_PROMISCOFF_REQ:
8727 		case DL_UNBIND_REQ:
8728 		case DL_ATTACH_REQ:
8729 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8730 			break;
8731 		}
8732 		break;
8733 	default:
8734 		break;
8735 	}
8736 
8737 	freemsg(mp);
8738 	if (mp1 == NULL)
8739 		return;
8740 
8741 	/*
8742 	 * The operation must complete without EINPROGRESS since
8743 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8744 	 * the operation will be stuck forever inside the IPSQ.
8745 	 */
8746 	ASSERT(err != EINPROGRESS);
8747 
8748 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8749 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8750 	    ipif_t *, NULL);
8751 
8752 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8753 	case 0:
8754 		ipsq_current_finish(ipsq);
8755 		break;
8756 
8757 	case SIOCSLIFNAME:
8758 	case IF_UNITSEL: {
8759 		ill_t *ill_other = ILL_OTHER(ill);
8760 
8761 		/*
8762 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8763 		 * ill has a peer which is in an IPMP group, then place ill
8764 		 * into the same group.  One catch: although ifconfig plumbs
8765 		 * the appropriate IPMP meta-interface prior to plumbing this
8766 		 * ill, it is possible for multiple ifconfig applications to
8767 		 * race (or for another application to adjust plumbing), in
8768 		 * which case the IPMP meta-interface we need will be missing.
8769 		 * If so, kick the phyint out of the group.
8770 		 */
8771 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8772 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8773 			ipmp_illgrp_t	*illg;
8774 
8775 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8776 			if (illg == NULL)
8777 				ipmp_phyint_leave_grp(ill->ill_phyint);
8778 			else
8779 				ipmp_ill_join_illgrp(ill, illg);
8780 		}
8781 
8782 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8783 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8784 		else
8785 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8786 		break;
8787 	}
8788 	case SIOCLIFADDIF:
8789 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8790 		break;
8791 
8792 	default:
8793 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8794 		break;
8795 	}
8796 }
8797 
8798 /*
8799  * ip_rput_other is called by ip_rput to handle messages modifying the global
8800  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8801  */
8802 /* ARGSUSED */
8803 void
8804 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8805 {
8806 	ill_t		*ill = q->q_ptr;
8807 	struct iocblk	*iocp;
8808 
8809 	ip1dbg(("ip_rput_other "));
8810 	if (ipsq != NULL) {
8811 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8812 		ASSERT(ipsq->ipsq_xop ==
8813 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8814 	}
8815 
8816 	switch (mp->b_datap->db_type) {
8817 	case M_ERROR:
8818 	case M_HANGUP:
8819 		/*
8820 		 * The device has a problem.  We force the ILL down.  It can
8821 		 * be brought up again manually using SIOCSIFFLAGS (via
8822 		 * ifconfig or equivalent).
8823 		 */
8824 		ASSERT(ipsq != NULL);
8825 		if (mp->b_rptr < mp->b_wptr)
8826 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8827 		if (ill->ill_error == 0)
8828 			ill->ill_error = ENXIO;
8829 		if (!ill_down_start(q, mp))
8830 			return;
8831 		ipif_all_down_tail(ipsq, q, mp, NULL);
8832 		break;
8833 	case M_IOCNAK: {
8834 		iocp = (struct iocblk *)mp->b_rptr;
8835 
8836 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8837 		/*
8838 		 * If this was the first attempt, turn off the fastpath
8839 		 * probing.
8840 		 */
8841 		mutex_enter(&ill->ill_lock);
8842 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8843 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8844 			mutex_exit(&ill->ill_lock);
8845 			/*
8846 			 * don't flush the nce_t entries: we use them
8847 			 * as an index to the ncec itself.
8848 			 */
8849 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8850 			    ill->ill_name));
8851 		} else {
8852 			mutex_exit(&ill->ill_lock);
8853 		}
8854 		freemsg(mp);
8855 		break;
8856 	}
8857 	default:
8858 		ASSERT(0);
8859 		break;
8860 	}
8861 }
8862 
8863 /*
8864  * Update any source route, record route or timestamp options
8865  * When it fails it has consumed the message and BUMPed the MIB.
8866  */
8867 boolean_t
8868 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8869     ip_recv_attr_t *ira)
8870 {
8871 	ipoptp_t	opts;
8872 	uchar_t		*opt;
8873 	uint8_t		optval;
8874 	uint8_t		optlen;
8875 	ipaddr_t	dst;
8876 	ipaddr_t	ifaddr;
8877 	uint32_t	ts;
8878 	timestruc_t	now;
8879 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
8880 
8881 	ip2dbg(("ip_forward_options\n"));
8882 	dst = ipha->ipha_dst;
8883 	for (optval = ipoptp_first(&opts, ipha);
8884 	    optval != IPOPT_EOL;
8885 	    optval = ipoptp_next(&opts)) {
8886 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
8887 		opt = opts.ipoptp_cur;
8888 		optlen = opts.ipoptp_len;
8889 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
8890 		    optval, opts.ipoptp_len));
8891 		switch (optval) {
8892 			uint32_t off;
8893 		case IPOPT_SSRR:
8894 		case IPOPT_LSRR:
8895 			/* Check if adminstratively disabled */
8896 			if (!ipst->ips_ip_forward_src_routed) {
8897 				BUMP_MIB(dst_ill->ill_ip_mib,
8898 				    ipIfStatsForwProhibits);
8899 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
8900 				    mp, dst_ill);
8901 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
8902 				    ira);
8903 				return (B_FALSE);
8904 			}
8905 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8906 				/*
8907 				 * Must be partial since ip_input_options
8908 				 * checked for strict.
8909 				 */
8910 				break;
8911 			}
8912 			off = opt[IPOPT_OFFSET];
8913 			off--;
8914 		redo_srr:
8915 			if (optlen < IP_ADDR_LEN ||
8916 			    off > optlen - IP_ADDR_LEN) {
8917 				/* End of source route */
8918 				ip1dbg((
8919 				    "ip_forward_options: end of SR\n"));
8920 				break;
8921 			}
8922 			/* Pick a reasonable address on the outbound if */
8923 			ASSERT(dst_ill != NULL);
8924 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8925 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8926 			    NULL) != 0) {
8927 				/* No source! Shouldn't happen */
8928 				ifaddr = INADDR_ANY;
8929 			}
8930 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8931 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8932 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
8933 			    ntohl(dst)));
8934 
8935 			/*
8936 			 * Check if our address is present more than
8937 			 * once as consecutive hops in source route.
8938 			 */
8939 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
8940 				off += IP_ADDR_LEN;
8941 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8942 				goto redo_srr;
8943 			}
8944 			ipha->ipha_dst = dst;
8945 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8946 			break;
8947 		case IPOPT_RR:
8948 			off = opt[IPOPT_OFFSET];
8949 			off--;
8950 			if (optlen < IP_ADDR_LEN ||
8951 			    off > optlen - IP_ADDR_LEN) {
8952 				/* No more room - ignore */
8953 				ip1dbg((
8954 				    "ip_forward_options: end of RR\n"));
8955 				break;
8956 			}
8957 			/* Pick a reasonable address on the outbound if */
8958 			ASSERT(dst_ill != NULL);
8959 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8960 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8961 			    NULL) != 0) {
8962 				/* No source! Shouldn't happen */
8963 				ifaddr = INADDR_ANY;
8964 			}
8965 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8966 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8967 			break;
8968 		case IPOPT_TS:
8969 			/* Insert timestamp if there is room */
8970 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
8971 			case IPOPT_TS_TSONLY:
8972 				off = IPOPT_TS_TIMELEN;
8973 				break;
8974 			case IPOPT_TS_PRESPEC:
8975 			case IPOPT_TS_PRESPEC_RFC791:
8976 				/* Verify that the address matched */
8977 				off = opt[IPOPT_OFFSET] - 1;
8978 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8979 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8980 					/* Not for us */
8981 					break;
8982 				}
8983 				/* FALLTHRU */
8984 			case IPOPT_TS_TSANDADDR:
8985 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
8986 				break;
8987 			default:
8988 				/*
8989 				 * ip_*put_options should have already
8990 				 * dropped this packet.
8991 				 */
8992 				cmn_err(CE_PANIC, "ip_forward_options: "
8993 				    "unknown IT - bug in ip_input_options?\n");
8994 				return (B_TRUE);	/* Keep "lint" happy */
8995 			}
8996 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
8997 				/* Increase overflow counter */
8998 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
8999 				opt[IPOPT_POS_OV_FLG] =
9000 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9001 				    (off << 4));
9002 				break;
9003 			}
9004 			off = opt[IPOPT_OFFSET] - 1;
9005 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9006 			case IPOPT_TS_PRESPEC:
9007 			case IPOPT_TS_PRESPEC_RFC791:
9008 			case IPOPT_TS_TSANDADDR:
9009 				/* Pick a reasonable addr on the outbound if */
9010 				ASSERT(dst_ill != NULL);
9011 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9012 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9013 				    NULL, NULL) != 0) {
9014 					/* No source! Shouldn't happen */
9015 					ifaddr = INADDR_ANY;
9016 				}
9017 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9018 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9019 				/* FALLTHRU */
9020 			case IPOPT_TS_TSONLY:
9021 				off = opt[IPOPT_OFFSET] - 1;
9022 				/* Compute # of milliseconds since midnight */
9023 				gethrestime(&now);
9024 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9025 				    now.tv_nsec / (NANOSEC / MILLISEC);
9026 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9027 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9028 				break;
9029 			}
9030 			break;
9031 		}
9032 	}
9033 	return (B_TRUE);
9034 }
9035 
9036 /*
9037  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9038  * returns 'true' if there are still fragments left on the queue, in
9039  * which case we restart the timer.
9040  */
9041 void
9042 ill_frag_timer(void *arg)
9043 {
9044 	ill_t	*ill = (ill_t *)arg;
9045 	boolean_t frag_pending;
9046 	ip_stack_t *ipst = ill->ill_ipst;
9047 	time_t	timeout;
9048 
9049 	mutex_enter(&ill->ill_lock);
9050 	ASSERT(!ill->ill_fragtimer_executing);
9051 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9052 		ill->ill_frag_timer_id = 0;
9053 		mutex_exit(&ill->ill_lock);
9054 		return;
9055 	}
9056 	ill->ill_fragtimer_executing = 1;
9057 	mutex_exit(&ill->ill_lock);
9058 
9059 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9060 	    ipst->ips_ip_reassembly_timeout);
9061 
9062 	frag_pending = ill_frag_timeout(ill, timeout);
9063 
9064 	/*
9065 	 * Restart the timer, if we have fragments pending or if someone
9066 	 * wanted us to be scheduled again.
9067 	 */
9068 	mutex_enter(&ill->ill_lock);
9069 	ill->ill_fragtimer_executing = 0;
9070 	ill->ill_frag_timer_id = 0;
9071 	if (frag_pending || ill->ill_fragtimer_needrestart)
9072 		ill_frag_timer_start(ill);
9073 	mutex_exit(&ill->ill_lock);
9074 }
9075 
9076 void
9077 ill_frag_timer_start(ill_t *ill)
9078 {
9079 	ip_stack_t *ipst = ill->ill_ipst;
9080 	clock_t	timeo_ms;
9081 
9082 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9083 
9084 	/* If the ill is closing or opening don't proceed */
9085 	if (ill->ill_state_flags & ILL_CONDEMNED)
9086 		return;
9087 
9088 	if (ill->ill_fragtimer_executing) {
9089 		/*
9090 		 * ill_frag_timer is currently executing. Just record the
9091 		 * the fact that we want the timer to be restarted.
9092 		 * ill_frag_timer will post a timeout before it returns,
9093 		 * ensuring it will be called again.
9094 		 */
9095 		ill->ill_fragtimer_needrestart = 1;
9096 		return;
9097 	}
9098 
9099 	if (ill->ill_frag_timer_id == 0) {
9100 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9101 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9102 
9103 		/*
9104 		 * The timer is neither running nor is the timeout handler
9105 		 * executing. Post a timeout so that ill_frag_timer will be
9106 		 * called
9107 		 */
9108 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9109 		    MSEC_TO_TICK(timeo_ms >> 1));
9110 		ill->ill_fragtimer_needrestart = 0;
9111 	}
9112 }
9113 
9114 /*
9115  * Update any source route, record route or timestamp options.
9116  * Check that we are at end of strict source route.
9117  * The options have already been checked for sanity in ip_input_options().
9118  */
9119 boolean_t
9120 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9121 {
9122 	ipoptp_t	opts;
9123 	uchar_t		*opt;
9124 	uint8_t		optval;
9125 	uint8_t		optlen;
9126 	ipaddr_t	dst;
9127 	ipaddr_t	ifaddr;
9128 	uint32_t	ts;
9129 	timestruc_t	now;
9130 	ill_t		*ill = ira->ira_ill;
9131 	ip_stack_t	*ipst = ill->ill_ipst;
9132 
9133 	ip2dbg(("ip_input_local_options\n"));
9134 
9135 	for (optval = ipoptp_first(&opts, ipha);
9136 	    optval != IPOPT_EOL;
9137 	    optval = ipoptp_next(&opts)) {
9138 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9139 		opt = opts.ipoptp_cur;
9140 		optlen = opts.ipoptp_len;
9141 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9142 		    optval, optlen));
9143 		switch (optval) {
9144 			uint32_t off;
9145 		case IPOPT_SSRR:
9146 		case IPOPT_LSRR:
9147 			off = opt[IPOPT_OFFSET];
9148 			off--;
9149 			if (optlen < IP_ADDR_LEN ||
9150 			    off > optlen - IP_ADDR_LEN) {
9151 				/* End of source route */
9152 				ip1dbg(("ip_input_local_options: end of SR\n"));
9153 				break;
9154 			}
9155 			/*
9156 			 * This will only happen if two consecutive entries
9157 			 * in the source route contains our address or if
9158 			 * it is a packet with a loose source route which
9159 			 * reaches us before consuming the whole source route
9160 			 */
9161 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9162 			if (optval == IPOPT_SSRR) {
9163 				goto bad_src_route;
9164 			}
9165 			/*
9166 			 * Hack: instead of dropping the packet truncate the
9167 			 * source route to what has been used by filling the
9168 			 * rest with IPOPT_NOP.
9169 			 */
9170 			opt[IPOPT_OLEN] = (uint8_t)off;
9171 			while (off < optlen) {
9172 				opt[off++] = IPOPT_NOP;
9173 			}
9174 			break;
9175 		case IPOPT_RR:
9176 			off = opt[IPOPT_OFFSET];
9177 			off--;
9178 			if (optlen < IP_ADDR_LEN ||
9179 			    off > optlen - IP_ADDR_LEN) {
9180 				/* No more room - ignore */
9181 				ip1dbg((
9182 				    "ip_input_local_options: end of RR\n"));
9183 				break;
9184 			}
9185 			/* Pick a reasonable address on the outbound if */
9186 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9187 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9188 			    NULL) != 0) {
9189 				/* No source! Shouldn't happen */
9190 				ifaddr = INADDR_ANY;
9191 			}
9192 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9193 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9194 			break;
9195 		case IPOPT_TS:
9196 			/* Insert timestamp if there is romm */
9197 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9198 			case IPOPT_TS_TSONLY:
9199 				off = IPOPT_TS_TIMELEN;
9200 				break;
9201 			case IPOPT_TS_PRESPEC:
9202 			case IPOPT_TS_PRESPEC_RFC791:
9203 				/* Verify that the address matched */
9204 				off = opt[IPOPT_OFFSET] - 1;
9205 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9206 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9207 					/* Not for us */
9208 					break;
9209 				}
9210 				/* FALLTHRU */
9211 			case IPOPT_TS_TSANDADDR:
9212 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9213 				break;
9214 			default:
9215 				/*
9216 				 * ip_*put_options should have already
9217 				 * dropped this packet.
9218 				 */
9219 				cmn_err(CE_PANIC, "ip_input_local_options: "
9220 				    "unknown IT - bug in ip_input_options?\n");
9221 				return (B_TRUE);	/* Keep "lint" happy */
9222 			}
9223 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9224 				/* Increase overflow counter */
9225 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9226 				opt[IPOPT_POS_OV_FLG] =
9227 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9228 				    (off << 4));
9229 				break;
9230 			}
9231 			off = opt[IPOPT_OFFSET] - 1;
9232 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9233 			case IPOPT_TS_PRESPEC:
9234 			case IPOPT_TS_PRESPEC_RFC791:
9235 			case IPOPT_TS_TSANDADDR:
9236 				/* Pick a reasonable addr on the outbound if */
9237 				if (ip_select_source_v4(ill, INADDR_ANY,
9238 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9239 				    &ifaddr, NULL, NULL) != 0) {
9240 					/* No source! Shouldn't happen */
9241 					ifaddr = INADDR_ANY;
9242 				}
9243 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9244 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9245 				/* FALLTHRU */
9246 			case IPOPT_TS_TSONLY:
9247 				off = opt[IPOPT_OFFSET] - 1;
9248 				/* Compute # of milliseconds since midnight */
9249 				gethrestime(&now);
9250 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9251 				    now.tv_nsec / (NANOSEC / MILLISEC);
9252 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9253 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9254 				break;
9255 			}
9256 			break;
9257 		}
9258 	}
9259 	return (B_TRUE);
9260 
9261 bad_src_route:
9262 	/* make sure we clear any indication of a hardware checksum */
9263 	DB_CKSUMFLAGS(mp) = 0;
9264 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9265 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9266 	return (B_FALSE);
9267 
9268 }
9269 
9270 /*
9271  * Process IP options in an inbound packet.  Always returns the nexthop.
9272  * Normally this is the passed in nexthop, but if there is an option
9273  * that effects the nexthop (such as a source route) that will be returned.
9274  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9275  * and mp freed.
9276  */
9277 ipaddr_t
9278 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9279     ip_recv_attr_t *ira, int *errorp)
9280 {
9281 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9282 	ipoptp_t	opts;
9283 	uchar_t		*opt;
9284 	uint8_t		optval;
9285 	uint8_t		optlen;
9286 	intptr_t	code = 0;
9287 	ire_t		*ire;
9288 
9289 	ip2dbg(("ip_input_options\n"));
9290 	*errorp = 0;
9291 	for (optval = ipoptp_first(&opts, ipha);
9292 	    optval != IPOPT_EOL;
9293 	    optval = ipoptp_next(&opts)) {
9294 		opt = opts.ipoptp_cur;
9295 		optlen = opts.ipoptp_len;
9296 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9297 		    optval, optlen));
9298 		/*
9299 		 * Note: we need to verify the checksum before we
9300 		 * modify anything thus this routine only extracts the next
9301 		 * hop dst from any source route.
9302 		 */
9303 		switch (optval) {
9304 			uint32_t off;
9305 		case IPOPT_SSRR:
9306 		case IPOPT_LSRR:
9307 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9308 				if (optval == IPOPT_SSRR) {
9309 					ip1dbg(("ip_input_options: not next"
9310 					    " strict source route 0x%x\n",
9311 					    ntohl(dst)));
9312 					code = (char *)&ipha->ipha_dst -
9313 					    (char *)ipha;
9314 					goto param_prob; /* RouterReq's */
9315 				}
9316 				ip2dbg(("ip_input_options: "
9317 				    "not next source route 0x%x\n",
9318 				    ntohl(dst)));
9319 				break;
9320 			}
9321 
9322 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9323 				ip1dbg((
9324 				    "ip_input_options: bad option offset\n"));
9325 				code = (char *)&opt[IPOPT_OLEN] -
9326 				    (char *)ipha;
9327 				goto param_prob;
9328 			}
9329 			off = opt[IPOPT_OFFSET];
9330 			off--;
9331 		redo_srr:
9332 			if (optlen < IP_ADDR_LEN ||
9333 			    off > optlen - IP_ADDR_LEN) {
9334 				/* End of source route */
9335 				ip1dbg(("ip_input_options: end of SR\n"));
9336 				break;
9337 			}
9338 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9339 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9340 			    ntohl(dst)));
9341 
9342 			/*
9343 			 * Check if our address is present more than
9344 			 * once as consecutive hops in source route.
9345 			 * XXX verify per-interface ip_forwarding
9346 			 * for source route?
9347 			 */
9348 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9349 				off += IP_ADDR_LEN;
9350 				goto redo_srr;
9351 			}
9352 
9353 			if (dst == htonl(INADDR_LOOPBACK)) {
9354 				ip1dbg(("ip_input_options: loopback addr in "
9355 				    "source route!\n"));
9356 				goto bad_src_route;
9357 			}
9358 			/*
9359 			 * For strict: verify that dst is directly
9360 			 * reachable.
9361 			 */
9362 			if (optval == IPOPT_SSRR) {
9363 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9364 				    IRE_IF_ALL, NULL, ALL_ZONES,
9365 				    ira->ira_tsl,
9366 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9367 				    NULL);
9368 				if (ire == NULL) {
9369 					ip1dbg(("ip_input_options: SSRR not "
9370 					    "directly reachable: 0x%x\n",
9371 					    ntohl(dst)));
9372 					goto bad_src_route;
9373 				}
9374 				ire_refrele(ire);
9375 			}
9376 			/*
9377 			 * Defer update of the offset and the record route
9378 			 * until the packet is forwarded.
9379 			 */
9380 			break;
9381 		case IPOPT_RR:
9382 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9383 				ip1dbg((
9384 				    "ip_input_options: bad option offset\n"));
9385 				code = (char *)&opt[IPOPT_OLEN] -
9386 				    (char *)ipha;
9387 				goto param_prob;
9388 			}
9389 			break;
9390 		case IPOPT_TS:
9391 			/*
9392 			 * Verify that length >= 5 and that there is either
9393 			 * room for another timestamp or that the overflow
9394 			 * counter is not maxed out.
9395 			 */
9396 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9397 			if (optlen < IPOPT_MINLEN_IT) {
9398 				goto param_prob;
9399 			}
9400 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9401 				ip1dbg((
9402 				    "ip_input_options: bad option offset\n"));
9403 				code = (char *)&opt[IPOPT_OFFSET] -
9404 				    (char *)ipha;
9405 				goto param_prob;
9406 			}
9407 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9408 			case IPOPT_TS_TSONLY:
9409 				off = IPOPT_TS_TIMELEN;
9410 				break;
9411 			case IPOPT_TS_TSANDADDR:
9412 			case IPOPT_TS_PRESPEC:
9413 			case IPOPT_TS_PRESPEC_RFC791:
9414 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9415 				break;
9416 			default:
9417 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9418 				    (char *)ipha;
9419 				goto param_prob;
9420 			}
9421 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9422 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9423 				/*
9424 				 * No room and the overflow counter is 15
9425 				 * already.
9426 				 */
9427 				goto param_prob;
9428 			}
9429 			break;
9430 		}
9431 	}
9432 
9433 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9434 		return (dst);
9435 	}
9436 
9437 	ip1dbg(("ip_input_options: error processing IP options."));
9438 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9439 
9440 param_prob:
9441 	/* make sure we clear any indication of a hardware checksum */
9442 	DB_CKSUMFLAGS(mp) = 0;
9443 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9444 	icmp_param_problem(mp, (uint8_t)code, ira);
9445 	*errorp = -1;
9446 	return (dst);
9447 
9448 bad_src_route:
9449 	/* make sure we clear any indication of a hardware checksum */
9450 	DB_CKSUMFLAGS(mp) = 0;
9451 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9452 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9453 	*errorp = -1;
9454 	return (dst);
9455 }
9456 
9457 /*
9458  * IP & ICMP info in >=14 msg's ...
9459  *  - ip fixed part (mib2_ip_t)
9460  *  - icmp fixed part (mib2_icmp_t)
9461  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9462  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9463  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9464  *  - ipRouteAttributeTable (ip 102)	labeled routes
9465  *  - ip multicast membership (ip_member_t)
9466  *  - ip multicast source filtering (ip_grpsrc_t)
9467  *  - igmp fixed part (struct igmpstat)
9468  *  - multicast routing stats (struct mrtstat)
9469  *  - multicast routing vifs (array of struct vifctl)
9470  *  - multicast routing routes (array of struct mfcctl)
9471  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9472  *					One per ill plus one generic
9473  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9474  *					One per ill plus one generic
9475  *  - ipv6RouteEntry			all IPv6 IREs
9476  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9477  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9478  *  - ipv6AddrEntry			all IPv6 ipifs
9479  *  - ipv6 multicast membership (ipv6_member_t)
9480  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9481  *
9482  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9483  * already filled in by the caller.
9484  * Return value of 0 indicates that no messages were sent and caller
9485  * should free mpctl.
9486  */
9487 int
9488 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
9489 {
9490 	ip_stack_t *ipst;
9491 	sctp_stack_t *sctps;
9492 
9493 	if (q->q_next != NULL) {
9494 		ipst = ILLQ_TO_IPST(q);
9495 	} else {
9496 		ipst = CONNQ_TO_IPST(q);
9497 	}
9498 	ASSERT(ipst != NULL);
9499 	sctps = ipst->ips_netstack->netstack_sctp;
9500 
9501 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9502 		return (0);
9503 	}
9504 
9505 	/*
9506 	 * For the purposes of the (broken) packet shell use
9507 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9508 	 * to make TCP and UDP appear first in the list of mib items.
9509 	 * TBD: We could expand this and use it in netstat so that
9510 	 * the kernel doesn't have to produce large tables (connections,
9511 	 * routes, etc) when netstat only wants the statistics or a particular
9512 	 * table.
9513 	 */
9514 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9515 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9516 			return (1);
9517 		}
9518 	}
9519 
9520 	if (level != MIB2_TCP) {
9521 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
9522 			return (1);
9523 		}
9524 	}
9525 
9526 	if (level != MIB2_UDP) {
9527 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
9528 			return (1);
9529 		}
9530 	}
9531 
9532 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9533 	    ipst)) == NULL) {
9534 		return (1);
9535 	}
9536 
9537 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
9538 		return (1);
9539 	}
9540 
9541 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9542 		return (1);
9543 	}
9544 
9545 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9546 		return (1);
9547 	}
9548 
9549 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9550 		return (1);
9551 	}
9552 
9553 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9554 		return (1);
9555 	}
9556 
9557 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
9558 		return (1);
9559 	}
9560 
9561 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
9562 		return (1);
9563 	}
9564 
9565 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9566 		return (1);
9567 	}
9568 
9569 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9570 		return (1);
9571 	}
9572 
9573 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9574 		return (1);
9575 	}
9576 
9577 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9578 		return (1);
9579 	}
9580 
9581 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9582 		return (1);
9583 	}
9584 
9585 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9586 		return (1);
9587 	}
9588 
9589 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9590 	if (mpctl == NULL)
9591 		return (1);
9592 
9593 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9594 	if (mpctl == NULL)
9595 		return (1);
9596 
9597 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9598 		return (1);
9599 	}
9600 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9601 		return (1);
9602 	}
9603 	freemsg(mpctl);
9604 	return (1);
9605 }
9606 
9607 /* Get global (legacy) IPv4 statistics */
9608 static mblk_t *
9609 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9610     ip_stack_t *ipst)
9611 {
9612 	mib2_ip_t		old_ip_mib;
9613 	struct opthdr		*optp;
9614 	mblk_t			*mp2ctl;
9615 
9616 	/*
9617 	 * make a copy of the original message
9618 	 */
9619 	mp2ctl = copymsg(mpctl);
9620 
9621 	/* fixed length IP structure... */
9622 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9623 	optp->level = MIB2_IP;
9624 	optp->name = 0;
9625 	SET_MIB(old_ip_mib.ipForwarding,
9626 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9627 	SET_MIB(old_ip_mib.ipDefaultTTL,
9628 	    (uint32_t)ipst->ips_ip_def_ttl);
9629 	SET_MIB(old_ip_mib.ipReasmTimeout,
9630 	    ipst->ips_ip_reassembly_timeout);
9631 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9632 	    sizeof (mib2_ipAddrEntry_t));
9633 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9634 	    sizeof (mib2_ipRouteEntry_t));
9635 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9636 	    sizeof (mib2_ipNetToMediaEntry_t));
9637 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9638 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9639 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9640 	    sizeof (mib2_ipAttributeEntry_t));
9641 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9642 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9643 
9644 	/*
9645 	 * Grab the statistics from the new IP MIB
9646 	 */
9647 	SET_MIB(old_ip_mib.ipInReceives,
9648 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9649 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9650 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9651 	SET_MIB(old_ip_mib.ipForwDatagrams,
9652 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9653 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9654 	    ipmib->ipIfStatsInUnknownProtos);
9655 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9656 	SET_MIB(old_ip_mib.ipInDelivers,
9657 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9658 	SET_MIB(old_ip_mib.ipOutRequests,
9659 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9660 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9661 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9662 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9663 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9664 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9665 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9666 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9667 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9668 
9669 	/* ipRoutingDiscards is not being used */
9670 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9671 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9672 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9673 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9674 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9675 	    ipmib->ipIfStatsReasmDuplicates);
9676 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9677 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9678 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9679 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9680 	SET_MIB(old_ip_mib.rawipInOverflows,
9681 	    ipmib->rawipIfStatsInOverflows);
9682 
9683 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9684 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9685 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9686 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9687 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9688 	    ipmib->ipIfStatsOutSwitchIPVersion);
9689 
9690 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9691 	    (int)sizeof (old_ip_mib))) {
9692 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9693 		    (uint_t)sizeof (old_ip_mib)));
9694 	}
9695 
9696 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9697 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9698 	    (int)optp->level, (int)optp->name, (int)optp->len));
9699 	qreply(q, mpctl);
9700 	return (mp2ctl);
9701 }
9702 
9703 /* Per interface IPv4 statistics */
9704 static mblk_t *
9705 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9706 {
9707 	struct opthdr		*optp;
9708 	mblk_t			*mp2ctl;
9709 	ill_t			*ill;
9710 	ill_walk_context_t	ctx;
9711 	mblk_t			*mp_tail = NULL;
9712 	mib2_ipIfStatsEntry_t	global_ip_mib;
9713 
9714 	/*
9715 	 * Make a copy of the original message
9716 	 */
9717 	mp2ctl = copymsg(mpctl);
9718 
9719 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9720 	optp->level = MIB2_IP;
9721 	optp->name = MIB2_IP_TRAFFIC_STATS;
9722 	/* Include "unknown interface" ip_mib */
9723 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9724 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9725 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9726 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9727 	    (ipst->ips_ip_forwarding ? 1 : 2));
9728 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9729 	    (uint32_t)ipst->ips_ip_def_ttl);
9730 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9731 	    sizeof (mib2_ipIfStatsEntry_t));
9732 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9733 	    sizeof (mib2_ipAddrEntry_t));
9734 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9735 	    sizeof (mib2_ipRouteEntry_t));
9736 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9737 	    sizeof (mib2_ipNetToMediaEntry_t));
9738 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9739 	    sizeof (ip_member_t));
9740 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9741 	    sizeof (ip_grpsrc_t));
9742 
9743 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9744 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
9745 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9746 		    "failed to allocate %u bytes\n",
9747 		    (uint_t)sizeof (ipst->ips_ip_mib)));
9748 	}
9749 
9750 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9751 
9752 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9753 	ill = ILL_START_WALK_V4(&ctx, ipst);
9754 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9755 		ill->ill_ip_mib->ipIfStatsIfIndex =
9756 		    ill->ill_phyint->phyint_ifindex;
9757 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9758 		    (ipst->ips_ip_forwarding ? 1 : 2));
9759 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9760 		    (uint32_t)ipst->ips_ip_def_ttl);
9761 
9762 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9763 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9764 		    (char *)ill->ill_ip_mib,
9765 		    (int)sizeof (*ill->ill_ip_mib))) {
9766 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9767 			    "failed to allocate %u bytes\n",
9768 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9769 		}
9770 	}
9771 	rw_exit(&ipst->ips_ill_g_lock);
9772 
9773 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9774 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9775 	    "level %d, name %d, len %d\n",
9776 	    (int)optp->level, (int)optp->name, (int)optp->len));
9777 	qreply(q, mpctl);
9778 
9779 	if (mp2ctl == NULL)
9780 		return (NULL);
9781 
9782 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
9783 }
9784 
9785 /* Global IPv4 ICMP statistics */
9786 static mblk_t *
9787 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9788 {
9789 	struct opthdr		*optp;
9790 	mblk_t			*mp2ctl;
9791 
9792 	/*
9793 	 * Make a copy of the original message
9794 	 */
9795 	mp2ctl = copymsg(mpctl);
9796 
9797 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9798 	optp->level = MIB2_ICMP;
9799 	optp->name = 0;
9800 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9801 	    (int)sizeof (ipst->ips_icmp_mib))) {
9802 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9803 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9804 	}
9805 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9806 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9807 	    (int)optp->level, (int)optp->name, (int)optp->len));
9808 	qreply(q, mpctl);
9809 	return (mp2ctl);
9810 }
9811 
9812 /* Global IPv4 IGMP statistics */
9813 static mblk_t *
9814 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9815 {
9816 	struct opthdr		*optp;
9817 	mblk_t			*mp2ctl;
9818 
9819 	/*
9820 	 * make a copy of the original message
9821 	 */
9822 	mp2ctl = copymsg(mpctl);
9823 
9824 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9825 	optp->level = EXPER_IGMP;
9826 	optp->name = 0;
9827 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9828 	    (int)sizeof (ipst->ips_igmpstat))) {
9829 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9830 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9831 	}
9832 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9833 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9834 	    (int)optp->level, (int)optp->name, (int)optp->len));
9835 	qreply(q, mpctl);
9836 	return (mp2ctl);
9837 }
9838 
9839 /* Global IPv4 Multicast Routing statistics */
9840 static mblk_t *
9841 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9842 {
9843 	struct opthdr		*optp;
9844 	mblk_t			*mp2ctl;
9845 
9846 	/*
9847 	 * make a copy of the original message
9848 	 */
9849 	mp2ctl = copymsg(mpctl);
9850 
9851 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9852 	optp->level = EXPER_DVMRP;
9853 	optp->name = 0;
9854 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9855 		ip0dbg(("ip_mroute_stats: failed\n"));
9856 	}
9857 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9858 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9859 	    (int)optp->level, (int)optp->name, (int)optp->len));
9860 	qreply(q, mpctl);
9861 	return (mp2ctl);
9862 }
9863 
9864 /* IPv4 address information */
9865 static mblk_t *
9866 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9867 {
9868 	struct opthdr		*optp;
9869 	mblk_t			*mp2ctl;
9870 	mblk_t			*mp_tail = NULL;
9871 	ill_t			*ill;
9872 	ipif_t			*ipif;
9873 	uint_t			bitval;
9874 	mib2_ipAddrEntry_t	mae;
9875 	zoneid_t		zoneid;
9876 	ill_walk_context_t ctx;
9877 
9878 	/*
9879 	 * make a copy of the original message
9880 	 */
9881 	mp2ctl = copymsg(mpctl);
9882 
9883 	/* ipAddrEntryTable */
9884 
9885 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9886 	optp->level = MIB2_IP;
9887 	optp->name = MIB2_IP_ADDR;
9888 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9889 
9890 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9891 	ill = ILL_START_WALK_V4(&ctx, ipst);
9892 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9893 		for (ipif = ill->ill_ipif; ipif != NULL;
9894 		    ipif = ipif->ipif_next) {
9895 			if (ipif->ipif_zoneid != zoneid &&
9896 			    ipif->ipif_zoneid != ALL_ZONES)
9897 				continue;
9898 			/* Sum of count from dead IRE_LO* and our current */
9899 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9900 			if (ipif->ipif_ire_local != NULL) {
9901 				mae.ipAdEntInfo.ae_ibcnt +=
9902 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9903 			}
9904 			mae.ipAdEntInfo.ae_obcnt = 0;
9905 			mae.ipAdEntInfo.ae_focnt = 0;
9906 
9907 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
9908 			    OCTET_LENGTH);
9909 			mae.ipAdEntIfIndex.o_length =
9910 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
9911 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
9912 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
9913 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
9914 			mae.ipAdEntInfo.ae_subnet_len =
9915 			    ip_mask_to_plen(ipif->ipif_net_mask);
9916 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
9917 			for (bitval = 1;
9918 			    bitval &&
9919 			    !(bitval & ipif->ipif_brd_addr);
9920 			    bitval <<= 1)
9921 				noop;
9922 			mae.ipAdEntBcastAddr = bitval;
9923 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
9924 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
9925 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
9926 			mae.ipAdEntInfo.ae_broadcast_addr =
9927 			    ipif->ipif_brd_addr;
9928 			mae.ipAdEntInfo.ae_pp_dst_addr =
9929 			    ipif->ipif_pp_dst_addr;
9930 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
9931 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
9932 			mae.ipAdEntRetransmitTime =
9933 			    ill->ill_reachable_retrans_time;
9934 
9935 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9936 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
9937 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
9938 				    "allocate %u bytes\n",
9939 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
9940 			}
9941 		}
9942 	}
9943 	rw_exit(&ipst->ips_ill_g_lock);
9944 
9945 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9946 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
9947 	    (int)optp->level, (int)optp->name, (int)optp->len));
9948 	qreply(q, mpctl);
9949 	return (mp2ctl);
9950 }
9951 
9952 /* IPv6 address information */
9953 static mblk_t *
9954 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9955 {
9956 	struct opthdr		*optp;
9957 	mblk_t			*mp2ctl;
9958 	mblk_t			*mp_tail = NULL;
9959 	ill_t			*ill;
9960 	ipif_t			*ipif;
9961 	mib2_ipv6AddrEntry_t	mae6;
9962 	zoneid_t		zoneid;
9963 	ill_walk_context_t	ctx;
9964 
9965 	/*
9966 	 * make a copy of the original message
9967 	 */
9968 	mp2ctl = copymsg(mpctl);
9969 
9970 	/* ipv6AddrEntryTable */
9971 
9972 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9973 	optp->level = MIB2_IP6;
9974 	optp->name = MIB2_IP6_ADDR;
9975 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9976 
9977 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9978 	ill = ILL_START_WALK_V6(&ctx, ipst);
9979 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9980 		for (ipif = ill->ill_ipif; ipif != NULL;
9981 		    ipif = ipif->ipif_next) {
9982 			if (ipif->ipif_zoneid != zoneid &&
9983 			    ipif->ipif_zoneid != ALL_ZONES)
9984 				continue;
9985 			/* Sum of count from dead IRE_LO* and our current */
9986 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9987 			if (ipif->ipif_ire_local != NULL) {
9988 				mae6.ipv6AddrInfo.ae_ibcnt +=
9989 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9990 			}
9991 			mae6.ipv6AddrInfo.ae_obcnt = 0;
9992 			mae6.ipv6AddrInfo.ae_focnt = 0;
9993 
9994 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
9995 			    OCTET_LENGTH);
9996 			mae6.ipv6AddrIfIndex.o_length =
9997 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
9998 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
9999 			mae6.ipv6AddrPfxLength =
10000 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10001 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10002 			mae6.ipv6AddrInfo.ae_subnet_len =
10003 			    mae6.ipv6AddrPfxLength;
10004 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10005 
10006 			/* Type: stateless(1), stateful(2), unknown(3) */
10007 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10008 				mae6.ipv6AddrType = 1;
10009 			else
10010 				mae6.ipv6AddrType = 2;
10011 			/* Anycast: true(1), false(2) */
10012 			if (ipif->ipif_flags & IPIF_ANYCAST)
10013 				mae6.ipv6AddrAnycastFlag = 1;
10014 			else
10015 				mae6.ipv6AddrAnycastFlag = 2;
10016 
10017 			/*
10018 			 * Address status: preferred(1), deprecated(2),
10019 			 * invalid(3), inaccessible(4), unknown(5)
10020 			 */
10021 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10022 				mae6.ipv6AddrStatus = 3;
10023 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10024 				mae6.ipv6AddrStatus = 2;
10025 			else
10026 				mae6.ipv6AddrStatus = 1;
10027 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10028 			mae6.ipv6AddrInfo.ae_metric  =
10029 			    ipif->ipif_ill->ill_metric;
10030 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10031 			    ipif->ipif_v6pp_dst_addr;
10032 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10033 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10034 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10035 			mae6.ipv6AddrIdentifier = ill->ill_token;
10036 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10037 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10038 			mae6.ipv6AddrRetransmitTime =
10039 			    ill->ill_reachable_retrans_time;
10040 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10041 			    (char *)&mae6,
10042 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
10043 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10044 				    "allocate %u bytes\n",
10045 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
10046 			}
10047 		}
10048 	}
10049 	rw_exit(&ipst->ips_ill_g_lock);
10050 
10051 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10052 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10053 	    (int)optp->level, (int)optp->name, (int)optp->len));
10054 	qreply(q, mpctl);
10055 	return (mp2ctl);
10056 }
10057 
10058 /* IPv4 multicast group membership. */
10059 static mblk_t *
10060 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10061 {
10062 	struct opthdr		*optp;
10063 	mblk_t			*mp2ctl;
10064 	ill_t			*ill;
10065 	ipif_t			*ipif;
10066 	ilm_t			*ilm;
10067 	ip_member_t		ipm;
10068 	mblk_t			*mp_tail = NULL;
10069 	ill_walk_context_t	ctx;
10070 	zoneid_t		zoneid;
10071 
10072 	/*
10073 	 * make a copy of the original message
10074 	 */
10075 	mp2ctl = copymsg(mpctl);
10076 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10077 
10078 	/* ipGroupMember table */
10079 	optp = (struct opthdr *)&mpctl->b_rptr[
10080 	    sizeof (struct T_optmgmt_ack)];
10081 	optp->level = MIB2_IP;
10082 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10083 
10084 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10085 	ill = ILL_START_WALK_V4(&ctx, ipst);
10086 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10087 		/* Make sure the ill isn't going away. */
10088 		if (!ill_check_and_refhold(ill))
10089 			continue;
10090 		rw_exit(&ipst->ips_ill_g_lock);
10091 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10092 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10093 			if (ilm->ilm_zoneid != zoneid &&
10094 			    ilm->ilm_zoneid != ALL_ZONES)
10095 				continue;
10096 
10097 			/* Is there an ipif for ilm_ifaddr? */
10098 			for (ipif = ill->ill_ipif; ipif != NULL;
10099 			    ipif = ipif->ipif_next) {
10100 				if (!IPIF_IS_CONDEMNED(ipif) &&
10101 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10102 				    ilm->ilm_ifaddr != INADDR_ANY)
10103 					break;
10104 			}
10105 			if (ipif != NULL) {
10106 				ipif_get_name(ipif,
10107 				    ipm.ipGroupMemberIfIndex.o_bytes,
10108 				    OCTET_LENGTH);
10109 			} else {
10110 				ill_get_name(ill,
10111 				    ipm.ipGroupMemberIfIndex.o_bytes,
10112 				    OCTET_LENGTH);
10113 			}
10114 			ipm.ipGroupMemberIfIndex.o_length =
10115 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10116 
10117 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10118 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10119 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10120 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10121 			    (char *)&ipm, (int)sizeof (ipm))) {
10122 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10123 				    "failed to allocate %u bytes\n",
10124 				    (uint_t)sizeof (ipm)));
10125 			}
10126 		}
10127 		rw_exit(&ill->ill_mcast_lock);
10128 		ill_refrele(ill);
10129 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10130 	}
10131 	rw_exit(&ipst->ips_ill_g_lock);
10132 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10133 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10134 	    (int)optp->level, (int)optp->name, (int)optp->len));
10135 	qreply(q, mpctl);
10136 	return (mp2ctl);
10137 }
10138 
10139 /* IPv6 multicast group membership. */
10140 static mblk_t *
10141 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10142 {
10143 	struct opthdr		*optp;
10144 	mblk_t			*mp2ctl;
10145 	ill_t			*ill;
10146 	ilm_t			*ilm;
10147 	ipv6_member_t		ipm6;
10148 	mblk_t			*mp_tail = NULL;
10149 	ill_walk_context_t	ctx;
10150 	zoneid_t		zoneid;
10151 
10152 	/*
10153 	 * make a copy of the original message
10154 	 */
10155 	mp2ctl = copymsg(mpctl);
10156 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10157 
10158 	/* ip6GroupMember table */
10159 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10160 	optp->level = MIB2_IP6;
10161 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10162 
10163 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10164 	ill = ILL_START_WALK_V6(&ctx, ipst);
10165 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10166 		/* Make sure the ill isn't going away. */
10167 		if (!ill_check_and_refhold(ill))
10168 			continue;
10169 		rw_exit(&ipst->ips_ill_g_lock);
10170 		/*
10171 		 * Normally we don't have any members on under IPMP interfaces.
10172 		 * We report them as a debugging aid.
10173 		 */
10174 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10175 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10176 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10177 			if (ilm->ilm_zoneid != zoneid &&
10178 			    ilm->ilm_zoneid != ALL_ZONES)
10179 				continue;	/* not this zone */
10180 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10181 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10182 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10183 			if (!snmp_append_data2(mpctl->b_cont,
10184 			    &mp_tail,
10185 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10186 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10187 				    "failed to allocate %u bytes\n",
10188 				    (uint_t)sizeof (ipm6)));
10189 			}
10190 		}
10191 		rw_exit(&ill->ill_mcast_lock);
10192 		ill_refrele(ill);
10193 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10194 	}
10195 	rw_exit(&ipst->ips_ill_g_lock);
10196 
10197 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10198 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10199 	    (int)optp->level, (int)optp->name, (int)optp->len));
10200 	qreply(q, mpctl);
10201 	return (mp2ctl);
10202 }
10203 
10204 /* IP multicast filtered sources */
10205 static mblk_t *
10206 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10207 {
10208 	struct opthdr		*optp;
10209 	mblk_t			*mp2ctl;
10210 	ill_t			*ill;
10211 	ipif_t			*ipif;
10212 	ilm_t			*ilm;
10213 	ip_grpsrc_t		ips;
10214 	mblk_t			*mp_tail = NULL;
10215 	ill_walk_context_t	ctx;
10216 	zoneid_t		zoneid;
10217 	int			i;
10218 	slist_t			*sl;
10219 
10220 	/*
10221 	 * make a copy of the original message
10222 	 */
10223 	mp2ctl = copymsg(mpctl);
10224 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10225 
10226 	/* ipGroupSource table */
10227 	optp = (struct opthdr *)&mpctl->b_rptr[
10228 	    sizeof (struct T_optmgmt_ack)];
10229 	optp->level = MIB2_IP;
10230 	optp->name = EXPER_IP_GROUP_SOURCES;
10231 
10232 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10233 	ill = ILL_START_WALK_V4(&ctx, ipst);
10234 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10235 		/* Make sure the ill isn't going away. */
10236 		if (!ill_check_and_refhold(ill))
10237 			continue;
10238 		rw_exit(&ipst->ips_ill_g_lock);
10239 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10240 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10241 			sl = ilm->ilm_filter;
10242 			if (ilm->ilm_zoneid != zoneid &&
10243 			    ilm->ilm_zoneid != ALL_ZONES)
10244 				continue;
10245 			if (SLIST_IS_EMPTY(sl))
10246 				continue;
10247 
10248 			/* Is there an ipif for ilm_ifaddr? */
10249 			for (ipif = ill->ill_ipif; ipif != NULL;
10250 			    ipif = ipif->ipif_next) {
10251 				if (!IPIF_IS_CONDEMNED(ipif) &&
10252 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10253 				    ilm->ilm_ifaddr != INADDR_ANY)
10254 					break;
10255 			}
10256 			if (ipif != NULL) {
10257 				ipif_get_name(ipif,
10258 				    ips.ipGroupSourceIfIndex.o_bytes,
10259 				    OCTET_LENGTH);
10260 			} else {
10261 				ill_get_name(ill,
10262 				    ips.ipGroupSourceIfIndex.o_bytes,
10263 				    OCTET_LENGTH);
10264 			}
10265 			ips.ipGroupSourceIfIndex.o_length =
10266 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10267 
10268 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10269 			for (i = 0; i < sl->sl_numsrc; i++) {
10270 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10271 					continue;
10272 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10273 				    ips.ipGroupSourceAddress);
10274 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10275 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10276 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10277 					    " failed to allocate %u bytes\n",
10278 					    (uint_t)sizeof (ips)));
10279 				}
10280 			}
10281 		}
10282 		rw_exit(&ill->ill_mcast_lock);
10283 		ill_refrele(ill);
10284 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10285 	}
10286 	rw_exit(&ipst->ips_ill_g_lock);
10287 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10288 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10289 	    (int)optp->level, (int)optp->name, (int)optp->len));
10290 	qreply(q, mpctl);
10291 	return (mp2ctl);
10292 }
10293 
10294 /* IPv6 multicast filtered sources. */
10295 static mblk_t *
10296 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10297 {
10298 	struct opthdr		*optp;
10299 	mblk_t			*mp2ctl;
10300 	ill_t			*ill;
10301 	ilm_t			*ilm;
10302 	ipv6_grpsrc_t		ips6;
10303 	mblk_t			*mp_tail = NULL;
10304 	ill_walk_context_t	ctx;
10305 	zoneid_t		zoneid;
10306 	int			i;
10307 	slist_t			*sl;
10308 
10309 	/*
10310 	 * make a copy of the original message
10311 	 */
10312 	mp2ctl = copymsg(mpctl);
10313 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10314 
10315 	/* ip6GroupMember table */
10316 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10317 	optp->level = MIB2_IP6;
10318 	optp->name = EXPER_IP6_GROUP_SOURCES;
10319 
10320 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10321 	ill = ILL_START_WALK_V6(&ctx, ipst);
10322 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10323 		/* Make sure the ill isn't going away. */
10324 		if (!ill_check_and_refhold(ill))
10325 			continue;
10326 		rw_exit(&ipst->ips_ill_g_lock);
10327 		/*
10328 		 * Normally we don't have any members on under IPMP interfaces.
10329 		 * We report them as a debugging aid.
10330 		 */
10331 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10332 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10333 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10334 			sl = ilm->ilm_filter;
10335 			if (ilm->ilm_zoneid != zoneid &&
10336 			    ilm->ilm_zoneid != ALL_ZONES)
10337 				continue;
10338 			if (SLIST_IS_EMPTY(sl))
10339 				continue;
10340 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10341 			for (i = 0; i < sl->sl_numsrc; i++) {
10342 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10343 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10344 				    (char *)&ips6, (int)sizeof (ips6))) {
10345 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10346 					    "group_src: failed to allocate "
10347 					    "%u bytes\n",
10348 					    (uint_t)sizeof (ips6)));
10349 				}
10350 			}
10351 		}
10352 		rw_exit(&ill->ill_mcast_lock);
10353 		ill_refrele(ill);
10354 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10355 	}
10356 	rw_exit(&ipst->ips_ill_g_lock);
10357 
10358 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10359 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10360 	    (int)optp->level, (int)optp->name, (int)optp->len));
10361 	qreply(q, mpctl);
10362 	return (mp2ctl);
10363 }
10364 
10365 /* Multicast routing virtual interface table. */
10366 static mblk_t *
10367 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10368 {
10369 	struct opthdr		*optp;
10370 	mblk_t			*mp2ctl;
10371 
10372 	/*
10373 	 * make a copy of the original message
10374 	 */
10375 	mp2ctl = copymsg(mpctl);
10376 
10377 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10378 	optp->level = EXPER_DVMRP;
10379 	optp->name = EXPER_DVMRP_VIF;
10380 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10381 		ip0dbg(("ip_mroute_vif: failed\n"));
10382 	}
10383 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10384 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10385 	    (int)optp->level, (int)optp->name, (int)optp->len));
10386 	qreply(q, mpctl);
10387 	return (mp2ctl);
10388 }
10389 
10390 /* Multicast routing table. */
10391 static mblk_t *
10392 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10393 {
10394 	struct opthdr		*optp;
10395 	mblk_t			*mp2ctl;
10396 
10397 	/*
10398 	 * make a copy of the original message
10399 	 */
10400 	mp2ctl = copymsg(mpctl);
10401 
10402 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10403 	optp->level = EXPER_DVMRP;
10404 	optp->name = EXPER_DVMRP_MRT;
10405 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10406 		ip0dbg(("ip_mroute_mrt: failed\n"));
10407 	}
10408 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10409 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10410 	    (int)optp->level, (int)optp->name, (int)optp->len));
10411 	qreply(q, mpctl);
10412 	return (mp2ctl);
10413 }
10414 
10415 /*
10416  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10417  * in one IRE walk.
10418  */
10419 static mblk_t *
10420 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10421     ip_stack_t *ipst)
10422 {
10423 	struct opthdr	*optp;
10424 	mblk_t		*mp2ctl;	/* Returned */
10425 	mblk_t		*mp3ctl;	/* nettomedia */
10426 	mblk_t		*mp4ctl;	/* routeattrs */
10427 	iproutedata_t	ird;
10428 	zoneid_t	zoneid;
10429 
10430 	/*
10431 	 * make copies of the original message
10432 	 *	- mp2ctl is returned unchanged to the caller for his use
10433 	 *	- mpctl is sent upstream as ipRouteEntryTable
10434 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10435 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10436 	 */
10437 	mp2ctl = copymsg(mpctl);
10438 	mp3ctl = copymsg(mpctl);
10439 	mp4ctl = copymsg(mpctl);
10440 	if (mp3ctl == NULL || mp4ctl == NULL) {
10441 		freemsg(mp4ctl);
10442 		freemsg(mp3ctl);
10443 		freemsg(mp2ctl);
10444 		freemsg(mpctl);
10445 		return (NULL);
10446 	}
10447 
10448 	bzero(&ird, sizeof (ird));
10449 
10450 	ird.ird_route.lp_head = mpctl->b_cont;
10451 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10452 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10453 	/*
10454 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10455 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10456 	 * intended a temporary solution until a proper MIB API is provided
10457 	 * that provides complete filtering/caller-opt-in.
10458 	 */
10459 	if (level == EXPER_IP_AND_ALL_IRES)
10460 		ird.ird_flags |= IRD_REPORT_ALL;
10461 
10462 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10463 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10464 
10465 	/* ipRouteEntryTable in mpctl */
10466 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10467 	optp->level = MIB2_IP;
10468 	optp->name = MIB2_IP_ROUTE;
10469 	optp->len = msgdsize(ird.ird_route.lp_head);
10470 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10471 	    (int)optp->level, (int)optp->name, (int)optp->len));
10472 	qreply(q, mpctl);
10473 
10474 	/* ipNetToMediaEntryTable in mp3ctl */
10475 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10476 
10477 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10478 	optp->level = MIB2_IP;
10479 	optp->name = MIB2_IP_MEDIA;
10480 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10481 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10482 	    (int)optp->level, (int)optp->name, (int)optp->len));
10483 	qreply(q, mp3ctl);
10484 
10485 	/* ipRouteAttributeTable in mp4ctl */
10486 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10487 	optp->level = MIB2_IP;
10488 	optp->name = EXPER_IP_RTATTR;
10489 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10490 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10491 	    (int)optp->level, (int)optp->name, (int)optp->len));
10492 	if (optp->len == 0)
10493 		freemsg(mp4ctl);
10494 	else
10495 		qreply(q, mp4ctl);
10496 
10497 	return (mp2ctl);
10498 }
10499 
10500 /*
10501  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10502  * ipv6NetToMediaEntryTable in an NDP walk.
10503  */
10504 static mblk_t *
10505 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10506     ip_stack_t *ipst)
10507 {
10508 	struct opthdr	*optp;
10509 	mblk_t		*mp2ctl;	/* Returned */
10510 	mblk_t		*mp3ctl;	/* nettomedia */
10511 	mblk_t		*mp4ctl;	/* routeattrs */
10512 	iproutedata_t	ird;
10513 	zoneid_t	zoneid;
10514 
10515 	/*
10516 	 * make copies of the original message
10517 	 *	- mp2ctl is returned unchanged to the caller for his use
10518 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10519 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10520 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10521 	 */
10522 	mp2ctl = copymsg(mpctl);
10523 	mp3ctl = copymsg(mpctl);
10524 	mp4ctl = copymsg(mpctl);
10525 	if (mp3ctl == NULL || mp4ctl == NULL) {
10526 		freemsg(mp4ctl);
10527 		freemsg(mp3ctl);
10528 		freemsg(mp2ctl);
10529 		freemsg(mpctl);
10530 		return (NULL);
10531 	}
10532 
10533 	bzero(&ird, sizeof (ird));
10534 
10535 	ird.ird_route.lp_head = mpctl->b_cont;
10536 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10537 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10538 	/*
10539 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10540 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10541 	 * intended a temporary solution until a proper MIB API is provided
10542 	 * that provides complete filtering/caller-opt-in.
10543 	 */
10544 	if (level == EXPER_IP_AND_ALL_IRES)
10545 		ird.ird_flags |= IRD_REPORT_ALL;
10546 
10547 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10548 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10549 
10550 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10551 	optp->level = MIB2_IP6;
10552 	optp->name = MIB2_IP6_ROUTE;
10553 	optp->len = msgdsize(ird.ird_route.lp_head);
10554 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10555 	    (int)optp->level, (int)optp->name, (int)optp->len));
10556 	qreply(q, mpctl);
10557 
10558 	/* ipv6NetToMediaEntryTable in mp3ctl */
10559 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10560 
10561 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10562 	optp->level = MIB2_IP6;
10563 	optp->name = MIB2_IP6_MEDIA;
10564 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10565 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10566 	    (int)optp->level, (int)optp->name, (int)optp->len));
10567 	qreply(q, mp3ctl);
10568 
10569 	/* ipv6RouteAttributeTable in mp4ctl */
10570 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10571 	optp->level = MIB2_IP6;
10572 	optp->name = EXPER_IP_RTATTR;
10573 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10574 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10575 	    (int)optp->level, (int)optp->name, (int)optp->len));
10576 	if (optp->len == 0)
10577 		freemsg(mp4ctl);
10578 	else
10579 		qreply(q, mp4ctl);
10580 
10581 	return (mp2ctl);
10582 }
10583 
10584 /*
10585  * IPv6 mib: One per ill
10586  */
10587 static mblk_t *
10588 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10589 {
10590 	struct opthdr		*optp;
10591 	mblk_t			*mp2ctl;
10592 	ill_t			*ill;
10593 	ill_walk_context_t	ctx;
10594 	mblk_t			*mp_tail = NULL;
10595 
10596 	/*
10597 	 * Make a copy of the original message
10598 	 */
10599 	mp2ctl = copymsg(mpctl);
10600 
10601 	/* fixed length IPv6 structure ... */
10602 
10603 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10604 	optp->level = MIB2_IP6;
10605 	optp->name = 0;
10606 	/* Include "unknown interface" ip6_mib */
10607 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10608 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10609 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10610 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10611 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10612 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10613 	    ipst->ips_ipv6_def_hops);
10614 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10615 	    sizeof (mib2_ipIfStatsEntry_t));
10616 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10617 	    sizeof (mib2_ipv6AddrEntry_t));
10618 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10619 	    sizeof (mib2_ipv6RouteEntry_t));
10620 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10621 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10622 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10623 	    sizeof (ipv6_member_t));
10624 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10625 	    sizeof (ipv6_grpsrc_t));
10626 
10627 	/*
10628 	 * Synchronize 64- and 32-bit counters
10629 	 */
10630 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10631 	    ipIfStatsHCInReceives);
10632 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10633 	    ipIfStatsHCInDelivers);
10634 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10635 	    ipIfStatsHCOutRequests);
10636 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10637 	    ipIfStatsHCOutForwDatagrams);
10638 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10639 	    ipIfStatsHCOutMcastPkts);
10640 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10641 	    ipIfStatsHCInMcastPkts);
10642 
10643 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10644 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
10645 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10646 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
10647 	}
10648 
10649 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10650 	ill = ILL_START_WALK_V6(&ctx, ipst);
10651 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10652 		ill->ill_ip_mib->ipIfStatsIfIndex =
10653 		    ill->ill_phyint->phyint_ifindex;
10654 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10655 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10656 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10657 		    ill->ill_max_hops);
10658 
10659 		/*
10660 		 * Synchronize 64- and 32-bit counters
10661 		 */
10662 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10663 		    ipIfStatsHCInReceives);
10664 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10665 		    ipIfStatsHCInDelivers);
10666 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10667 		    ipIfStatsHCOutRequests);
10668 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10669 		    ipIfStatsHCOutForwDatagrams);
10670 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10671 		    ipIfStatsHCOutMcastPkts);
10672 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10673 		    ipIfStatsHCInMcastPkts);
10674 
10675 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10676 		    (char *)ill->ill_ip_mib,
10677 		    (int)sizeof (*ill->ill_ip_mib))) {
10678 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10679 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
10680 		}
10681 	}
10682 	rw_exit(&ipst->ips_ill_g_lock);
10683 
10684 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10685 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10686 	    (int)optp->level, (int)optp->name, (int)optp->len));
10687 	qreply(q, mpctl);
10688 	return (mp2ctl);
10689 }
10690 
10691 /*
10692  * ICMPv6 mib: One per ill
10693  */
10694 static mblk_t *
10695 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10696 {
10697 	struct opthdr		*optp;
10698 	mblk_t			*mp2ctl;
10699 	ill_t			*ill;
10700 	ill_walk_context_t	ctx;
10701 	mblk_t			*mp_tail = NULL;
10702 	/*
10703 	 * Make a copy of the original message
10704 	 */
10705 	mp2ctl = copymsg(mpctl);
10706 
10707 	/* fixed length ICMPv6 structure ... */
10708 
10709 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10710 	optp->level = MIB2_ICMP6;
10711 	optp->name = 0;
10712 	/* Include "unknown interface" icmp6_mib */
10713 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10714 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10715 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10716 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10717 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10718 	    (char *)&ipst->ips_icmp6_mib,
10719 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10720 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10721 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10722 	}
10723 
10724 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10725 	ill = ILL_START_WALK_V6(&ctx, ipst);
10726 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10727 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10728 		    ill->ill_phyint->phyint_ifindex;
10729 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10730 		    (char *)ill->ill_icmp6_mib,
10731 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10732 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10733 			    "%u bytes\n",
10734 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10735 		}
10736 	}
10737 	rw_exit(&ipst->ips_ill_g_lock);
10738 
10739 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10740 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10741 	    (int)optp->level, (int)optp->name, (int)optp->len));
10742 	qreply(q, mpctl);
10743 	return (mp2ctl);
10744 }
10745 
10746 /*
10747  * ire_walk routine to create both ipRouteEntryTable and
10748  * ipRouteAttributeTable in one IRE walk
10749  */
10750 static void
10751 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10752 {
10753 	ill_t				*ill;
10754 	mib2_ipRouteEntry_t		*re;
10755 	mib2_ipAttributeEntry_t		iaes;
10756 	tsol_ire_gw_secattr_t		*attrp;
10757 	tsol_gc_t			*gc = NULL;
10758 	tsol_gcgrp_t			*gcgrp = NULL;
10759 	ip_stack_t			*ipst = ire->ire_ipst;
10760 
10761 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10762 
10763 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10764 		if (ire->ire_testhidden)
10765 			return;
10766 		if (ire->ire_type & IRE_IF_CLONE)
10767 			return;
10768 	}
10769 
10770 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10771 		return;
10772 
10773 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10774 		mutex_enter(&attrp->igsa_lock);
10775 		if ((gc = attrp->igsa_gc) != NULL) {
10776 			gcgrp = gc->gc_grp;
10777 			ASSERT(gcgrp != NULL);
10778 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10779 		}
10780 		mutex_exit(&attrp->igsa_lock);
10781 	}
10782 	/*
10783 	 * Return all IRE types for route table... let caller pick and choose
10784 	 */
10785 	re->ipRouteDest = ire->ire_addr;
10786 	ill = ire->ire_ill;
10787 	re->ipRouteIfIndex.o_length = 0;
10788 	if (ill != NULL) {
10789 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10790 		re->ipRouteIfIndex.o_length =
10791 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10792 	}
10793 	re->ipRouteMetric1 = -1;
10794 	re->ipRouteMetric2 = -1;
10795 	re->ipRouteMetric3 = -1;
10796 	re->ipRouteMetric4 = -1;
10797 
10798 	re->ipRouteNextHop = ire->ire_gateway_addr;
10799 	/* indirect(4), direct(3), or invalid(2) */
10800 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10801 		re->ipRouteType = 2;
10802 	else if (ire->ire_type & IRE_ONLINK)
10803 		re->ipRouteType = 3;
10804 	else
10805 		re->ipRouteType = 4;
10806 
10807 	re->ipRouteProto = -1;
10808 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10809 	re->ipRouteMask = ire->ire_mask;
10810 	re->ipRouteMetric5 = -1;
10811 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10812 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10813 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10814 
10815 	re->ipRouteInfo.re_frag_flag	= 0;
10816 	re->ipRouteInfo.re_rtt		= 0;
10817 	re->ipRouteInfo.re_src_addr	= 0;
10818 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
10819 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10820 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10821 	re->ipRouteInfo.re_flags	= ire->ire_flags;
10822 
10823 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10824 	if (ire->ire_type & IRE_INTERFACE) {
10825 		ire_t *child;
10826 
10827 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10828 		child = ire->ire_dep_children;
10829 		while (child != NULL) {
10830 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10831 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10832 			child = child->ire_dep_sib_next;
10833 		}
10834 		rw_exit(&ipst->ips_ire_dep_lock);
10835 	}
10836 
10837 	if (ire->ire_flags & RTF_DYNAMIC) {
10838 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10839 	} else {
10840 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
10841 	}
10842 
10843 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10844 	    (char *)re, (int)sizeof (*re))) {
10845 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
10846 		    (uint_t)sizeof (*re)));
10847 	}
10848 
10849 	if (gc != NULL) {
10850 		iaes.iae_routeidx = ird->ird_idx;
10851 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10852 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10853 
10854 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10855 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10856 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
10857 			    "bytes\n", (uint_t)sizeof (iaes)));
10858 		}
10859 	}
10860 
10861 	/* bump route index for next pass */
10862 	ird->ird_idx++;
10863 
10864 	kmem_free(re, sizeof (*re));
10865 	if (gcgrp != NULL)
10866 		rw_exit(&gcgrp->gcgrp_rwlock);
10867 }
10868 
10869 /*
10870  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
10871  */
10872 static void
10873 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
10874 {
10875 	ill_t				*ill;
10876 	mib2_ipv6RouteEntry_t		*re;
10877 	mib2_ipAttributeEntry_t		iaes;
10878 	tsol_ire_gw_secattr_t		*attrp;
10879 	tsol_gc_t			*gc = NULL;
10880 	tsol_gcgrp_t			*gcgrp = NULL;
10881 	ip_stack_t			*ipst = ire->ire_ipst;
10882 
10883 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
10884 
10885 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10886 		if (ire->ire_testhidden)
10887 			return;
10888 		if (ire->ire_type & IRE_IF_CLONE)
10889 			return;
10890 	}
10891 
10892 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10893 		return;
10894 
10895 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10896 		mutex_enter(&attrp->igsa_lock);
10897 		if ((gc = attrp->igsa_gc) != NULL) {
10898 			gcgrp = gc->gc_grp;
10899 			ASSERT(gcgrp != NULL);
10900 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10901 		}
10902 		mutex_exit(&attrp->igsa_lock);
10903 	}
10904 	/*
10905 	 * Return all IRE types for route table... let caller pick and choose
10906 	 */
10907 	re->ipv6RouteDest = ire->ire_addr_v6;
10908 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
10909 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
10910 	re->ipv6RouteIfIndex.o_length = 0;
10911 	ill = ire->ire_ill;
10912 	if (ill != NULL) {
10913 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
10914 		re->ipv6RouteIfIndex.o_length =
10915 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
10916 	}
10917 
10918 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
10919 
10920 	mutex_enter(&ire->ire_lock);
10921 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
10922 	mutex_exit(&ire->ire_lock);
10923 
10924 	/* remote(4), local(3), or discard(2) */
10925 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10926 		re->ipv6RouteType = 2;
10927 	else if (ire->ire_type & IRE_ONLINK)
10928 		re->ipv6RouteType = 3;
10929 	else
10930 		re->ipv6RouteType = 4;
10931 
10932 	re->ipv6RouteProtocol	= -1;
10933 	re->ipv6RoutePolicy	= 0;
10934 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
10935 	re->ipv6RouteNextHopRDI	= 0;
10936 	re->ipv6RouteWeight	= 0;
10937 	re->ipv6RouteMetric	= 0;
10938 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10939 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
10940 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10941 
10942 	re->ipv6RouteInfo.re_frag_flag	= 0;
10943 	re->ipv6RouteInfo.re_rtt	= 0;
10944 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
10945 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10946 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10947 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
10948 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
10949 
10950 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10951 	if (ire->ire_type & IRE_INTERFACE) {
10952 		ire_t *child;
10953 
10954 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10955 		child = ire->ire_dep_children;
10956 		while (child != NULL) {
10957 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
10958 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10959 			child = child->ire_dep_sib_next;
10960 		}
10961 		rw_exit(&ipst->ips_ire_dep_lock);
10962 	}
10963 	if (ire->ire_flags & RTF_DYNAMIC) {
10964 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10965 	} else {
10966 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
10967 	}
10968 
10969 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10970 	    (char *)re, (int)sizeof (*re))) {
10971 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
10972 		    (uint_t)sizeof (*re)));
10973 	}
10974 
10975 	if (gc != NULL) {
10976 		iaes.iae_routeidx = ird->ird_idx;
10977 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10978 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10979 
10980 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10981 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10982 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
10983 			    "bytes\n", (uint_t)sizeof (iaes)));
10984 		}
10985 	}
10986 
10987 	/* bump route index for next pass */
10988 	ird->ird_idx++;
10989 
10990 	kmem_free(re, sizeof (*re));
10991 	if (gcgrp != NULL)
10992 		rw_exit(&gcgrp->gcgrp_rwlock);
10993 }
10994 
10995 /*
10996  * ncec_walk routine to create ipv6NetToMediaEntryTable
10997  */
10998 static int
10999 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11000 {
11001 	ill_t				*ill;
11002 	mib2_ipv6NetToMediaEntry_t	ntme;
11003 
11004 	ill = ncec->ncec_ill;
11005 	/* skip arpce entries, and loopback ncec entries */
11006 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11007 		return (0);
11008 	/*
11009 	 * Neighbor cache entry attached to IRE with on-link
11010 	 * destination.
11011 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11012 	 */
11013 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11014 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11015 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11016 	if (ncec->ncec_lladdr != NULL) {
11017 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11018 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11019 	}
11020 	/*
11021 	 * Note: Returns ND_* states. Should be:
11022 	 * reachable(1), stale(2), delay(3), probe(4),
11023 	 * invalid(5), unknown(6)
11024 	 */
11025 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11026 	ntme.ipv6NetToMediaLastUpdated = 0;
11027 
11028 	/* other(1), dynamic(2), static(3), local(4) */
11029 	if (NCE_MYADDR(ncec)) {
11030 		ntme.ipv6NetToMediaType = 4;
11031 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11032 		ntme.ipv6NetToMediaType = 1; /* proxy */
11033 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11034 		ntme.ipv6NetToMediaType = 3;
11035 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11036 		ntme.ipv6NetToMediaType = 1;
11037 	} else {
11038 		ntme.ipv6NetToMediaType = 2;
11039 	}
11040 
11041 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11042 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11043 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11044 		    (uint_t)sizeof (ntme)));
11045 	}
11046 	return (0);
11047 }
11048 
11049 int
11050 nce2ace(ncec_t *ncec)
11051 {
11052 	int flags = 0;
11053 
11054 	if (NCE_ISREACHABLE(ncec))
11055 		flags |= ACE_F_RESOLVED;
11056 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11057 		flags |= ACE_F_AUTHORITY;
11058 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11059 		flags |= ACE_F_PUBLISH;
11060 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11061 		flags |= ACE_F_PERMANENT;
11062 	if (NCE_MYADDR(ncec))
11063 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11064 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11065 		flags |= ACE_F_UNVERIFIED;
11066 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11067 		flags |= ACE_F_AUTHORITY;
11068 	if (ncec->ncec_flags & NCE_F_DELAYED)
11069 		flags |= ACE_F_DELAYED;
11070 	return (flags);
11071 }
11072 
11073 /*
11074  * ncec_walk routine to create ipNetToMediaEntryTable
11075  */
11076 static int
11077 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11078 {
11079 	ill_t				*ill;
11080 	mib2_ipNetToMediaEntry_t	ntme;
11081 	const char			*name = "unknown";
11082 	ipaddr_t			ncec_addr;
11083 
11084 	ill = ncec->ncec_ill;
11085 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11086 	    ill->ill_net_type == IRE_LOOPBACK)
11087 		return (0);
11088 
11089 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11090 	name = ill->ill_name;
11091 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11092 	if (NCE_MYADDR(ncec)) {
11093 		ntme.ipNetToMediaType = 4;
11094 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11095 		ntme.ipNetToMediaType = 1;
11096 	} else {
11097 		ntme.ipNetToMediaType = 3;
11098 	}
11099 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11100 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11101 	    ntme.ipNetToMediaIfIndex.o_length);
11102 
11103 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11104 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11105 
11106 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11107 	ncec_addr = INADDR_BROADCAST;
11108 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11109 	    sizeof (ncec_addr));
11110 	/*
11111 	 * map all the flags to the ACE counterpart.
11112 	 */
11113 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11114 
11115 	ntme.ipNetToMediaPhysAddress.o_length =
11116 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11117 
11118 	if (!NCE_ISREACHABLE(ncec))
11119 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11120 	else {
11121 		if (ncec->ncec_lladdr != NULL) {
11122 			bcopy(ncec->ncec_lladdr,
11123 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11124 			    ntme.ipNetToMediaPhysAddress.o_length);
11125 		}
11126 	}
11127 
11128 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11129 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11130 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11131 		    (uint_t)sizeof (ntme)));
11132 	}
11133 	return (0);
11134 }
11135 
11136 /*
11137  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11138  */
11139 /* ARGSUSED */
11140 int
11141 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11142 {
11143 	switch (level) {
11144 	case MIB2_IP:
11145 	case MIB2_ICMP:
11146 		switch (name) {
11147 		default:
11148 			break;
11149 		}
11150 		return (1);
11151 	default:
11152 		return (1);
11153 	}
11154 }
11155 
11156 /*
11157  * When there exists both a 64- and 32-bit counter of a particular type
11158  * (i.e., InReceives), only the 64-bit counters are added.
11159  */
11160 void
11161 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11162 {
11163 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11164 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11165 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11166 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11167 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11168 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11169 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11170 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11171 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11172 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11173 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11174 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11175 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11176 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11177 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11178 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11179 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11180 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11181 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11182 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11183 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11184 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11185 	    o2->ipIfStatsInWrongIPVersion);
11186 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11187 	    o2->ipIfStatsInWrongIPVersion);
11188 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11189 	    o2->ipIfStatsOutSwitchIPVersion);
11190 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11191 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11192 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11193 	    o2->ipIfStatsHCInForwDatagrams);
11194 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11195 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11196 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11197 	    o2->ipIfStatsHCOutForwDatagrams);
11198 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11199 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11200 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11201 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11202 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11203 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11204 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11205 	    o2->ipIfStatsHCOutMcastOctets);
11206 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11207 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11208 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11209 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11210 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11211 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11212 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11213 }
11214 
11215 void
11216 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11217 {
11218 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11219 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11220 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11221 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11222 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11223 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11224 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11225 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11226 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11227 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11228 	    o2->ipv6IfIcmpInRouterSolicits);
11229 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11230 	    o2->ipv6IfIcmpInRouterAdvertisements);
11231 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11232 	    o2->ipv6IfIcmpInNeighborSolicits);
11233 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11234 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11235 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11236 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11237 	    o2->ipv6IfIcmpInGroupMembQueries);
11238 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11239 	    o2->ipv6IfIcmpInGroupMembResponses);
11240 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11241 	    o2->ipv6IfIcmpInGroupMembReductions);
11242 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11243 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11244 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11245 	    o2->ipv6IfIcmpOutDestUnreachs);
11246 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11247 	    o2->ipv6IfIcmpOutAdminProhibs);
11248 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11249 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11250 	    o2->ipv6IfIcmpOutParmProblems);
11251 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11252 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11253 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11254 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11255 	    o2->ipv6IfIcmpOutRouterSolicits);
11256 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11257 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11258 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11259 	    o2->ipv6IfIcmpOutNeighborSolicits);
11260 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11261 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11262 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11263 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11264 	    o2->ipv6IfIcmpOutGroupMembQueries);
11265 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11266 	    o2->ipv6IfIcmpOutGroupMembResponses);
11267 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11268 	    o2->ipv6IfIcmpOutGroupMembReductions);
11269 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11270 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11271 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11272 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11273 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11274 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11275 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11276 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11277 	    o2->ipv6IfIcmpInGroupMembTotal);
11278 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11279 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11280 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11281 	    o2->ipv6IfIcmpInGroupMembBadReports);
11282 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11283 	    o2->ipv6IfIcmpInGroupMembOurReports);
11284 }
11285 
11286 /*
11287  * Called before the options are updated to check if this packet will
11288  * be source routed from here.
11289  * This routine assumes that the options are well formed i.e. that they
11290  * have already been checked.
11291  */
11292 boolean_t
11293 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11294 {
11295 	ipoptp_t	opts;
11296 	uchar_t		*opt;
11297 	uint8_t		optval;
11298 	uint8_t		optlen;
11299 	ipaddr_t	dst;
11300 
11301 	if (IS_SIMPLE_IPH(ipha)) {
11302 		ip2dbg(("not source routed\n"));
11303 		return (B_FALSE);
11304 	}
11305 	dst = ipha->ipha_dst;
11306 	for (optval = ipoptp_first(&opts, ipha);
11307 	    optval != IPOPT_EOL;
11308 	    optval = ipoptp_next(&opts)) {
11309 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11310 		opt = opts.ipoptp_cur;
11311 		optlen = opts.ipoptp_len;
11312 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11313 		    optval, optlen));
11314 		switch (optval) {
11315 			uint32_t off;
11316 		case IPOPT_SSRR:
11317 		case IPOPT_LSRR:
11318 			/*
11319 			 * If dst is one of our addresses and there are some
11320 			 * entries left in the source route return (true).
11321 			 */
11322 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11323 				ip2dbg(("ip_source_routed: not next"
11324 				    " source route 0x%x\n",
11325 				    ntohl(dst)));
11326 				return (B_FALSE);
11327 			}
11328 			off = opt[IPOPT_OFFSET];
11329 			off--;
11330 			if (optlen < IP_ADDR_LEN ||
11331 			    off > optlen - IP_ADDR_LEN) {
11332 				/* End of source route */
11333 				ip1dbg(("ip_source_routed: end of SR\n"));
11334 				return (B_FALSE);
11335 			}
11336 			return (B_TRUE);
11337 		}
11338 	}
11339 	ip2dbg(("not source routed\n"));
11340 	return (B_FALSE);
11341 }
11342 
11343 /*
11344  * ip_unbind is called by the transports to remove a conn from
11345  * the fanout table.
11346  */
11347 void
11348 ip_unbind(conn_t *connp)
11349 {
11350 
11351 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11352 
11353 	if (is_system_labeled() && connp->conn_anon_port) {
11354 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11355 		    connp->conn_mlp_type, connp->conn_proto,
11356 		    ntohs(connp->conn_lport), B_FALSE);
11357 		connp->conn_anon_port = 0;
11358 	}
11359 	connp->conn_mlp_type = mlptSingle;
11360 
11361 	ipcl_hash_remove(connp);
11362 }
11363 
11364 /*
11365  * Used for deciding the MSS size for the upper layer. Thus
11366  * we need to check the outbound policy values in the conn.
11367  */
11368 int
11369 conn_ipsec_length(conn_t *connp)
11370 {
11371 	ipsec_latch_t *ipl;
11372 
11373 	ipl = connp->conn_latch;
11374 	if (ipl == NULL)
11375 		return (0);
11376 
11377 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11378 		return (0);
11379 
11380 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11381 }
11382 
11383 /*
11384  * Returns an estimate of the IPsec headers size. This is used if
11385  * we don't want to call into IPsec to get the exact size.
11386  */
11387 int
11388 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11389 {
11390 	ipsec_action_t *a;
11391 
11392 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11393 		return (0);
11394 
11395 	a = ixa->ixa_ipsec_action;
11396 	if (a == NULL) {
11397 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11398 		a = ixa->ixa_ipsec_policy->ipsp_act;
11399 	}
11400 	ASSERT(a != NULL);
11401 
11402 	return (a->ipa_ovhd);
11403 }
11404 
11405 /*
11406  * If there are any source route options, return the true final
11407  * destination. Otherwise, return the destination.
11408  */
11409 ipaddr_t
11410 ip_get_dst(ipha_t *ipha)
11411 {
11412 	ipoptp_t	opts;
11413 	uchar_t		*opt;
11414 	uint8_t		optval;
11415 	uint8_t		optlen;
11416 	ipaddr_t	dst;
11417 	uint32_t off;
11418 
11419 	dst = ipha->ipha_dst;
11420 
11421 	if (IS_SIMPLE_IPH(ipha))
11422 		return (dst);
11423 
11424 	for (optval = ipoptp_first(&opts, ipha);
11425 	    optval != IPOPT_EOL;
11426 	    optval = ipoptp_next(&opts)) {
11427 		opt = opts.ipoptp_cur;
11428 		optlen = opts.ipoptp_len;
11429 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11430 		switch (optval) {
11431 		case IPOPT_SSRR:
11432 		case IPOPT_LSRR:
11433 			off = opt[IPOPT_OFFSET];
11434 			/*
11435 			 * If one of the conditions is true, it means
11436 			 * end of options and dst already has the right
11437 			 * value.
11438 			 */
11439 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11440 				off = optlen - IP_ADDR_LEN;
11441 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11442 			}
11443 			return (dst);
11444 		default:
11445 			break;
11446 		}
11447 	}
11448 
11449 	return (dst);
11450 }
11451 
11452 /*
11453  * Outbound IP fragmentation routine.
11454  * Assumes the caller has checked whether or not fragmentation should
11455  * be allowed. Here we copy the DF bit from the header to all the generated
11456  * fragments.
11457  */
11458 int
11459 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11460     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11461     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11462 {
11463 	int		i1;
11464 	int		hdr_len;
11465 	mblk_t		*hdr_mp;
11466 	ipha_t		*ipha;
11467 	int		ip_data_end;
11468 	int		len;
11469 	mblk_t		*mp = mp_orig;
11470 	int		offset;
11471 	ill_t		*ill = nce->nce_ill;
11472 	ip_stack_t	*ipst = ill->ill_ipst;
11473 	mblk_t		*carve_mp;
11474 	uint32_t	frag_flag;
11475 	uint_t		priority = mp->b_band;
11476 	int		error = 0;
11477 
11478 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11479 
11480 	if (pkt_len != msgdsize(mp)) {
11481 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11482 		    pkt_len, msgdsize(mp)));
11483 		freemsg(mp);
11484 		return (EINVAL);
11485 	}
11486 
11487 	if (max_frag == 0) {
11488 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11489 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11490 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11491 		freemsg(mp);
11492 		return (EINVAL);
11493 	}
11494 
11495 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11496 	ipha = (ipha_t *)mp->b_rptr;
11497 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11498 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11499 
11500 	/*
11501 	 * Establish the starting offset.  May not be zero if we are fragging
11502 	 * a fragment that is being forwarded.
11503 	 */
11504 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11505 
11506 	/* TODO why is this test needed? */
11507 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11508 		/* TODO: notify ulp somehow */
11509 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11510 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11511 		freemsg(mp);
11512 		return (EINVAL);
11513 	}
11514 
11515 	hdr_len = IPH_HDR_LENGTH(ipha);
11516 	ipha->ipha_hdr_checksum = 0;
11517 
11518 	/*
11519 	 * Establish the number of bytes maximum per frag, after putting
11520 	 * in the header.
11521 	 */
11522 	len = (max_frag - hdr_len) & ~7;
11523 
11524 	/* Get a copy of the header for the trailing frags */
11525 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11526 	    mp);
11527 	if (hdr_mp == NULL) {
11528 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11529 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11530 		freemsg(mp);
11531 		return (ENOBUFS);
11532 	}
11533 
11534 	/* Store the starting offset, with the MoreFrags flag. */
11535 	i1 = offset | IPH_MF | frag_flag;
11536 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11537 
11538 	/* Establish the ending byte offset, based on the starting offset. */
11539 	offset <<= 3;
11540 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11541 
11542 	/* Store the length of the first fragment in the IP header. */
11543 	i1 = len + hdr_len;
11544 	ASSERT(i1 <= IP_MAXPACKET);
11545 	ipha->ipha_length = htons((uint16_t)i1);
11546 
11547 	/*
11548 	 * Compute the IP header checksum for the first frag.  We have to
11549 	 * watch out that we stop at the end of the header.
11550 	 */
11551 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11552 
11553 	/*
11554 	 * Now carve off the first frag.  Note that this will include the
11555 	 * original IP header.
11556 	 */
11557 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11558 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11559 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11560 		freeb(hdr_mp);
11561 		freemsg(mp_orig);
11562 		return (ENOBUFS);
11563 	}
11564 
11565 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11566 
11567 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11568 	    ixa_cookie);
11569 	if (error != 0 && error != EWOULDBLOCK) {
11570 		/* No point in sending the other fragments */
11571 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11572 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11573 		freeb(hdr_mp);
11574 		freemsg(mp_orig);
11575 		return (error);
11576 	}
11577 
11578 	/* No need to redo state machine in loop */
11579 	ixaflags &= ~IXAF_REACH_CONF;
11580 
11581 	/* Advance the offset to the second frag starting point. */
11582 	offset += len;
11583 	/*
11584 	 * Update hdr_len from the copied header - there might be less options
11585 	 * in the later fragments.
11586 	 */
11587 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11588 	/* Loop until done. */
11589 	for (;;) {
11590 		uint16_t	offset_and_flags;
11591 		uint16_t	ip_len;
11592 
11593 		if (ip_data_end - offset > len) {
11594 			/*
11595 			 * Carve off the appropriate amount from the original
11596 			 * datagram.
11597 			 */
11598 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11599 				mp = NULL;
11600 				break;
11601 			}
11602 			/*
11603 			 * More frags after this one.  Get another copy
11604 			 * of the header.
11605 			 */
11606 			if (carve_mp->b_datap->db_ref == 1 &&
11607 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11608 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11609 				/* Inline IP header */
11610 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11611 				    hdr_mp->b_rptr;
11612 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11613 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11614 				mp = carve_mp;
11615 			} else {
11616 				if (!(mp = copyb(hdr_mp))) {
11617 					freemsg(carve_mp);
11618 					break;
11619 				}
11620 				/* Get priority marking, if any. */
11621 				mp->b_band = priority;
11622 				mp->b_cont = carve_mp;
11623 			}
11624 			ipha = (ipha_t *)mp->b_rptr;
11625 			offset_and_flags = IPH_MF;
11626 		} else {
11627 			/*
11628 			 * Last frag.  Consume the header. Set len to
11629 			 * the length of this last piece.
11630 			 */
11631 			len = ip_data_end - offset;
11632 
11633 			/*
11634 			 * Carve off the appropriate amount from the original
11635 			 * datagram.
11636 			 */
11637 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11638 				mp = NULL;
11639 				break;
11640 			}
11641 			if (carve_mp->b_datap->db_ref == 1 &&
11642 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11643 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11644 				/* Inline IP header */
11645 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11646 				    hdr_mp->b_rptr;
11647 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11648 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11649 				mp = carve_mp;
11650 				freeb(hdr_mp);
11651 				hdr_mp = mp;
11652 			} else {
11653 				mp = hdr_mp;
11654 				/* Get priority marking, if any. */
11655 				mp->b_band = priority;
11656 				mp->b_cont = carve_mp;
11657 			}
11658 			ipha = (ipha_t *)mp->b_rptr;
11659 			/* A frag of a frag might have IPH_MF non-zero */
11660 			offset_and_flags =
11661 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11662 			    IPH_MF;
11663 		}
11664 		offset_and_flags |= (uint16_t)(offset >> 3);
11665 		offset_and_flags |= (uint16_t)frag_flag;
11666 		/* Store the offset and flags in the IP header. */
11667 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11668 
11669 		/* Store the length in the IP header. */
11670 		ip_len = (uint16_t)(len + hdr_len);
11671 		ipha->ipha_length = htons(ip_len);
11672 
11673 		/*
11674 		 * Set the IP header checksum.	Note that mp is just
11675 		 * the header, so this is easy to pass to ip_csum.
11676 		 */
11677 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11678 
11679 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11680 
11681 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11682 		    nolzid, ixa_cookie);
11683 		/* All done if we just consumed the hdr_mp. */
11684 		if (mp == hdr_mp) {
11685 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11686 			return (error);
11687 		}
11688 		if (error != 0 && error != EWOULDBLOCK) {
11689 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11690 			    mblk_t *, hdr_mp);
11691 			/* No point in sending the other fragments */
11692 			break;
11693 		}
11694 
11695 		/* Otherwise, advance and loop. */
11696 		offset += len;
11697 	}
11698 	/* Clean up following allocation failure. */
11699 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11700 	ip_drop_output("FragFails: loop ended", NULL, ill);
11701 	if (mp != hdr_mp)
11702 		freeb(hdr_mp);
11703 	if (mp != mp_orig)
11704 		freemsg(mp_orig);
11705 	return (error);
11706 }
11707 
11708 /*
11709  * Copy the header plus those options which have the copy bit set
11710  */
11711 static mblk_t *
11712 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11713     mblk_t *src)
11714 {
11715 	mblk_t	*mp;
11716 	uchar_t	*up;
11717 
11718 	/*
11719 	 * Quick check if we need to look for options without the copy bit
11720 	 * set
11721 	 */
11722 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11723 	if (!mp)
11724 		return (mp);
11725 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11726 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11727 		bcopy(rptr, mp->b_rptr, hdr_len);
11728 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11729 		return (mp);
11730 	}
11731 	up  = mp->b_rptr;
11732 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11733 	up += IP_SIMPLE_HDR_LENGTH;
11734 	rptr += IP_SIMPLE_HDR_LENGTH;
11735 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11736 	while (hdr_len > 0) {
11737 		uint32_t optval;
11738 		uint32_t optlen;
11739 
11740 		optval = *rptr;
11741 		if (optval == IPOPT_EOL)
11742 			break;
11743 		if (optval == IPOPT_NOP)
11744 			optlen = 1;
11745 		else
11746 			optlen = rptr[1];
11747 		if (optval & IPOPT_COPY) {
11748 			bcopy(rptr, up, optlen);
11749 			up += optlen;
11750 		}
11751 		rptr += optlen;
11752 		hdr_len -= optlen;
11753 	}
11754 	/*
11755 	 * Make sure that we drop an even number of words by filling
11756 	 * with EOL to the next word boundary.
11757 	 */
11758 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11759 	    hdr_len & 0x3; hdr_len++)
11760 		*up++ = IPOPT_EOL;
11761 	mp->b_wptr = up;
11762 	/* Update header length */
11763 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11764 	return (mp);
11765 }
11766 
11767 /*
11768  * Update any source route, record route, or timestamp options when
11769  * sending a packet back to ourselves.
11770  * Check that we are at end of strict source route.
11771  * The options have been sanity checked by ip_output_options().
11772  */
11773 void
11774 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11775 {
11776 	ipoptp_t	opts;
11777 	uchar_t		*opt;
11778 	uint8_t		optval;
11779 	uint8_t		optlen;
11780 	ipaddr_t	dst;
11781 	uint32_t	ts;
11782 	timestruc_t	now;
11783 
11784 	for (optval = ipoptp_first(&opts, ipha);
11785 	    optval != IPOPT_EOL;
11786 	    optval = ipoptp_next(&opts)) {
11787 		opt = opts.ipoptp_cur;
11788 		optlen = opts.ipoptp_len;
11789 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11790 		switch (optval) {
11791 			uint32_t off;
11792 		case IPOPT_SSRR:
11793 		case IPOPT_LSRR:
11794 			off = opt[IPOPT_OFFSET];
11795 			off--;
11796 			if (optlen < IP_ADDR_LEN ||
11797 			    off > optlen - IP_ADDR_LEN) {
11798 				/* End of source route */
11799 				break;
11800 			}
11801 			/*
11802 			 * This will only happen if two consecutive entries
11803 			 * in the source route contains our address or if
11804 			 * it is a packet with a loose source route which
11805 			 * reaches us before consuming the whole source route
11806 			 */
11807 
11808 			if (optval == IPOPT_SSRR) {
11809 				return;
11810 			}
11811 			/*
11812 			 * Hack: instead of dropping the packet truncate the
11813 			 * source route to what has been used by filling the
11814 			 * rest with IPOPT_NOP.
11815 			 */
11816 			opt[IPOPT_OLEN] = (uint8_t)off;
11817 			while (off < optlen) {
11818 				opt[off++] = IPOPT_NOP;
11819 			}
11820 			break;
11821 		case IPOPT_RR:
11822 			off = opt[IPOPT_OFFSET];
11823 			off--;
11824 			if (optlen < IP_ADDR_LEN ||
11825 			    off > optlen - IP_ADDR_LEN) {
11826 				/* No more room - ignore */
11827 				ip1dbg((
11828 				    "ip_output_local_options: end of RR\n"));
11829 				break;
11830 			}
11831 			dst = htonl(INADDR_LOOPBACK);
11832 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11833 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11834 			break;
11835 		case IPOPT_TS:
11836 			/* Insert timestamp if there is romm */
11837 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11838 			case IPOPT_TS_TSONLY:
11839 				off = IPOPT_TS_TIMELEN;
11840 				break;
11841 			case IPOPT_TS_PRESPEC:
11842 			case IPOPT_TS_PRESPEC_RFC791:
11843 				/* Verify that the address matched */
11844 				off = opt[IPOPT_OFFSET] - 1;
11845 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
11846 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11847 					/* Not for us */
11848 					break;
11849 				}
11850 				/* FALLTHRU */
11851 			case IPOPT_TS_TSANDADDR:
11852 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
11853 				break;
11854 			default:
11855 				/*
11856 				 * ip_*put_options should have already
11857 				 * dropped this packet.
11858 				 */
11859 				cmn_err(CE_PANIC, "ip_output_local_options: "
11860 				    "unknown IT - bug in ip_output_options?\n");
11861 				return;	/* Keep "lint" happy */
11862 			}
11863 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
11864 				/* Increase overflow counter */
11865 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
11866 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
11867 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
11868 				    (off << 4);
11869 				break;
11870 			}
11871 			off = opt[IPOPT_OFFSET] - 1;
11872 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11873 			case IPOPT_TS_PRESPEC:
11874 			case IPOPT_TS_PRESPEC_RFC791:
11875 			case IPOPT_TS_TSANDADDR:
11876 				dst = htonl(INADDR_LOOPBACK);
11877 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11878 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11879 				/* FALLTHRU */
11880 			case IPOPT_TS_TSONLY:
11881 				off = opt[IPOPT_OFFSET] - 1;
11882 				/* Compute # of milliseconds since midnight */
11883 				gethrestime(&now);
11884 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
11885 				    now.tv_nsec / (NANOSEC / MILLISEC);
11886 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
11887 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
11888 				break;
11889 			}
11890 			break;
11891 		}
11892 	}
11893 }
11894 
11895 /*
11896  * Prepend an M_DATA fastpath header, and if none present prepend a
11897  * DL_UNITDATA_REQ. Frees the mblk on failure.
11898  *
11899  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
11900  * If there is a change to them, the nce will be deleted (condemned) and
11901  * a new nce_t will be created when packets are sent. Thus we need no locks
11902  * to access those fields.
11903  *
11904  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
11905  * we place b_band in dl_priority.dl_max.
11906  */
11907 static mblk_t *
11908 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
11909 {
11910 	uint_t	hlen;
11911 	mblk_t *mp1;
11912 	uint_t	priority;
11913 	uchar_t *rptr;
11914 
11915 	rptr = mp->b_rptr;
11916 
11917 	ASSERT(DB_TYPE(mp) == M_DATA);
11918 	priority = mp->b_band;
11919 
11920 	ASSERT(nce != NULL);
11921 	if ((mp1 = nce->nce_fp_mp) != NULL) {
11922 		hlen = MBLKL(mp1);
11923 		/*
11924 		 * Check if we have enough room to prepend fastpath
11925 		 * header
11926 		 */
11927 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
11928 			rptr -= hlen;
11929 			bcopy(mp1->b_rptr, rptr, hlen);
11930 			/*
11931 			 * Set the b_rptr to the start of the link layer
11932 			 * header
11933 			 */
11934 			mp->b_rptr = rptr;
11935 			return (mp);
11936 		}
11937 		mp1 = copyb(mp1);
11938 		if (mp1 == NULL) {
11939 			ill_t *ill = nce->nce_ill;
11940 
11941 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
11942 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
11943 			freemsg(mp);
11944 			return (NULL);
11945 		}
11946 		mp1->b_band = priority;
11947 		mp1->b_cont = mp;
11948 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
11949 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
11950 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
11951 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
11952 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
11953 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
11954 		/*
11955 		 * XXX disable ICK_VALID and compute checksum
11956 		 * here; can happen if nce_fp_mp changes and
11957 		 * it can't be copied now due to insufficient
11958 		 * space. (unlikely, fp mp can change, but it
11959 		 * does not increase in length)
11960 		 */
11961 		return (mp1);
11962 	}
11963 	mp1 = copyb(nce->nce_dlur_mp);
11964 
11965 	if (mp1 == NULL) {
11966 		ill_t *ill = nce->nce_ill;
11967 
11968 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
11969 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
11970 		freemsg(mp);
11971 		return (NULL);
11972 	}
11973 	mp1->b_cont = mp;
11974 	if (priority != 0) {
11975 		mp1->b_band = priority;
11976 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
11977 		    priority;
11978 	}
11979 	return (mp1);
11980 #undef rptr
11981 }
11982 
11983 /*
11984  * Finish the outbound IPsec processing. This function is called from
11985  * ipsec_out_process() if the IPsec packet was processed
11986  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
11987  * asynchronously.
11988  *
11989  * This is common to IPv4 and IPv6.
11990  */
11991 int
11992 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
11993 {
11994 	iaflags_t	ixaflags = ixa->ixa_flags;
11995 	uint_t		pktlen;
11996 
11997 
11998 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
11999 	if (ixaflags & IXAF_IS_IPV4) {
12000 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12001 
12002 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12003 		pktlen = ntohs(ipha->ipha_length);
12004 	} else {
12005 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12006 
12007 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12008 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12009 	}
12010 
12011 	/*
12012 	 * We release any hard reference on the SAs here to make
12013 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12014 	 * on the SAs.
12015 	 * If in the future we want the hard latching of the SAs in the
12016 	 * ip_xmit_attr_t then we should remove this.
12017 	 */
12018 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12019 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12020 		ixa->ixa_ipsec_esp_sa = NULL;
12021 	}
12022 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12023 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12024 		ixa->ixa_ipsec_ah_sa = NULL;
12025 	}
12026 
12027 	/* Do we need to fragment? */
12028 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12029 	    pktlen > ixa->ixa_fragsize) {
12030 		if (ixaflags & IXAF_IS_IPV4) {
12031 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12032 			/*
12033 			 * We check for the DF case in ipsec_out_process
12034 			 * hence this only handles the non-DF case.
12035 			 */
12036 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12037 			    pktlen, ixa->ixa_fragsize,
12038 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12039 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12040 			    &ixa->ixa_cookie));
12041 		} else {
12042 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12043 			if (mp == NULL) {
12044 				/* MIB and ip_drop_output already done */
12045 				return (ENOMEM);
12046 			}
12047 			pktlen += sizeof (ip6_frag_t);
12048 			if (pktlen > ixa->ixa_fragsize) {
12049 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12050 				    ixa->ixa_flags, pktlen,
12051 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12052 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12053 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12054 			}
12055 		}
12056 	}
12057 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12058 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12059 	    ixa->ixa_no_loop_zoneid, NULL));
12060 }
12061 
12062 /*
12063  * Finish the inbound IPsec processing. This function is called from
12064  * ipsec_out_process() if the IPsec packet was processed
12065  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12066  * asynchronously.
12067  *
12068  * This is common to IPv4 and IPv6.
12069  */
12070 void
12071 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12072 {
12073 	iaflags_t	iraflags = ira->ira_flags;
12074 
12075 	/* Length might have changed */
12076 	if (iraflags & IRAF_IS_IPV4) {
12077 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12078 
12079 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12080 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12081 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12082 		ira->ira_protocol = ipha->ipha_protocol;
12083 
12084 		ip_fanout_v4(mp, ipha, ira);
12085 	} else {
12086 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12087 		uint8_t		*nexthdrp;
12088 
12089 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12090 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12091 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12092 		    &nexthdrp)) {
12093 			/* Malformed packet */
12094 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12095 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12096 			freemsg(mp);
12097 			return;
12098 		}
12099 		ira->ira_protocol = *nexthdrp;
12100 		ip_fanout_v6(mp, ip6h, ira);
12101 	}
12102 }
12103 
12104 /*
12105  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12106  *
12107  * If this function returns B_TRUE, the requested SA's have been filled
12108  * into the ixa_ipsec_*_sa pointers.
12109  *
12110  * If the function returns B_FALSE, the packet has been "consumed", most
12111  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12112  *
12113  * The SA references created by the protocol-specific "select"
12114  * function will be released in ip_output_post_ipsec.
12115  */
12116 static boolean_t
12117 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12118 {
12119 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12120 	ipsec_policy_t *pp;
12121 	ipsec_action_t *ap;
12122 
12123 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12124 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12125 	    (ixa->ixa_ipsec_action != NULL));
12126 
12127 	ap = ixa->ixa_ipsec_action;
12128 	if (ap == NULL) {
12129 		pp = ixa->ixa_ipsec_policy;
12130 		ASSERT(pp != NULL);
12131 		ap = pp->ipsp_act;
12132 		ASSERT(ap != NULL);
12133 	}
12134 
12135 	/*
12136 	 * We have an action.  now, let's select SA's.
12137 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12138 	 * be cached in the conn_t.
12139 	 */
12140 	if (ap->ipa_want_esp) {
12141 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12142 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12143 			    IPPROTO_ESP);
12144 		}
12145 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12146 	}
12147 
12148 	if (ap->ipa_want_ah) {
12149 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12150 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12151 			    IPPROTO_AH);
12152 		}
12153 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12154 		/*
12155 		 * The ESP and AH processing order needs to be preserved
12156 		 * when both protocols are required (ESP should be applied
12157 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12158 		 * when both ESP and AH are required, and an AH ACQUIRE
12159 		 * is needed.
12160 		 */
12161 		if (ap->ipa_want_esp && need_ah_acquire)
12162 			need_esp_acquire = B_TRUE;
12163 	}
12164 
12165 	/*
12166 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12167 	 * Release SAs that got referenced, but will not be used until we
12168 	 * acquire _all_ of the SAs we need.
12169 	 */
12170 	if (need_ah_acquire || need_esp_acquire) {
12171 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12172 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12173 			ixa->ixa_ipsec_ah_sa = NULL;
12174 		}
12175 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12176 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12177 			ixa->ixa_ipsec_esp_sa = NULL;
12178 		}
12179 
12180 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12181 		return (B_FALSE);
12182 	}
12183 
12184 	return (B_TRUE);
12185 }
12186 
12187 /*
12188  * Handle IPsec output processing.
12189  * This function is only entered once for a given packet.
12190  * We try to do things synchronously, but if we need to have user-level
12191  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12192  * will be completed
12193  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12194  *  - when asynchronous ESP is done it will do AH
12195  *
12196  * In all cases we come back in ip_output_post_ipsec() to fragment and
12197  * send out the packet.
12198  */
12199 int
12200 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12201 {
12202 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12203 	ip_stack_t	*ipst = ixa->ixa_ipst;
12204 	ipsec_stack_t	*ipss;
12205 	ipsec_policy_t	*pp;
12206 	ipsec_action_t	*ap;
12207 
12208 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12209 
12210 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12211 	    (ixa->ixa_ipsec_action != NULL));
12212 
12213 	ipss = ipst->ips_netstack->netstack_ipsec;
12214 	if (!ipsec_loaded(ipss)) {
12215 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12216 		ip_drop_packet(mp, B_TRUE, ill,
12217 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12218 		    &ipss->ipsec_dropper);
12219 		return (ENOTSUP);
12220 	}
12221 
12222 	ap = ixa->ixa_ipsec_action;
12223 	if (ap == NULL) {
12224 		pp = ixa->ixa_ipsec_policy;
12225 		ASSERT(pp != NULL);
12226 		ap = pp->ipsp_act;
12227 		ASSERT(ap != NULL);
12228 	}
12229 
12230 	/* Handle explicit drop action and bypass. */
12231 	switch (ap->ipa_act.ipa_type) {
12232 	case IPSEC_ACT_DISCARD:
12233 	case IPSEC_ACT_REJECT:
12234 		ip_drop_packet(mp, B_FALSE, ill,
12235 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12236 		return (EHOSTUNREACH);	/* IPsec policy failure */
12237 	case IPSEC_ACT_BYPASS:
12238 		return (ip_output_post_ipsec(mp, ixa));
12239 	}
12240 
12241 	/*
12242 	 * The order of processing is first insert a IP header if needed.
12243 	 * Then insert the ESP header and then the AH header.
12244 	 */
12245 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12246 		/*
12247 		 * First get the outer IP header before sending
12248 		 * it to ESP.
12249 		 */
12250 		ipha_t *oipha, *iipha;
12251 		mblk_t *outer_mp, *inner_mp;
12252 
12253 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12254 			(void) mi_strlog(ill->ill_rq, 0,
12255 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12256 			    "ipsec_out_process: "
12257 			    "Self-Encapsulation failed: Out of memory\n");
12258 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12259 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12260 			freemsg(mp);
12261 			return (ENOBUFS);
12262 		}
12263 		inner_mp = mp;
12264 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12265 		oipha = (ipha_t *)outer_mp->b_rptr;
12266 		iipha = (ipha_t *)inner_mp->b_rptr;
12267 		*oipha = *iipha;
12268 		outer_mp->b_wptr += sizeof (ipha_t);
12269 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12270 		    sizeof (ipha_t));
12271 		oipha->ipha_protocol = IPPROTO_ENCAP;
12272 		oipha->ipha_version_and_hdr_length =
12273 		    IP_SIMPLE_HDR_VERSION;
12274 		oipha->ipha_hdr_checksum = 0;
12275 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12276 		outer_mp->b_cont = inner_mp;
12277 		mp = outer_mp;
12278 
12279 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12280 	}
12281 
12282 	/* If we need to wait for a SA then we can't return any errno */
12283 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12284 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12285 	    !ipsec_out_select_sa(mp, ixa))
12286 		return (0);
12287 
12288 	/*
12289 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12290 	 * to do the heavy lifting.
12291 	 */
12292 	if (ap->ipa_want_esp) {
12293 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12294 
12295 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12296 		if (mp == NULL) {
12297 			/*
12298 			 * Either it failed or is pending. In the former case
12299 			 * ipIfStatsInDiscards was increased.
12300 			 */
12301 			return (0);
12302 		}
12303 	}
12304 
12305 	if (ap->ipa_want_ah) {
12306 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12307 
12308 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12309 		if (mp == NULL) {
12310 			/*
12311 			 * Either it failed or is pending. In the former case
12312 			 * ipIfStatsInDiscards was increased.
12313 			 */
12314 			return (0);
12315 		}
12316 	}
12317 	/*
12318 	 * We are done with IPsec processing. Send it over
12319 	 * the wire.
12320 	 */
12321 	return (ip_output_post_ipsec(mp, ixa));
12322 }
12323 
12324 /*
12325  * ioctls that go through a down/up sequence may need to wait for the down
12326  * to complete. This involves waiting for the ire and ipif refcnts to go down
12327  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12328  */
12329 /* ARGSUSED */
12330 void
12331 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12332 {
12333 	struct iocblk *iocp;
12334 	mblk_t *mp1;
12335 	ip_ioctl_cmd_t *ipip;
12336 	int err;
12337 	sin_t	*sin;
12338 	struct lifreq *lifr;
12339 	struct ifreq *ifr;
12340 
12341 	iocp = (struct iocblk *)mp->b_rptr;
12342 	ASSERT(ipsq != NULL);
12343 	/* Existence of mp1 verified in ip_wput_nondata */
12344 	mp1 = mp->b_cont->b_cont;
12345 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12346 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12347 		/*
12348 		 * Special case where ipx_current_ipif is not set:
12349 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12350 		 * We are here as were not able to complete the operation in
12351 		 * ipif_set_values because we could not become exclusive on
12352 		 * the new ipsq.
12353 		 */
12354 		ill_t *ill = q->q_ptr;
12355 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12356 	}
12357 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12358 
12359 	if (ipip->ipi_cmd_type == IF_CMD) {
12360 		/* This a old style SIOC[GS]IF* command */
12361 		ifr = (struct ifreq *)mp1->b_rptr;
12362 		sin = (sin_t *)&ifr->ifr_addr;
12363 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12364 		/* This a new style SIOC[GS]LIF* command */
12365 		lifr = (struct lifreq *)mp1->b_rptr;
12366 		sin = (sin_t *)&lifr->lifr_addr;
12367 	} else {
12368 		sin = NULL;
12369 	}
12370 
12371 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12372 	    q, mp, ipip, mp1->b_rptr);
12373 
12374 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12375 	    int, ipip->ipi_cmd,
12376 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12377 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12378 
12379 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12380 }
12381 
12382 /*
12383  * ioctl processing
12384  *
12385  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12386  * the ioctl command in the ioctl tables, determines the copyin data size
12387  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12388  *
12389  * ioctl processing then continues when the M_IOCDATA makes its way down to
12390  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12391  * associated 'conn' is refheld till the end of the ioctl and the general
12392  * ioctl processing function ip_process_ioctl() is called to extract the
12393  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12394  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12395  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12396  * is used to extract the ioctl's arguments.
12397  *
12398  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12399  * so goes thru the serialization primitive ipsq_try_enter. Then the
12400  * appropriate function to handle the ioctl is called based on the entry in
12401  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12402  * which also refreleases the 'conn' that was refheld at the start of the
12403  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12404  *
12405  * Many exclusive ioctls go thru an internal down up sequence as part of
12406  * the operation. For example an attempt to change the IP address of an
12407  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12408  * does all the cleanup such as deleting all ires that use this address.
12409  * Then we need to wait till all references to the interface go away.
12410  */
12411 void
12412 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12413 {
12414 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12415 	ip_ioctl_cmd_t *ipip = arg;
12416 	ip_extract_func_t *extract_funcp;
12417 	cmd_info_t ci;
12418 	int err;
12419 	boolean_t entered_ipsq = B_FALSE;
12420 
12421 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12422 
12423 	if (ipip == NULL)
12424 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12425 
12426 	/*
12427 	 * SIOCLIFADDIF needs to go thru a special path since the
12428 	 * ill may not exist yet. This happens in the case of lo0
12429 	 * which is created using this ioctl.
12430 	 */
12431 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12432 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12433 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12434 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12435 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12436 		return;
12437 	}
12438 
12439 	ci.ci_ipif = NULL;
12440 	switch (ipip->ipi_cmd_type) {
12441 	case MISC_CMD:
12442 	case MSFILT_CMD:
12443 		/*
12444 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12445 		 */
12446 		if (ipip->ipi_cmd == IF_UNITSEL) {
12447 			/* ioctl comes down the ill */
12448 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12449 			ipif_refhold(ci.ci_ipif);
12450 		}
12451 		err = 0;
12452 		ci.ci_sin = NULL;
12453 		ci.ci_sin6 = NULL;
12454 		ci.ci_lifr = NULL;
12455 		extract_funcp = NULL;
12456 		break;
12457 
12458 	case IF_CMD:
12459 	case LIF_CMD:
12460 		extract_funcp = ip_extract_lifreq;
12461 		break;
12462 
12463 	case ARP_CMD:
12464 	case XARP_CMD:
12465 		extract_funcp = ip_extract_arpreq;
12466 		break;
12467 
12468 	default:
12469 		ASSERT(0);
12470 	}
12471 
12472 	if (extract_funcp != NULL) {
12473 		err = (*extract_funcp)(q, mp, ipip, &ci);
12474 		if (err != 0) {
12475 			DTRACE_PROBE4(ipif__ioctl,
12476 			    char *, "ip_process_ioctl finish err",
12477 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12478 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12479 			return;
12480 		}
12481 
12482 		/*
12483 		 * All of the extraction functions return a refheld ipif.
12484 		 */
12485 		ASSERT(ci.ci_ipif != NULL);
12486 	}
12487 
12488 	if (!(ipip->ipi_flags & IPI_WR)) {
12489 		/*
12490 		 * A return value of EINPROGRESS means the ioctl is
12491 		 * either queued and waiting for some reason or has
12492 		 * already completed.
12493 		 */
12494 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12495 		    ci.ci_lifr);
12496 		if (ci.ci_ipif != NULL) {
12497 			DTRACE_PROBE4(ipif__ioctl,
12498 			    char *, "ip_process_ioctl finish RD",
12499 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12500 			    ipif_t *, ci.ci_ipif);
12501 			ipif_refrele(ci.ci_ipif);
12502 		} else {
12503 			DTRACE_PROBE4(ipif__ioctl,
12504 			    char *, "ip_process_ioctl finish RD",
12505 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12506 		}
12507 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12508 		return;
12509 	}
12510 
12511 	ASSERT(ci.ci_ipif != NULL);
12512 
12513 	/*
12514 	 * If ipsq is non-NULL, we are already being called exclusively
12515 	 */
12516 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12517 	if (ipsq == NULL) {
12518 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12519 		    NEW_OP, B_TRUE);
12520 		if (ipsq == NULL) {
12521 			ipif_refrele(ci.ci_ipif);
12522 			return;
12523 		}
12524 		entered_ipsq = B_TRUE;
12525 	}
12526 	/*
12527 	 * Release the ipif so that ipif_down and friends that wait for
12528 	 * references to go away are not misled about the current ipif_refcnt
12529 	 * values. We are writer so we can access the ipif even after releasing
12530 	 * the ipif.
12531 	 */
12532 	ipif_refrele(ci.ci_ipif);
12533 
12534 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12535 
12536 	/*
12537 	 * A return value of EINPROGRESS means the ioctl is
12538 	 * either queued and waiting for some reason or has
12539 	 * already completed.
12540 	 */
12541 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12542 
12543 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12544 	    int, ipip->ipi_cmd,
12545 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12546 	    ipif_t *, ci.ci_ipif);
12547 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12548 
12549 	if (entered_ipsq)
12550 		ipsq_exit(ipsq);
12551 }
12552 
12553 /*
12554  * Complete the ioctl. Typically ioctls use the mi package and need to
12555  * do mi_copyout/mi_copy_done.
12556  */
12557 void
12558 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12559 {
12560 	conn_t	*connp = NULL;
12561 
12562 	if (err == EINPROGRESS)
12563 		return;
12564 
12565 	if (CONN_Q(q)) {
12566 		connp = Q_TO_CONN(q);
12567 		ASSERT(connp->conn_ref >= 2);
12568 	}
12569 
12570 	switch (mode) {
12571 	case COPYOUT:
12572 		if (err == 0)
12573 			mi_copyout(q, mp);
12574 		else
12575 			mi_copy_done(q, mp, err);
12576 		break;
12577 
12578 	case NO_COPYOUT:
12579 		mi_copy_done(q, mp, err);
12580 		break;
12581 
12582 	default:
12583 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12584 		break;
12585 	}
12586 
12587 	/*
12588 	 * The conn refhold and ioctlref placed on the conn at the start of the
12589 	 * ioctl are released here.
12590 	 */
12591 	if (connp != NULL) {
12592 		CONN_DEC_IOCTLREF(connp);
12593 		CONN_OPER_PENDING_DONE(connp);
12594 	}
12595 
12596 	if (ipsq != NULL)
12597 		ipsq_current_finish(ipsq);
12598 }
12599 
12600 /* Handles all non data messages */
12601 void
12602 ip_wput_nondata(queue_t *q, mblk_t *mp)
12603 {
12604 	mblk_t		*mp1;
12605 	struct iocblk	*iocp;
12606 	ip_ioctl_cmd_t	*ipip;
12607 	conn_t		*connp;
12608 	cred_t		*cr;
12609 	char		*proto_str;
12610 
12611 	if (CONN_Q(q))
12612 		connp = Q_TO_CONN(q);
12613 	else
12614 		connp = NULL;
12615 
12616 	switch (DB_TYPE(mp)) {
12617 	case M_IOCTL:
12618 		/*
12619 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12620 		 * will arrange to copy in associated control structures.
12621 		 */
12622 		ip_sioctl_copyin_setup(q, mp);
12623 		return;
12624 	case M_IOCDATA:
12625 		/*
12626 		 * Ensure that this is associated with one of our trans-
12627 		 * parent ioctls.  If it's not ours, discard it if we're
12628 		 * running as a driver, or pass it on if we're a module.
12629 		 */
12630 		iocp = (struct iocblk *)mp->b_rptr;
12631 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12632 		if (ipip == NULL) {
12633 			if (q->q_next == NULL) {
12634 				goto nak;
12635 			} else {
12636 				putnext(q, mp);
12637 			}
12638 			return;
12639 		}
12640 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12641 			/*
12642 			 * The ioctl is one we recognise, but is not consumed
12643 			 * by IP as a module and we are a module, so we drop
12644 			 */
12645 			goto nak;
12646 		}
12647 
12648 		/* IOCTL continuation following copyin or copyout. */
12649 		if (mi_copy_state(q, mp, NULL) == -1) {
12650 			/*
12651 			 * The copy operation failed.  mi_copy_state already
12652 			 * cleaned up, so we're out of here.
12653 			 */
12654 			return;
12655 		}
12656 		/*
12657 		 * If we just completed a copy in, we become writer and
12658 		 * continue processing in ip_sioctl_copyin_done.  If it
12659 		 * was a copy out, we call mi_copyout again.  If there is
12660 		 * nothing more to copy out, it will complete the IOCTL.
12661 		 */
12662 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12663 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12664 				mi_copy_done(q, mp, EPROTO);
12665 				return;
12666 			}
12667 			/*
12668 			 * Check for cases that need more copying.  A return
12669 			 * value of 0 means a second copyin has been started,
12670 			 * so we return; a return value of 1 means no more
12671 			 * copying is needed, so we continue.
12672 			 */
12673 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12674 			    MI_COPY_COUNT(mp) == 1) {
12675 				if (ip_copyin_msfilter(q, mp) == 0)
12676 					return;
12677 			}
12678 			/*
12679 			 * Refhold the conn, till the ioctl completes. This is
12680 			 * needed in case the ioctl ends up in the pending mp
12681 			 * list. Every mp in the ipx_pending_mp list must have
12682 			 * a refhold on the conn to resume processing. The
12683 			 * refhold is released when the ioctl completes
12684 			 * (whether normally or abnormally). An ioctlref is also
12685 			 * placed on the conn to prevent TCP from removing the
12686 			 * queue needed to send the ioctl reply back.
12687 			 * In all cases ip_ioctl_finish is called to finish
12688 			 * the ioctl and release the refholds.
12689 			 */
12690 			if (connp != NULL) {
12691 				/* This is not a reentry */
12692 				CONN_INC_REF(connp);
12693 				CONN_INC_IOCTLREF(connp);
12694 			} else {
12695 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12696 					mi_copy_done(q, mp, EINVAL);
12697 					return;
12698 				}
12699 			}
12700 
12701 			ip_process_ioctl(NULL, q, mp, ipip);
12702 
12703 		} else {
12704 			mi_copyout(q, mp);
12705 		}
12706 		return;
12707 
12708 	case M_IOCNAK:
12709 		/*
12710 		 * The only way we could get here is if a resolver didn't like
12711 		 * an IOCTL we sent it.	 This shouldn't happen.
12712 		 */
12713 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12714 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12715 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12716 		freemsg(mp);
12717 		return;
12718 	case M_IOCACK:
12719 		/* /dev/ip shouldn't see this */
12720 		goto nak;
12721 	case M_FLUSH:
12722 		if (*mp->b_rptr & FLUSHW)
12723 			flushq(q, FLUSHALL);
12724 		if (q->q_next) {
12725 			putnext(q, mp);
12726 			return;
12727 		}
12728 		if (*mp->b_rptr & FLUSHR) {
12729 			*mp->b_rptr &= ~FLUSHW;
12730 			qreply(q, mp);
12731 			return;
12732 		}
12733 		freemsg(mp);
12734 		return;
12735 	case M_CTL:
12736 		break;
12737 	case M_PROTO:
12738 	case M_PCPROTO:
12739 		/*
12740 		 * The only PROTO messages we expect are SNMP-related.
12741 		 */
12742 		switch (((union T_primitives *)mp->b_rptr)->type) {
12743 		case T_SVR4_OPTMGMT_REQ:
12744 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12745 			    "flags %x\n",
12746 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12747 
12748 			if (connp == NULL) {
12749 				proto_str = "T_SVR4_OPTMGMT_REQ";
12750 				goto protonak;
12751 			}
12752 
12753 			/*
12754 			 * All Solaris components should pass a db_credp
12755 			 * for this TPI message, hence we ASSERT.
12756 			 * But in case there is some other M_PROTO that looks
12757 			 * like a TPI message sent by some other kernel
12758 			 * component, we check and return an error.
12759 			 */
12760 			cr = msg_getcred(mp, NULL);
12761 			ASSERT(cr != NULL);
12762 			if (cr == NULL) {
12763 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12764 				if (mp != NULL)
12765 					qreply(q, mp);
12766 				return;
12767 			}
12768 
12769 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12770 				proto_str = "Bad SNMPCOM request?";
12771 				goto protonak;
12772 			}
12773 			return;
12774 		default:
12775 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12776 			    (int)*(uint_t *)mp->b_rptr));
12777 			freemsg(mp);
12778 			return;
12779 		}
12780 	default:
12781 		break;
12782 	}
12783 	if (q->q_next) {
12784 		putnext(q, mp);
12785 	} else
12786 		freemsg(mp);
12787 	return;
12788 
12789 nak:
12790 	iocp->ioc_error = EINVAL;
12791 	mp->b_datap->db_type = M_IOCNAK;
12792 	iocp->ioc_count = 0;
12793 	qreply(q, mp);
12794 	return;
12795 
12796 protonak:
12797 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12798 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12799 		qreply(q, mp);
12800 }
12801 
12802 /*
12803  * Process IP options in an outbound packet.  Verify that the nexthop in a
12804  * strict source route is onlink.
12805  * Returns non-zero if something fails in which case an ICMP error has been
12806  * sent and mp freed.
12807  *
12808  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12809  */
12810 int
12811 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12812 {
12813 	ipoptp_t	opts;
12814 	uchar_t		*opt;
12815 	uint8_t		optval;
12816 	uint8_t		optlen;
12817 	ipaddr_t	dst;
12818 	intptr_t	code = 0;
12819 	ire_t		*ire;
12820 	ip_stack_t	*ipst = ixa->ixa_ipst;
12821 	ip_recv_attr_t	iras;
12822 
12823 	ip2dbg(("ip_output_options\n"));
12824 
12825 	dst = ipha->ipha_dst;
12826 	for (optval = ipoptp_first(&opts, ipha);
12827 	    optval != IPOPT_EOL;
12828 	    optval = ipoptp_next(&opts)) {
12829 		opt = opts.ipoptp_cur;
12830 		optlen = opts.ipoptp_len;
12831 		ip2dbg(("ip_output_options: opt %d, len %d\n",
12832 		    optval, optlen));
12833 		switch (optval) {
12834 			uint32_t off;
12835 		case IPOPT_SSRR:
12836 		case IPOPT_LSRR:
12837 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12838 				ip1dbg((
12839 				    "ip_output_options: bad option offset\n"));
12840 				code = (char *)&opt[IPOPT_OLEN] -
12841 				    (char *)ipha;
12842 				goto param_prob;
12843 			}
12844 			off = opt[IPOPT_OFFSET];
12845 			ip1dbg(("ip_output_options: next hop 0x%x\n",
12846 			    ntohl(dst)));
12847 			/*
12848 			 * For strict: verify that dst is directly
12849 			 * reachable.
12850 			 */
12851 			if (optval == IPOPT_SSRR) {
12852 				ire = ire_ftable_lookup_v4(dst, 0, 0,
12853 				    IRE_IF_ALL, NULL, ALL_ZONES, ixa->ixa_tsl,
12854 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
12855 				    NULL);
12856 				if (ire == NULL) {
12857 					ip1dbg(("ip_output_options: SSRR not"
12858 					    " directly reachable: 0x%x\n",
12859 					    ntohl(dst)));
12860 					goto bad_src_route;
12861 				}
12862 				ire_refrele(ire);
12863 			}
12864 			break;
12865 		case IPOPT_RR:
12866 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12867 				ip1dbg((
12868 				    "ip_output_options: bad option offset\n"));
12869 				code = (char *)&opt[IPOPT_OLEN] -
12870 				    (char *)ipha;
12871 				goto param_prob;
12872 			}
12873 			break;
12874 		case IPOPT_TS:
12875 			/*
12876 			 * Verify that length >=5 and that there is either
12877 			 * room for another timestamp or that the overflow
12878 			 * counter is not maxed out.
12879 			 */
12880 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
12881 			if (optlen < IPOPT_MINLEN_IT) {
12882 				goto param_prob;
12883 			}
12884 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12885 				ip1dbg((
12886 				    "ip_output_options: bad option offset\n"));
12887 				code = (char *)&opt[IPOPT_OFFSET] -
12888 				    (char *)ipha;
12889 				goto param_prob;
12890 			}
12891 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12892 			case IPOPT_TS_TSONLY:
12893 				off = IPOPT_TS_TIMELEN;
12894 				break;
12895 			case IPOPT_TS_TSANDADDR:
12896 			case IPOPT_TS_PRESPEC:
12897 			case IPOPT_TS_PRESPEC_RFC791:
12898 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12899 				break;
12900 			default:
12901 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
12902 				    (char *)ipha;
12903 				goto param_prob;
12904 			}
12905 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
12906 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
12907 				/*
12908 				 * No room and the overflow counter is 15
12909 				 * already.
12910 				 */
12911 				goto param_prob;
12912 			}
12913 			break;
12914 		}
12915 	}
12916 
12917 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
12918 		return (0);
12919 
12920 	ip1dbg(("ip_output_options: error processing IP options."));
12921 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
12922 
12923 param_prob:
12924 	bzero(&iras, sizeof (iras));
12925 	iras.ira_ill = iras.ira_rill = ill;
12926 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12927 	iras.ira_rifindex = iras.ira_ruifindex;
12928 	iras.ira_flags = IRAF_IS_IPV4;
12929 
12930 	ip_drop_output("ip_output_options", mp, ill);
12931 	icmp_param_problem(mp, (uint8_t)code, &iras);
12932 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12933 	return (-1);
12934 
12935 bad_src_route:
12936 	bzero(&iras, sizeof (iras));
12937 	iras.ira_ill = iras.ira_rill = ill;
12938 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12939 	iras.ira_rifindex = iras.ira_ruifindex;
12940 	iras.ira_flags = IRAF_IS_IPV4;
12941 
12942 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
12943 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
12944 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12945 	return (-1);
12946 }
12947 
12948 /*
12949  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
12950  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
12951  * thru /etc/system.
12952  */
12953 #define	CONN_MAXDRAINCNT	64
12954 
12955 static void
12956 conn_drain_init(ip_stack_t *ipst)
12957 {
12958 	int i, j;
12959 	idl_tx_list_t *itl_tx;
12960 
12961 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
12962 
12963 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
12964 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
12965 		/*
12966 		 * Default value of the number of drainers is the
12967 		 * number of cpus, subject to maximum of 8 drainers.
12968 		 */
12969 		if (boot_max_ncpus != -1)
12970 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
12971 		else
12972 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
12973 	}
12974 
12975 	ipst->ips_idl_tx_list =
12976 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
12977 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
12978 		itl_tx =  &ipst->ips_idl_tx_list[i];
12979 		itl_tx->txl_drain_list =
12980 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
12981 		    sizeof (idl_t), KM_SLEEP);
12982 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
12983 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
12984 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
12985 			    MUTEX_DEFAULT, NULL);
12986 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
12987 		}
12988 	}
12989 }
12990 
12991 static void
12992 conn_drain_fini(ip_stack_t *ipst)
12993 {
12994 	int i;
12995 	idl_tx_list_t *itl_tx;
12996 
12997 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
12998 		itl_tx =  &ipst->ips_idl_tx_list[i];
12999 		kmem_free(itl_tx->txl_drain_list,
13000 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13001 	}
13002 	kmem_free(ipst->ips_idl_tx_list,
13003 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13004 	ipst->ips_idl_tx_list = NULL;
13005 }
13006 
13007 /*
13008  * Flow control has blocked us from proceeding.  Insert the given conn in one
13009  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13010  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13011  * will call conn_walk_drain().  See the flow control notes at the top of this
13012  * file for more details.
13013  */
13014 void
13015 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13016 {
13017 	idl_t	*idl = tx_list->txl_drain_list;
13018 	uint_t	index;
13019 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13020 
13021 	mutex_enter(&connp->conn_lock);
13022 	if (connp->conn_state_flags & CONN_CLOSING) {
13023 		/*
13024 		 * The conn is closing as a result of which CONN_CLOSING
13025 		 * is set. Return.
13026 		 */
13027 		mutex_exit(&connp->conn_lock);
13028 		return;
13029 	} else if (connp->conn_idl == NULL) {
13030 		/*
13031 		 * Assign the next drain list round robin. We dont' use
13032 		 * a lock, and thus it may not be strictly round robin.
13033 		 * Atomicity of load/stores is enough to make sure that
13034 		 * conn_drain_list_index is always within bounds.
13035 		 */
13036 		index = tx_list->txl_drain_index;
13037 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13038 		connp->conn_idl = &tx_list->txl_drain_list[index];
13039 		index++;
13040 		if (index == ipst->ips_conn_drain_list_cnt)
13041 			index = 0;
13042 		tx_list->txl_drain_index = index;
13043 	} else {
13044 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13045 	}
13046 	mutex_exit(&connp->conn_lock);
13047 
13048 	idl = connp->conn_idl;
13049 	mutex_enter(&idl->idl_lock);
13050 	if ((connp->conn_drain_prev != NULL) ||
13051 	    (connp->conn_state_flags & CONN_CLOSING)) {
13052 		/*
13053 		 * The conn is either already in the drain list or closing.
13054 		 * (We needed to check for CONN_CLOSING again since close can
13055 		 * sneak in between dropping conn_lock and acquiring idl_lock.)
13056 		 */
13057 		mutex_exit(&idl->idl_lock);
13058 		return;
13059 	}
13060 
13061 	/*
13062 	 * The conn is not in the drain list. Insert it at the
13063 	 * tail of the drain list. The drain list is circular
13064 	 * and doubly linked. idl_conn points to the 1st element
13065 	 * in the list.
13066 	 */
13067 	if (idl->idl_conn == NULL) {
13068 		idl->idl_conn = connp;
13069 		connp->conn_drain_next = connp;
13070 		connp->conn_drain_prev = connp;
13071 	} else {
13072 		conn_t *head = idl->idl_conn;
13073 
13074 		connp->conn_drain_next = head;
13075 		connp->conn_drain_prev = head->conn_drain_prev;
13076 		head->conn_drain_prev->conn_drain_next = connp;
13077 		head->conn_drain_prev = connp;
13078 	}
13079 	/*
13080 	 * For non streams based sockets assert flow control.
13081 	 */
13082 	conn_setqfull(connp, NULL);
13083 	mutex_exit(&idl->idl_lock);
13084 }
13085 
13086 static void
13087 conn_drain_remove(conn_t *connp)
13088 {
13089 	idl_t *idl = connp->conn_idl;
13090 
13091 	if (idl != NULL) {
13092 		/*
13093 		 * Remove ourself from the drain list.
13094 		 */
13095 		if (connp->conn_drain_next == connp) {
13096 			/* Singleton in the list */
13097 			ASSERT(connp->conn_drain_prev == connp);
13098 			idl->idl_conn = NULL;
13099 		} else {
13100 			connp->conn_drain_prev->conn_drain_next =
13101 			    connp->conn_drain_next;
13102 			connp->conn_drain_next->conn_drain_prev =
13103 			    connp->conn_drain_prev;
13104 			if (idl->idl_conn == connp)
13105 				idl->idl_conn = connp->conn_drain_next;
13106 		}
13107 
13108 		/*
13109 		 * NOTE: because conn_idl is associated with a specific drain
13110 		 * list which in turn is tied to the index the TX ring
13111 		 * (txl_cookie) hashes to, and because the TX ring can change
13112 		 * over the lifetime of the conn_t, we must clear conn_idl so
13113 		 * a subsequent conn_drain_insert() will set conn_idl again
13114 		 * based on the latest txl_cookie.
13115 		 */
13116 		connp->conn_idl = NULL;
13117 	}
13118 	connp->conn_drain_next = NULL;
13119 	connp->conn_drain_prev = NULL;
13120 
13121 	conn_clrqfull(connp, NULL);
13122 	/*
13123 	 * For streams based sockets open up flow control.
13124 	 */
13125 	if (!IPCL_IS_NONSTR(connp))
13126 		enableok(connp->conn_wq);
13127 }
13128 
13129 /*
13130  * This conn is closing, and we are called from ip_close. OR
13131  * this conn is draining because flow-control on the ill has been relieved.
13132  *
13133  * We must also need to remove conn's on this idl from the list, and also
13134  * inform the sockfs upcalls about the change in flow-control.
13135  */
13136 static void
13137 conn_drain(conn_t *connp, boolean_t closing)
13138 {
13139 	idl_t *idl;
13140 	conn_t *next_connp;
13141 
13142 	/*
13143 	 * connp->conn_idl is stable at this point, and no lock is needed
13144 	 * to check it. If we are called from ip_close, close has already
13145 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13146 	 * called us only because conn_idl is non-null. If we are called thru
13147 	 * service, conn_idl could be null, but it cannot change because
13148 	 * service is single-threaded per queue, and there cannot be another
13149 	 * instance of service trying to call conn_drain_insert on this conn
13150 	 * now.
13151 	 */
13152 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13153 
13154 	/*
13155 	 * If the conn doesn't exist or is not on a drain list, bail.
13156 	 */
13157 	if (connp == NULL || connp->conn_idl == NULL ||
13158 	    connp->conn_drain_prev == NULL) {
13159 		return;
13160 	}
13161 
13162 	idl = connp->conn_idl;
13163 	ASSERT(MUTEX_HELD(&idl->idl_lock));
13164 
13165 	if (!closing) {
13166 		next_connp = connp->conn_drain_next;
13167 		while (next_connp != connp) {
13168 			conn_t *delconnp = next_connp;
13169 
13170 			next_connp = next_connp->conn_drain_next;
13171 			conn_drain_remove(delconnp);
13172 		}
13173 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13174 	}
13175 	conn_drain_remove(connp);
13176 }
13177 
13178 /*
13179  * Write service routine. Shared perimeter entry point.
13180  * The device queue's messages has fallen below the low water mark and STREAMS
13181  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13182  * each waiting conn.
13183  */
13184 void
13185 ip_wsrv(queue_t *q)
13186 {
13187 	ill_t	*ill;
13188 
13189 	ill = (ill_t *)q->q_ptr;
13190 	if (ill->ill_state_flags == 0) {
13191 		ip_stack_t *ipst = ill->ill_ipst;
13192 
13193 		/*
13194 		 * The device flow control has opened up.
13195 		 * Walk through conn drain lists and qenable the
13196 		 * first conn in each list. This makes sense only
13197 		 * if the stream is fully plumbed and setup.
13198 		 * Hence the ill_state_flags check above.
13199 		 */
13200 		ip1dbg(("ip_wsrv: walking\n"));
13201 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13202 		enableok(ill->ill_wq);
13203 	}
13204 }
13205 
13206 /*
13207  * Callback to disable flow control in IP.
13208  *
13209  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13210  * is enabled.
13211  *
13212  * When MAC_TX() is not able to send any more packets, dld sets its queue
13213  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13214  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13215  * function and wakes up corresponding mac worker threads, which in turn
13216  * calls this callback function, and disables flow control.
13217  */
13218 void
13219 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13220 {
13221 	ill_t *ill = (ill_t *)arg;
13222 	ip_stack_t *ipst = ill->ill_ipst;
13223 	idl_tx_list_t *idl_txl;
13224 
13225 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13226 	mutex_enter(&idl_txl->txl_lock);
13227 	/* add code to to set a flag to indicate idl_txl is enabled */
13228 	conn_walk_drain(ipst, idl_txl);
13229 	mutex_exit(&idl_txl->txl_lock);
13230 }
13231 
13232 /*
13233  * Flow control has been relieved and STREAMS has backenabled us; drain
13234  * all the conn lists on `tx_list'.
13235  */
13236 static void
13237 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13238 {
13239 	int i;
13240 	idl_t *idl;
13241 
13242 	IP_STAT(ipst, ip_conn_walk_drain);
13243 
13244 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13245 		idl = &tx_list->txl_drain_list[i];
13246 		mutex_enter(&idl->idl_lock);
13247 		conn_drain(idl->idl_conn, B_FALSE);
13248 		mutex_exit(&idl->idl_lock);
13249 	}
13250 }
13251 
13252 /*
13253  * Determine if the ill and multicast aspects of that packets
13254  * "matches" the conn.
13255  */
13256 boolean_t
13257 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13258 {
13259 	ill_t		*ill = ira->ira_rill;
13260 	zoneid_t	zoneid = ira->ira_zoneid;
13261 	uint_t		in_ifindex;
13262 	ipaddr_t	dst, src;
13263 
13264 	dst = ipha->ipha_dst;
13265 	src = ipha->ipha_src;
13266 
13267 	/*
13268 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13269 	 * unicast, broadcast and multicast reception to
13270 	 * conn_incoming_ifindex.
13271 	 * conn_wantpacket is called for unicast, broadcast and
13272 	 * multicast packets.
13273 	 */
13274 	in_ifindex = connp->conn_incoming_ifindex;
13275 
13276 	/* mpathd can bind to the under IPMP interface, which we allow */
13277 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13278 		if (!IS_UNDER_IPMP(ill))
13279 			return (B_FALSE);
13280 
13281 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13282 			return (B_FALSE);
13283 	}
13284 
13285 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13286 		return (B_FALSE);
13287 
13288 	if (!(ira->ira_flags & IRAF_MULTICAST))
13289 		return (B_TRUE);
13290 
13291 	if (connp->conn_multi_router) {
13292 		/* multicast packet and multicast router socket: send up */
13293 		return (B_TRUE);
13294 	}
13295 
13296 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13297 	    ipha->ipha_protocol == IPPROTO_RSVP)
13298 		return (B_TRUE);
13299 
13300 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13301 }
13302 
13303 void
13304 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13305 {
13306 	if (IPCL_IS_NONSTR(connp)) {
13307 		(*connp->conn_upcalls->su_txq_full)
13308 		    (connp->conn_upper_handle, B_TRUE);
13309 		if (flow_stopped != NULL)
13310 			*flow_stopped = B_TRUE;
13311 	} else {
13312 		queue_t *q = connp->conn_wq;
13313 
13314 		ASSERT(q != NULL);
13315 		if (!(q->q_flag & QFULL)) {
13316 			mutex_enter(QLOCK(q));
13317 			if (!(q->q_flag & QFULL)) {
13318 				/* still need to set QFULL */
13319 				q->q_flag |= QFULL;
13320 				/* set flow_stopped to true under QLOCK */
13321 				if (flow_stopped != NULL)
13322 					*flow_stopped = B_TRUE;
13323 				mutex_exit(QLOCK(q));
13324 			} else {
13325 				/* flow_stopped is left unchanged */
13326 				mutex_exit(QLOCK(q));
13327 			}
13328 		}
13329 	}
13330 }
13331 
13332 void
13333 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13334 {
13335 	if (IPCL_IS_NONSTR(connp)) {
13336 		(*connp->conn_upcalls->su_txq_full)
13337 		    (connp->conn_upper_handle, B_FALSE);
13338 		if (flow_stopped != NULL)
13339 			*flow_stopped = B_FALSE;
13340 	} else {
13341 		queue_t *q = connp->conn_wq;
13342 
13343 		ASSERT(q != NULL);
13344 		if (q->q_flag & QFULL) {
13345 			mutex_enter(QLOCK(q));
13346 			if (q->q_flag & QFULL) {
13347 				q->q_flag &= ~QFULL;
13348 				/* set flow_stopped to false under QLOCK */
13349 				if (flow_stopped != NULL)
13350 					*flow_stopped = B_FALSE;
13351 				mutex_exit(QLOCK(q));
13352 				if (q->q_flag & QWANTW)
13353 					qbackenable(q, 0);
13354 			} else {
13355 				/* flow_stopped is left unchanged */
13356 				mutex_exit(QLOCK(q));
13357 			}
13358 		}
13359 	}
13360 
13361 	mutex_enter(&connp->conn_lock);
13362 	connp->conn_blocked = B_FALSE;
13363 	mutex_exit(&connp->conn_lock);
13364 }
13365 
13366 /*
13367  * Return the length in bytes of the IPv4 headers (base header, label, and
13368  * other IP options) that will be needed based on the
13369  * ip_pkt_t structure passed by the caller.
13370  *
13371  * The returned length does not include the length of the upper level
13372  * protocol (ULP) header.
13373  * The caller needs to check that the length doesn't exceed the max for IPv4.
13374  */
13375 int
13376 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13377 {
13378 	int len;
13379 
13380 	len = IP_SIMPLE_HDR_LENGTH;
13381 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13382 		ASSERT(ipp->ipp_label_len_v4 != 0);
13383 		/* We need to round up here */
13384 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13385 	}
13386 
13387 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13388 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13389 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13390 		len += ipp->ipp_ipv4_options_len;
13391 	}
13392 	return (len);
13393 }
13394 
13395 /*
13396  * All-purpose routine to build an IPv4 header with options based
13397  * on the abstract ip_pkt_t.
13398  *
13399  * The caller has to set the source and destination address as well as
13400  * ipha_length. The caller has to massage any source route and compensate
13401  * for the ULP pseudo-header checksum due to the source route.
13402  */
13403 void
13404 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13405     uint8_t protocol)
13406 {
13407 	ipha_t	*ipha = (ipha_t *)buf;
13408 	uint8_t *cp;
13409 
13410 	/* Initialize IPv4 header */
13411 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13412 	ipha->ipha_length = 0;	/* Caller will set later */
13413 	ipha->ipha_ident = 0;
13414 	ipha->ipha_fragment_offset_and_flags = 0;
13415 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13416 	ipha->ipha_protocol = protocol;
13417 	ipha->ipha_hdr_checksum = 0;
13418 
13419 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13420 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13421 		ipha->ipha_src = ipp->ipp_addr_v4;
13422 
13423 	cp = (uint8_t *)&ipha[1];
13424 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13425 		ASSERT(ipp->ipp_label_len_v4 != 0);
13426 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13427 		cp += ipp->ipp_label_len_v4;
13428 		/* We need to round up here */
13429 		while ((uintptr_t)cp & 0x3) {
13430 			*cp++ = IPOPT_NOP;
13431 		}
13432 	}
13433 
13434 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13435 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13436 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13437 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13438 		cp += ipp->ipp_ipv4_options_len;
13439 	}
13440 	ipha->ipha_version_and_hdr_length =
13441 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13442 
13443 	ASSERT((int)(cp - buf) == buf_len);
13444 }
13445 
13446 /* Allocate the private structure */
13447 static int
13448 ip_priv_alloc(void **bufp)
13449 {
13450 	void	*buf;
13451 
13452 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13453 		return (ENOMEM);
13454 
13455 	*bufp = buf;
13456 	return (0);
13457 }
13458 
13459 /* Function to delete the private structure */
13460 void
13461 ip_priv_free(void *buf)
13462 {
13463 	ASSERT(buf != NULL);
13464 	kmem_free(buf, sizeof (ip_priv_t));
13465 }
13466 
13467 /*
13468  * The entry point for IPPF processing.
13469  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13470  * routine just returns.
13471  *
13472  * When called, ip_process generates an ipp_packet_t structure
13473  * which holds the state information for this packet and invokes the
13474  * the classifier (via ipp_packet_process). The classification, depending on
13475  * configured filters, results in a list of actions for this packet. Invoking
13476  * an action may cause the packet to be dropped, in which case we return NULL.
13477  * proc indicates the callout position for
13478  * this packet and ill is the interface this packet arrived on or will leave
13479  * on (inbound and outbound resp.).
13480  *
13481  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13482  * on the ill corrsponding to the destination IP address.
13483  */
13484 mblk_t *
13485 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13486 {
13487 	ip_priv_t	*priv;
13488 	ipp_action_id_t	aid;
13489 	int		rc = 0;
13490 	ipp_packet_t	*pp;
13491 
13492 	/* If the classifier is not loaded, return  */
13493 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13494 		return (mp);
13495 	}
13496 
13497 	ASSERT(mp != NULL);
13498 
13499 	/* Allocate the packet structure */
13500 	rc = ipp_packet_alloc(&pp, "ip", aid);
13501 	if (rc != 0)
13502 		goto drop;
13503 
13504 	/* Allocate the private structure */
13505 	rc = ip_priv_alloc((void **)&priv);
13506 	if (rc != 0) {
13507 		ipp_packet_free(pp);
13508 		goto drop;
13509 	}
13510 	priv->proc = proc;
13511 	priv->ill_index = ill_get_upper_ifindex(rill);
13512 
13513 	ipp_packet_set_private(pp, priv, ip_priv_free);
13514 	ipp_packet_set_data(pp, mp);
13515 
13516 	/* Invoke the classifier */
13517 	rc = ipp_packet_process(&pp);
13518 	if (pp != NULL) {
13519 		mp = ipp_packet_get_data(pp);
13520 		ipp_packet_free(pp);
13521 		if (rc != 0)
13522 			goto drop;
13523 		return (mp);
13524 	} else {
13525 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13526 		mp = NULL;
13527 	}
13528 drop:
13529 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13530 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13531 		ip_drop_input("ip_process", mp, ill);
13532 	} else {
13533 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13534 		ip_drop_output("ip_process", mp, ill);
13535 	}
13536 	freemsg(mp);
13537 	return (NULL);
13538 }
13539 
13540 /*
13541  * Propagate a multicast group membership operation (add/drop) on
13542  * all the interfaces crossed by the related multirt routes.
13543  * The call is considered successful if the operation succeeds
13544  * on at least one interface.
13545  *
13546  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13547  * multicast addresses with the ire argument being the first one.
13548  * We walk the bucket to find all the of those.
13549  *
13550  * Common to IPv4 and IPv6.
13551  */
13552 static int
13553 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13554     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13555     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13556     mcast_record_t fmode, const in6_addr_t *v6src)
13557 {
13558 	ire_t		*ire_gw;
13559 	irb_t		*irb;
13560 	int		ifindex;
13561 	int		error = 0;
13562 	int		result;
13563 	ip_stack_t	*ipst = ire->ire_ipst;
13564 	ipaddr_t	group;
13565 	boolean_t	isv6;
13566 	int		match_flags;
13567 
13568 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13569 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13570 		isv6 = B_FALSE;
13571 	} else {
13572 		isv6 = B_TRUE;
13573 	}
13574 
13575 	irb = ire->ire_bucket;
13576 	ASSERT(irb != NULL);
13577 
13578 	result = 0;
13579 	irb_refhold(irb);
13580 	for (; ire != NULL; ire = ire->ire_next) {
13581 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13582 			continue;
13583 
13584 		/* We handle -ifp routes by matching on the ill if set */
13585 		match_flags = MATCH_IRE_TYPE;
13586 		if (ire->ire_ill != NULL)
13587 			match_flags |= MATCH_IRE_ILL;
13588 
13589 		if (isv6) {
13590 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13591 				continue;
13592 
13593 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13594 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13595 			    match_flags, 0, ipst, NULL);
13596 		} else {
13597 			if (ire->ire_addr != group)
13598 				continue;
13599 
13600 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13601 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13602 			    match_flags, 0, ipst, NULL);
13603 		}
13604 		/* No interface route exists for the gateway; skip this ire. */
13605 		if (ire_gw == NULL)
13606 			continue;
13607 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13608 			ire_refrele(ire_gw);
13609 			continue;
13610 		}
13611 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13612 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13613 
13614 		/*
13615 		 * The operation is considered a success if
13616 		 * it succeeds at least once on any one interface.
13617 		 */
13618 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13619 		    fmode, v6src);
13620 		if (error == 0)
13621 			result = CGTP_MCAST_SUCCESS;
13622 
13623 		ire_refrele(ire_gw);
13624 	}
13625 	irb_refrele(irb);
13626 	/*
13627 	 * Consider the call as successful if we succeeded on at least
13628 	 * one interface. Otherwise, return the last encountered error.
13629 	 */
13630 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13631 }
13632 
13633 /*
13634  * Return the expected CGTP hooks version number.
13635  */
13636 int
13637 ip_cgtp_filter_supported(void)
13638 {
13639 	return (ip_cgtp_filter_rev);
13640 }
13641 
13642 /*
13643  * CGTP hooks can be registered by invoking this function.
13644  * Checks that the version number matches.
13645  */
13646 int
13647 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13648 {
13649 	netstack_t *ns;
13650 	ip_stack_t *ipst;
13651 
13652 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13653 		return (ENOTSUP);
13654 
13655 	ns = netstack_find_by_stackid(stackid);
13656 	if (ns == NULL)
13657 		return (EINVAL);
13658 	ipst = ns->netstack_ip;
13659 	ASSERT(ipst != NULL);
13660 
13661 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13662 		netstack_rele(ns);
13663 		return (EALREADY);
13664 	}
13665 
13666 	ipst->ips_ip_cgtp_filter_ops = ops;
13667 
13668 	ill_set_inputfn_all(ipst);
13669 
13670 	netstack_rele(ns);
13671 	return (0);
13672 }
13673 
13674 /*
13675  * CGTP hooks can be unregistered by invoking this function.
13676  * Returns ENXIO if there was no registration.
13677  * Returns EBUSY if the ndd variable has not been turned off.
13678  */
13679 int
13680 ip_cgtp_filter_unregister(netstackid_t stackid)
13681 {
13682 	netstack_t *ns;
13683 	ip_stack_t *ipst;
13684 
13685 	ns = netstack_find_by_stackid(stackid);
13686 	if (ns == NULL)
13687 		return (EINVAL);
13688 	ipst = ns->netstack_ip;
13689 	ASSERT(ipst != NULL);
13690 
13691 	if (ipst->ips_ip_cgtp_filter) {
13692 		netstack_rele(ns);
13693 		return (EBUSY);
13694 	}
13695 
13696 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13697 		netstack_rele(ns);
13698 		return (ENXIO);
13699 	}
13700 	ipst->ips_ip_cgtp_filter_ops = NULL;
13701 
13702 	ill_set_inputfn_all(ipst);
13703 
13704 	netstack_rele(ns);
13705 	return (0);
13706 }
13707 
13708 /*
13709  * Check whether there is a CGTP filter registration.
13710  * Returns non-zero if there is a registration, otherwise returns zero.
13711  * Note: returns zero if bad stackid.
13712  */
13713 int
13714 ip_cgtp_filter_is_registered(netstackid_t stackid)
13715 {
13716 	netstack_t *ns;
13717 	ip_stack_t *ipst;
13718 	int ret;
13719 
13720 	ns = netstack_find_by_stackid(stackid);
13721 	if (ns == NULL)
13722 		return (0);
13723 	ipst = ns->netstack_ip;
13724 	ASSERT(ipst != NULL);
13725 
13726 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13727 		ret = 1;
13728 	else
13729 		ret = 0;
13730 
13731 	netstack_rele(ns);
13732 	return (ret);
13733 }
13734 
13735 static int
13736 ip_squeue_switch(int val)
13737 {
13738 	int rval;
13739 
13740 	switch (val) {
13741 	case IP_SQUEUE_ENTER_NODRAIN:
13742 		rval = SQ_NODRAIN;
13743 		break;
13744 	case IP_SQUEUE_ENTER:
13745 		rval = SQ_PROCESS;
13746 		break;
13747 	case IP_SQUEUE_FILL:
13748 	default:
13749 		rval = SQ_FILL;
13750 		break;
13751 	}
13752 	return (rval);
13753 }
13754 
13755 static void *
13756 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13757 {
13758 	kstat_t *ksp;
13759 
13760 	ip_stat_t template = {
13761 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
13762 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
13763 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
13764 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13765 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13766 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13767 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13768 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13769 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13770 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13771 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13772 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13773 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13774 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13775 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13776 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13777 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13778 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13779 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13780 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13781 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13782 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13783 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13784 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13785 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13786 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13787 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13788 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13789 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13790 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13791 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
13792 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
13793 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
13794 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
13795 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
13796 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
13797 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
13798 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
13799 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
13800 	};
13801 
13802 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13803 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13804 	    KSTAT_FLAG_VIRTUAL, stackid);
13805 
13806 	if (ksp == NULL)
13807 		return (NULL);
13808 
13809 	bcopy(&template, ip_statisticsp, sizeof (template));
13810 	ksp->ks_data = (void *)ip_statisticsp;
13811 	ksp->ks_private = (void *)(uintptr_t)stackid;
13812 
13813 	kstat_install(ksp);
13814 	return (ksp);
13815 }
13816 
13817 static void
13818 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13819 {
13820 	if (ksp != NULL) {
13821 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13822 		kstat_delete_netstack(ksp, stackid);
13823 	}
13824 }
13825 
13826 static void *
13827 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13828 {
13829 	kstat_t	*ksp;
13830 
13831 	ip_named_kstat_t template = {
13832 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
13833 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
13834 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
13835 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
13836 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
13837 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
13838 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
13839 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
13840 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
13841 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
13842 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
13843 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
13844 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
13845 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
13846 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
13847 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
13848 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
13849 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
13850 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
13851 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
13852 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
13853 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
13854 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
13855 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
13856 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
13857 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
13858 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
13859 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
13860 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
13861 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
13862 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
13863 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
13864 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
13865 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
13866 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
13867 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
13868 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
13869 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
13870 	};
13871 
13872 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
13873 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
13874 	if (ksp == NULL || ksp->ks_data == NULL)
13875 		return (NULL);
13876 
13877 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
13878 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
13879 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
13880 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
13881 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
13882 
13883 	template.netToMediaEntrySize.value.i32 =
13884 	    sizeof (mib2_ipNetToMediaEntry_t);
13885 
13886 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
13887 
13888 	bcopy(&template, ksp->ks_data, sizeof (template));
13889 	ksp->ks_update = ip_kstat_update;
13890 	ksp->ks_private = (void *)(uintptr_t)stackid;
13891 
13892 	kstat_install(ksp);
13893 	return (ksp);
13894 }
13895 
13896 static void
13897 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
13898 {
13899 	if (ksp != NULL) {
13900 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13901 		kstat_delete_netstack(ksp, stackid);
13902 	}
13903 }
13904 
13905 static int
13906 ip_kstat_update(kstat_t *kp, int rw)
13907 {
13908 	ip_named_kstat_t *ipkp;
13909 	mib2_ipIfStatsEntry_t ipmib;
13910 	ill_walk_context_t ctx;
13911 	ill_t *ill;
13912 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
13913 	netstack_t	*ns;
13914 	ip_stack_t	*ipst;
13915 
13916 	if (kp == NULL || kp->ks_data == NULL)
13917 		return (EIO);
13918 
13919 	if (rw == KSTAT_WRITE)
13920 		return (EACCES);
13921 
13922 	ns = netstack_find_by_stackid(stackid);
13923 	if (ns == NULL)
13924 		return (-1);
13925 	ipst = ns->netstack_ip;
13926 	if (ipst == NULL) {
13927 		netstack_rele(ns);
13928 		return (-1);
13929 	}
13930 	ipkp = (ip_named_kstat_t *)kp->ks_data;
13931 
13932 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
13933 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
13934 	ill = ILL_START_WALK_V4(&ctx, ipst);
13935 	for (; ill != NULL; ill = ill_next(&ctx, ill))
13936 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
13937 	rw_exit(&ipst->ips_ill_g_lock);
13938 
13939 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
13940 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
13941 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
13942 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
13943 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
13944 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
13945 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
13946 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
13947 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
13948 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
13949 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
13950 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
13951 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
13952 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
13953 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
13954 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
13955 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
13956 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
13957 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
13958 
13959 	ipkp->routingDiscards.value.ui32 =	0;
13960 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
13961 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
13962 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
13963 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
13964 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
13965 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
13966 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
13967 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
13968 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
13969 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
13970 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
13971 
13972 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
13973 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
13974 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
13975 
13976 	netstack_rele(ns);
13977 
13978 	return (0);
13979 }
13980 
13981 static void *
13982 icmp_kstat_init(netstackid_t stackid)
13983 {
13984 	kstat_t	*ksp;
13985 
13986 	icmp_named_kstat_t template = {
13987 		{ "inMsgs",		KSTAT_DATA_UINT32 },
13988 		{ "inErrors",		KSTAT_DATA_UINT32 },
13989 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
13990 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
13991 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
13992 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
13993 		{ "inRedirects",	KSTAT_DATA_UINT32 },
13994 		{ "inEchos",		KSTAT_DATA_UINT32 },
13995 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
13996 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
13997 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
13998 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
13999 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14000 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14001 		{ "outErrors",		KSTAT_DATA_UINT32 },
14002 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14003 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14004 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14005 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14006 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14007 		{ "outEchos",		KSTAT_DATA_UINT32 },
14008 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14009 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14010 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14011 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14012 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14013 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14014 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14015 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14016 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14017 		{ "outDrops",		KSTAT_DATA_UINT32 },
14018 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14019 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14020 	};
14021 
14022 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14023 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14024 	if (ksp == NULL || ksp->ks_data == NULL)
14025 		return (NULL);
14026 
14027 	bcopy(&template, ksp->ks_data, sizeof (template));
14028 
14029 	ksp->ks_update = icmp_kstat_update;
14030 	ksp->ks_private = (void *)(uintptr_t)stackid;
14031 
14032 	kstat_install(ksp);
14033 	return (ksp);
14034 }
14035 
14036 static void
14037 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14038 {
14039 	if (ksp != NULL) {
14040 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14041 		kstat_delete_netstack(ksp, stackid);
14042 	}
14043 }
14044 
14045 static int
14046 icmp_kstat_update(kstat_t *kp, int rw)
14047 {
14048 	icmp_named_kstat_t *icmpkp;
14049 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14050 	netstack_t	*ns;
14051 	ip_stack_t	*ipst;
14052 
14053 	if ((kp == NULL) || (kp->ks_data == NULL))
14054 		return (EIO);
14055 
14056 	if (rw == KSTAT_WRITE)
14057 		return (EACCES);
14058 
14059 	ns = netstack_find_by_stackid(stackid);
14060 	if (ns == NULL)
14061 		return (-1);
14062 	ipst = ns->netstack_ip;
14063 	if (ipst == NULL) {
14064 		netstack_rele(ns);
14065 		return (-1);
14066 	}
14067 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14068 
14069 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14070 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14071 	icmpkp->inDestUnreachs.value.ui32 =
14072 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14073 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14074 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14075 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14076 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14077 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14078 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14079 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14080 	icmpkp->inTimestampReps.value.ui32 =
14081 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14082 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14083 	icmpkp->inAddrMaskReps.value.ui32 =
14084 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14085 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14086 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14087 	icmpkp->outDestUnreachs.value.ui32 =
14088 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14089 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14090 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14091 	icmpkp->outSrcQuenchs.value.ui32 =
14092 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14093 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14094 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14095 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14096 	icmpkp->outTimestamps.value.ui32 =
14097 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14098 	icmpkp->outTimestampReps.value.ui32 =
14099 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14100 	icmpkp->outAddrMasks.value.ui32 =
14101 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14102 	icmpkp->outAddrMaskReps.value.ui32 =
14103 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14104 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14105 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14106 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14107 	icmpkp->outFragNeeded.value.ui32 =
14108 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14109 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14110 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14111 	icmpkp->inBadRedirects.value.ui32 =
14112 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14113 
14114 	netstack_rele(ns);
14115 	return (0);
14116 }
14117 
14118 /*
14119  * This is the fanout function for raw socket opened for SCTP.  Note
14120  * that it is called after SCTP checks that there is no socket which
14121  * wants a packet.  Then before SCTP handles this out of the blue packet,
14122  * this function is called to see if there is any raw socket for SCTP.
14123  * If there is and it is bound to the correct address, the packet will
14124  * be sent to that socket.  Note that only one raw socket can be bound to
14125  * a port.  This is assured in ipcl_sctp_hash_insert();
14126  */
14127 void
14128 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14129     ip_recv_attr_t *ira)
14130 {
14131 	conn_t		*connp;
14132 	queue_t		*rq;
14133 	boolean_t	secure;
14134 	ill_t		*ill = ira->ira_ill;
14135 	ip_stack_t	*ipst = ill->ill_ipst;
14136 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14137 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14138 	iaflags_t	iraflags = ira->ira_flags;
14139 	ill_t		*rill = ira->ira_rill;
14140 
14141 	secure = iraflags & IRAF_IPSEC_SECURE;
14142 
14143 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14144 	    ira, ipst);
14145 	if (connp == NULL) {
14146 		/*
14147 		 * Although raw sctp is not summed, OOB chunks must be.
14148 		 * Drop the packet here if the sctp checksum failed.
14149 		 */
14150 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14151 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
14152 			freemsg(mp);
14153 			return;
14154 		}
14155 		ira->ira_ill = ira->ira_rill = NULL;
14156 		sctp_ootb_input(mp, ira, ipst);
14157 		ira->ira_ill = ill;
14158 		ira->ira_rill = rill;
14159 		return;
14160 	}
14161 	rq = connp->conn_rq;
14162 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14163 		CONN_DEC_REF(connp);
14164 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14165 		freemsg(mp);
14166 		return;
14167 	}
14168 	if (((iraflags & IRAF_IS_IPV4) ?
14169 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14170 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14171 	    secure) {
14172 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14173 		    ip6h, ira);
14174 		if (mp == NULL) {
14175 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14176 			/* Note that mp is NULL */
14177 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14178 			CONN_DEC_REF(connp);
14179 			return;
14180 		}
14181 	}
14182 
14183 	if (iraflags & IRAF_ICMP_ERROR) {
14184 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14185 	} else {
14186 		ill_t *rill = ira->ira_rill;
14187 
14188 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14189 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14190 		ira->ira_ill = ira->ira_rill = NULL;
14191 		(connp->conn_recv)(connp, mp, NULL, ira);
14192 		ira->ira_ill = ill;
14193 		ira->ira_rill = rill;
14194 	}
14195 	CONN_DEC_REF(connp);
14196 }
14197 
14198 /*
14199  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14200  * header before the ip payload.
14201  */
14202 static void
14203 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14204 {
14205 	int len = (mp->b_wptr - mp->b_rptr);
14206 	mblk_t *ip_mp;
14207 
14208 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14209 	if (is_fp_mp || len != fp_mp_len) {
14210 		if (len > fp_mp_len) {
14211 			/*
14212 			 * fastpath header and ip header in the first mblk
14213 			 */
14214 			mp->b_rptr += fp_mp_len;
14215 		} else {
14216 			/*
14217 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14218 			 * attach the fastpath header before ip header.
14219 			 */
14220 			ip_mp = mp->b_cont;
14221 			freeb(mp);
14222 			mp = ip_mp;
14223 			mp->b_rptr += (fp_mp_len - len);
14224 		}
14225 	} else {
14226 		ip_mp = mp->b_cont;
14227 		freeb(mp);
14228 		mp = ip_mp;
14229 	}
14230 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14231 	freemsg(mp);
14232 }
14233 
14234 /*
14235  * Normal post fragmentation function.
14236  *
14237  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14238  * using the same state machine.
14239  *
14240  * We return an error on failure. In particular we return EWOULDBLOCK
14241  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14242  * (currently by canputnext failure resulting in backenabling from GLD.)
14243  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14244  * indication that they can flow control until ip_wsrv() tells then to restart.
14245  *
14246  * If the nce passed by caller is incomplete, this function
14247  * queues the packet and if necessary, sends ARP request and bails.
14248  * If the Neighbor Cache passed is fully resolved, we simply prepend
14249  * the link-layer header to the packet, do ipsec hw acceleration
14250  * work if necessary, and send the packet out on the wire.
14251  */
14252 /* ARGSUSED6 */
14253 int
14254 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14255     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14256 {
14257 	queue_t		*wq;
14258 	ill_t		*ill = nce->nce_ill;
14259 	ip_stack_t	*ipst = ill->ill_ipst;
14260 	uint64_t	delta;
14261 	boolean_t	isv6 = ill->ill_isv6;
14262 	boolean_t	fp_mp;
14263 	ncec_t		*ncec = nce->nce_common;
14264 	int64_t		now = LBOLT_FASTPATH64;
14265 	boolean_t	is_probe;
14266 
14267 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14268 
14269 	ASSERT(mp != NULL);
14270 	ASSERT(mp->b_datap->db_type == M_DATA);
14271 	ASSERT(pkt_len == msgdsize(mp));
14272 
14273 	/*
14274 	 * If we have already been here and are coming back after ARP/ND.
14275 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14276 	 * in that case since they have seen the packet when it came here
14277 	 * the first time.
14278 	 */
14279 	if (ixaflags & IXAF_NO_TRACE)
14280 		goto sendit;
14281 
14282 	if (ixaflags & IXAF_IS_IPV4) {
14283 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14284 
14285 		ASSERT(!isv6);
14286 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14287 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14288 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14289 			int	error;
14290 
14291 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14292 			    ipst->ips_ipv4firewall_physical_out,
14293 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14294 			DTRACE_PROBE1(ip4__physical__out__end,
14295 			    mblk_t *, mp);
14296 			if (mp == NULL)
14297 				return (error);
14298 
14299 			/* The length could have changed */
14300 			pkt_len = msgdsize(mp);
14301 		}
14302 		if (ipst->ips_ip4_observe.he_interested) {
14303 			/*
14304 			 * Note that for TX the zoneid is the sending
14305 			 * zone, whether or not MLP is in play.
14306 			 * Since the szone argument is the IP zoneid (i.e.,
14307 			 * zero for exclusive-IP zones) and ipobs wants
14308 			 * the system zoneid, we map it here.
14309 			 */
14310 			szone = IP_REAL_ZONEID(szone, ipst);
14311 
14312 			/*
14313 			 * On the outbound path the destination zone will be
14314 			 * unknown as we're sending this packet out on the
14315 			 * wire.
14316 			 */
14317 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14318 			    ill, ipst);
14319 		}
14320 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14321 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14322 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14323 	} else {
14324 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14325 
14326 		ASSERT(isv6);
14327 		ASSERT(pkt_len ==
14328 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14329 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14330 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14331 			int	error;
14332 
14333 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14334 			    ipst->ips_ipv6firewall_physical_out,
14335 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14336 			DTRACE_PROBE1(ip6__physical__out__end,
14337 			    mblk_t *, mp);
14338 			if (mp == NULL)
14339 				return (error);
14340 
14341 			/* The length could have changed */
14342 			pkt_len = msgdsize(mp);
14343 		}
14344 		if (ipst->ips_ip6_observe.he_interested) {
14345 			/* See above */
14346 			szone = IP_REAL_ZONEID(szone, ipst);
14347 
14348 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14349 			    ill, ipst);
14350 		}
14351 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14352 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14353 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14354 	}
14355 
14356 sendit:
14357 	/*
14358 	 * We check the state without a lock because the state can never
14359 	 * move "backwards" to initial or incomplete.
14360 	 */
14361 	switch (ncec->ncec_state) {
14362 	case ND_REACHABLE:
14363 	case ND_STALE:
14364 	case ND_DELAY:
14365 	case ND_PROBE:
14366 		mp = ip_xmit_attach_llhdr(mp, nce);
14367 		if (mp == NULL) {
14368 			/*
14369 			 * ip_xmit_attach_llhdr has increased
14370 			 * ipIfStatsOutDiscards and called ip_drop_output()
14371 			 */
14372 			return (ENOBUFS);
14373 		}
14374 		/*
14375 		 * check if nce_fastpath completed and we tagged on a
14376 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14377 		 */
14378 		fp_mp = (mp->b_datap->db_type == M_DATA);
14379 
14380 		if (fp_mp &&
14381 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14382 			ill_dld_direct_t *idd;
14383 
14384 			idd = &ill->ill_dld_capab->idc_direct;
14385 			/*
14386 			 * Send the packet directly to DLD, where it
14387 			 * may be queued depending on the availability
14388 			 * of transmit resources at the media layer.
14389 			 * Return value should be taken into
14390 			 * account and flow control the TCP.
14391 			 */
14392 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14393 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14394 			    pkt_len);
14395 
14396 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14397 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14398 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14399 			} else {
14400 				uintptr_t cookie;
14401 
14402 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14403 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14404 					if (ixacookie != NULL)
14405 						*ixacookie = cookie;
14406 					return (EWOULDBLOCK);
14407 				}
14408 			}
14409 		} else {
14410 			wq = ill->ill_wq;
14411 
14412 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14413 			    !canputnext(wq)) {
14414 				if (ixacookie != NULL)
14415 					*ixacookie = 0;
14416 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14417 				    nce->nce_fp_mp != NULL ?
14418 				    MBLKL(nce->nce_fp_mp) : 0);
14419 				return (EWOULDBLOCK);
14420 			}
14421 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14422 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14423 			    pkt_len);
14424 			putnext(wq, mp);
14425 		}
14426 
14427 		/*
14428 		 * The rest of this function implements Neighbor Unreachability
14429 		 * detection. Determine if the ncec is eligible for NUD.
14430 		 */
14431 		if (ncec->ncec_flags & NCE_F_NONUD)
14432 			return (0);
14433 
14434 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14435 
14436 		/*
14437 		 * Check for upper layer advice
14438 		 */
14439 		if (ixaflags & IXAF_REACH_CONF) {
14440 			timeout_id_t tid;
14441 
14442 			/*
14443 			 * It should be o.k. to check the state without
14444 			 * a lock here, at most we lose an advice.
14445 			 */
14446 			ncec->ncec_last = TICK_TO_MSEC(now);
14447 			if (ncec->ncec_state != ND_REACHABLE) {
14448 				mutex_enter(&ncec->ncec_lock);
14449 				ncec->ncec_state = ND_REACHABLE;
14450 				tid = ncec->ncec_timeout_id;
14451 				ncec->ncec_timeout_id = 0;
14452 				mutex_exit(&ncec->ncec_lock);
14453 				(void) untimeout(tid);
14454 				if (ip_debug > 2) {
14455 					/* ip1dbg */
14456 					pr_addr_dbg("ip_xmit: state"
14457 					    " for %s changed to"
14458 					    " REACHABLE\n", AF_INET6,
14459 					    &ncec->ncec_addr);
14460 				}
14461 			}
14462 			return (0);
14463 		}
14464 
14465 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14466 		ip1dbg(("ip_xmit: delta = %" PRId64
14467 		    " ill_reachable_time = %d \n", delta,
14468 		    ill->ill_reachable_time));
14469 		if (delta > (uint64_t)ill->ill_reachable_time) {
14470 			mutex_enter(&ncec->ncec_lock);
14471 			switch (ncec->ncec_state) {
14472 			case ND_REACHABLE:
14473 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14474 				/* FALLTHROUGH */
14475 			case ND_STALE:
14476 				/*
14477 				 * ND_REACHABLE is identical to
14478 				 * ND_STALE in this specific case. If
14479 				 * reachable time has expired for this
14480 				 * neighbor (delta is greater than
14481 				 * reachable time), conceptually, the
14482 				 * neighbor cache is no longer in
14483 				 * REACHABLE state, but already in
14484 				 * STALE state.  So the correct
14485 				 * transition here is to ND_DELAY.
14486 				 */
14487 				ncec->ncec_state = ND_DELAY;
14488 				mutex_exit(&ncec->ncec_lock);
14489 				nce_restart_timer(ncec,
14490 				    ipst->ips_delay_first_probe_time);
14491 				if (ip_debug > 3) {
14492 					/* ip2dbg */
14493 					pr_addr_dbg("ip_xmit: state"
14494 					    " for %s changed to"
14495 					    " DELAY\n", AF_INET6,
14496 					    &ncec->ncec_addr);
14497 				}
14498 				break;
14499 			case ND_DELAY:
14500 			case ND_PROBE:
14501 				mutex_exit(&ncec->ncec_lock);
14502 				/* Timers have already started */
14503 				break;
14504 			case ND_UNREACHABLE:
14505 				/*
14506 				 * nce_timer has detected that this ncec
14507 				 * is unreachable and initiated deleting
14508 				 * this ncec.
14509 				 * This is a harmless race where we found the
14510 				 * ncec before it was deleted and have
14511 				 * just sent out a packet using this
14512 				 * unreachable ncec.
14513 				 */
14514 				mutex_exit(&ncec->ncec_lock);
14515 				break;
14516 			default:
14517 				ASSERT(0);
14518 				mutex_exit(&ncec->ncec_lock);
14519 			}
14520 		}
14521 		return (0);
14522 
14523 	case ND_INCOMPLETE:
14524 		/*
14525 		 * the state could have changed since we didn't hold the lock.
14526 		 * Re-verify state under lock.
14527 		 */
14528 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14529 		mutex_enter(&ncec->ncec_lock);
14530 		if (NCE_ISREACHABLE(ncec)) {
14531 			mutex_exit(&ncec->ncec_lock);
14532 			goto sendit;
14533 		}
14534 		/* queue the packet */
14535 		nce_queue_mp(ncec, mp, is_probe);
14536 		mutex_exit(&ncec->ncec_lock);
14537 		DTRACE_PROBE2(ip__xmit__incomplete,
14538 		    (ncec_t *), ncec, (mblk_t *), mp);
14539 		return (0);
14540 
14541 	case ND_INITIAL:
14542 		/*
14543 		 * State could have changed since we didn't hold the lock, so
14544 		 * re-verify state.
14545 		 */
14546 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14547 		mutex_enter(&ncec->ncec_lock);
14548 		if (NCE_ISREACHABLE(ncec))  {
14549 			mutex_exit(&ncec->ncec_lock);
14550 			goto sendit;
14551 		}
14552 		nce_queue_mp(ncec, mp, is_probe);
14553 		if (ncec->ncec_state == ND_INITIAL) {
14554 			ncec->ncec_state = ND_INCOMPLETE;
14555 			mutex_exit(&ncec->ncec_lock);
14556 			/*
14557 			 * figure out the source we want to use
14558 			 * and resolve it.
14559 			 */
14560 			ip_ndp_resolve(ncec);
14561 		} else  {
14562 			mutex_exit(&ncec->ncec_lock);
14563 		}
14564 		return (0);
14565 
14566 	case ND_UNREACHABLE:
14567 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14568 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14569 		    mp, ill);
14570 		freemsg(mp);
14571 		return (0);
14572 
14573 	default:
14574 		ASSERT(0);
14575 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14576 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14577 		    mp, ill);
14578 		freemsg(mp);
14579 		return (ENETUNREACH);
14580 	}
14581 }
14582 
14583 /*
14584  * Return B_TRUE if the buffers differ in length or content.
14585  * This is used for comparing extension header buffers.
14586  * Note that an extension header would be declared different
14587  * even if all that changed was the next header value in that header i.e.
14588  * what really changed is the next extension header.
14589  */
14590 boolean_t
14591 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14592     uint_t blen)
14593 {
14594 	if (!b_valid)
14595 		blen = 0;
14596 
14597 	if (alen != blen)
14598 		return (B_TRUE);
14599 	if (alen == 0)
14600 		return (B_FALSE);	/* Both zero length */
14601 	return (bcmp(abuf, bbuf, alen));
14602 }
14603 
14604 /*
14605  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14606  * Return B_FALSE if memory allocation fails - don't change any state!
14607  */
14608 boolean_t
14609 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14610     const void *src, uint_t srclen)
14611 {
14612 	void *dst;
14613 
14614 	if (!src_valid)
14615 		srclen = 0;
14616 
14617 	ASSERT(*dstlenp == 0);
14618 	if (src != NULL && srclen != 0) {
14619 		dst = mi_alloc(srclen, BPRI_MED);
14620 		if (dst == NULL)
14621 			return (B_FALSE);
14622 	} else {
14623 		dst = NULL;
14624 	}
14625 	if (*dstp != NULL)
14626 		mi_free(*dstp);
14627 	*dstp = dst;
14628 	*dstlenp = dst == NULL ? 0 : srclen;
14629 	return (B_TRUE);
14630 }
14631 
14632 /*
14633  * Replace what is in *dst, *dstlen with the source.
14634  * Assumes ip_allocbuf has already been called.
14635  */
14636 void
14637 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14638     const void *src, uint_t srclen)
14639 {
14640 	if (!src_valid)
14641 		srclen = 0;
14642 
14643 	ASSERT(*dstlenp == srclen);
14644 	if (src != NULL && srclen != 0)
14645 		bcopy(src, *dstp, srclen);
14646 }
14647 
14648 /*
14649  * Free the storage pointed to by the members of an ip_pkt_t.
14650  */
14651 void
14652 ip_pkt_free(ip_pkt_t *ipp)
14653 {
14654 	uint_t	fields = ipp->ipp_fields;
14655 
14656 	if (fields & IPPF_HOPOPTS) {
14657 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14658 		ipp->ipp_hopopts = NULL;
14659 		ipp->ipp_hopoptslen = 0;
14660 	}
14661 	if (fields & IPPF_RTHDRDSTOPTS) {
14662 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14663 		ipp->ipp_rthdrdstopts = NULL;
14664 		ipp->ipp_rthdrdstoptslen = 0;
14665 	}
14666 	if (fields & IPPF_DSTOPTS) {
14667 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14668 		ipp->ipp_dstopts = NULL;
14669 		ipp->ipp_dstoptslen = 0;
14670 	}
14671 	if (fields & IPPF_RTHDR) {
14672 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14673 		ipp->ipp_rthdr = NULL;
14674 		ipp->ipp_rthdrlen = 0;
14675 	}
14676 	if (fields & IPPF_IPV4_OPTIONS) {
14677 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14678 		ipp->ipp_ipv4_options = NULL;
14679 		ipp->ipp_ipv4_options_len = 0;
14680 	}
14681 	if (fields & IPPF_LABEL_V4) {
14682 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14683 		ipp->ipp_label_v4 = NULL;
14684 		ipp->ipp_label_len_v4 = 0;
14685 	}
14686 	if (fields & IPPF_LABEL_V6) {
14687 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14688 		ipp->ipp_label_v6 = NULL;
14689 		ipp->ipp_label_len_v6 = 0;
14690 	}
14691 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14692 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14693 }
14694 
14695 /*
14696  * Copy from src to dst and allocate as needed.
14697  * Returns zero or ENOMEM.
14698  *
14699  * The caller must initialize dst to zero.
14700  */
14701 int
14702 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14703 {
14704 	uint_t	fields = src->ipp_fields;
14705 
14706 	/* Start with fields that don't require memory allocation */
14707 	dst->ipp_fields = fields &
14708 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14709 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14710 
14711 	dst->ipp_addr = src->ipp_addr;
14712 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14713 	dst->ipp_hoplimit = src->ipp_hoplimit;
14714 	dst->ipp_tclass = src->ipp_tclass;
14715 	dst->ipp_type_of_service = src->ipp_type_of_service;
14716 
14717 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14718 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14719 		return (0);
14720 
14721 	if (fields & IPPF_HOPOPTS) {
14722 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14723 		if (dst->ipp_hopopts == NULL) {
14724 			ip_pkt_free(dst);
14725 			return (ENOMEM);
14726 		}
14727 		dst->ipp_fields |= IPPF_HOPOPTS;
14728 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14729 		    src->ipp_hopoptslen);
14730 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14731 	}
14732 	if (fields & IPPF_RTHDRDSTOPTS) {
14733 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14734 		    kmflag);
14735 		if (dst->ipp_rthdrdstopts == NULL) {
14736 			ip_pkt_free(dst);
14737 			return (ENOMEM);
14738 		}
14739 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14740 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14741 		    src->ipp_rthdrdstoptslen);
14742 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14743 	}
14744 	if (fields & IPPF_DSTOPTS) {
14745 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14746 		if (dst->ipp_dstopts == NULL) {
14747 			ip_pkt_free(dst);
14748 			return (ENOMEM);
14749 		}
14750 		dst->ipp_fields |= IPPF_DSTOPTS;
14751 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14752 		    src->ipp_dstoptslen);
14753 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14754 	}
14755 	if (fields & IPPF_RTHDR) {
14756 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14757 		if (dst->ipp_rthdr == NULL) {
14758 			ip_pkt_free(dst);
14759 			return (ENOMEM);
14760 		}
14761 		dst->ipp_fields |= IPPF_RTHDR;
14762 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14763 		    src->ipp_rthdrlen);
14764 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14765 	}
14766 	if (fields & IPPF_IPV4_OPTIONS) {
14767 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14768 		    kmflag);
14769 		if (dst->ipp_ipv4_options == NULL) {
14770 			ip_pkt_free(dst);
14771 			return (ENOMEM);
14772 		}
14773 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14774 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14775 		    src->ipp_ipv4_options_len);
14776 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14777 	}
14778 	if (fields & IPPF_LABEL_V4) {
14779 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14780 		if (dst->ipp_label_v4 == NULL) {
14781 			ip_pkt_free(dst);
14782 			return (ENOMEM);
14783 		}
14784 		dst->ipp_fields |= IPPF_LABEL_V4;
14785 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14786 		    src->ipp_label_len_v4);
14787 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14788 	}
14789 	if (fields & IPPF_LABEL_V6) {
14790 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14791 		if (dst->ipp_label_v6 == NULL) {
14792 			ip_pkt_free(dst);
14793 			return (ENOMEM);
14794 		}
14795 		dst->ipp_fields |= IPPF_LABEL_V6;
14796 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14797 		    src->ipp_label_len_v6);
14798 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14799 	}
14800 	if (fields & IPPF_FRAGHDR) {
14801 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14802 		if (dst->ipp_fraghdr == NULL) {
14803 			ip_pkt_free(dst);
14804 			return (ENOMEM);
14805 		}
14806 		dst->ipp_fields |= IPPF_FRAGHDR;
14807 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14808 		    src->ipp_fraghdrlen);
14809 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14810 	}
14811 	return (0);
14812 }
14813 
14814 /*
14815  * Returns INADDR_ANY if no source route
14816  */
14817 ipaddr_t
14818 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14819 {
14820 	ipaddr_t	nexthop = INADDR_ANY;
14821 	ipoptp_t	opts;
14822 	uchar_t		*opt;
14823 	uint8_t		optval;
14824 	uint8_t		optlen;
14825 	uint32_t	totallen;
14826 
14827 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14828 		return (INADDR_ANY);
14829 
14830 	totallen = ipp->ipp_ipv4_options_len;
14831 	if (totallen & 0x3)
14832 		return (INADDR_ANY);
14833 
14834 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14835 	    optval != IPOPT_EOL;
14836 	    optval = ipoptp_next(&opts)) {
14837 		opt = opts.ipoptp_cur;
14838 		switch (optval) {
14839 			uint8_t off;
14840 		case IPOPT_SSRR:
14841 		case IPOPT_LSRR:
14842 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14843 				break;
14844 			}
14845 			optlen = opts.ipoptp_len;
14846 			off = opt[IPOPT_OFFSET];
14847 			off--;
14848 			if (optlen < IP_ADDR_LEN ||
14849 			    off > optlen - IP_ADDR_LEN) {
14850 				/* End of source route */
14851 				break;
14852 			}
14853 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
14854 			if (nexthop == htonl(INADDR_LOOPBACK)) {
14855 				/* Ignore */
14856 				nexthop = INADDR_ANY;
14857 				break;
14858 			}
14859 			break;
14860 		}
14861 	}
14862 	return (nexthop);
14863 }
14864 
14865 /*
14866  * Reverse a source route.
14867  */
14868 void
14869 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
14870 {
14871 	ipaddr_t	tmp;
14872 	ipoptp_t	opts;
14873 	uchar_t		*opt;
14874 	uint8_t		optval;
14875 	uint32_t	totallen;
14876 
14877 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14878 		return;
14879 
14880 	totallen = ipp->ipp_ipv4_options_len;
14881 	if (totallen & 0x3)
14882 		return;
14883 
14884 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14885 	    optval != IPOPT_EOL;
14886 	    optval = ipoptp_next(&opts)) {
14887 		uint8_t off1, off2;
14888 
14889 		opt = opts.ipoptp_cur;
14890 		switch (optval) {
14891 		case IPOPT_SSRR:
14892 		case IPOPT_LSRR:
14893 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14894 				break;
14895 			}
14896 			off1 = IPOPT_MINOFF_SR - 1;
14897 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
14898 			while (off2 > off1) {
14899 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
14900 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
14901 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
14902 				off2 -= IP_ADDR_LEN;
14903 				off1 += IP_ADDR_LEN;
14904 			}
14905 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
14906 			break;
14907 		}
14908 	}
14909 }
14910 
14911 /*
14912  * Returns NULL if no routing header
14913  */
14914 in6_addr_t *
14915 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
14916 {
14917 	in6_addr_t	*nexthop = NULL;
14918 	ip6_rthdr0_t	*rthdr;
14919 
14920 	if (!(ipp->ipp_fields & IPPF_RTHDR))
14921 		return (NULL);
14922 
14923 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
14924 	if (rthdr->ip6r0_segleft == 0)
14925 		return (NULL);
14926 
14927 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
14928 	return (nexthop);
14929 }
14930 
14931 zoneid_t
14932 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
14933     zoneid_t lookup_zoneid)
14934 {
14935 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
14936 	ire_t		*ire;
14937 	int		ire_flags = MATCH_IRE_TYPE;
14938 	zoneid_t	zoneid = ALL_ZONES;
14939 
14940 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
14941 		return (ALL_ZONES);
14942 
14943 	if (lookup_zoneid != ALL_ZONES)
14944 		ire_flags |= MATCH_IRE_ZONEONLY;
14945 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
14946 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
14947 	if (ire != NULL) {
14948 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
14949 		ire_refrele(ire);
14950 	}
14951 	return (zoneid);
14952 }
14953 
14954 zoneid_t
14955 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
14956     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
14957 {
14958 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
14959 	ire_t		*ire;
14960 	int		ire_flags = MATCH_IRE_TYPE;
14961 	zoneid_t	zoneid = ALL_ZONES;
14962 
14963 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
14964 		return (ALL_ZONES);
14965 
14966 	if (IN6_IS_ADDR_LINKLOCAL(addr))
14967 		ire_flags |= MATCH_IRE_ILL;
14968 
14969 	if (lookup_zoneid != ALL_ZONES)
14970 		ire_flags |= MATCH_IRE_ZONEONLY;
14971 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
14972 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
14973 	if (ire != NULL) {
14974 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
14975 		ire_refrele(ire);
14976 	}
14977 	return (zoneid);
14978 }
14979 
14980 /*
14981  * IP obserability hook support functions.
14982  */
14983 static void
14984 ipobs_init(ip_stack_t *ipst)
14985 {
14986 	netid_t id;
14987 
14988 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
14989 
14990 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
14991 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
14992 
14993 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
14994 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
14995 }
14996 
14997 static void
14998 ipobs_fini(ip_stack_t *ipst)
14999 {
15000 
15001 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15002 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15003 }
15004 
15005 /*
15006  * hook_pkt_observe_t is composed in network byte order so that the
15007  * entire mblk_t chain handed into hook_run can be used as-is.
15008  * The caveat is that use of the fields, such as the zone fields,
15009  * requires conversion into host byte order first.
15010  */
15011 void
15012 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15013     const ill_t *ill, ip_stack_t *ipst)
15014 {
15015 	hook_pkt_observe_t *hdr;
15016 	uint64_t grifindex;
15017 	mblk_t *imp;
15018 
15019 	imp = allocb(sizeof (*hdr), BPRI_HI);
15020 	if (imp == NULL)
15021 		return;
15022 
15023 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15024 	/*
15025 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15026 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15027 	 */
15028 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15029 	imp->b_cont = mp;
15030 
15031 	ASSERT(DB_TYPE(mp) == M_DATA);
15032 
15033 	if (IS_UNDER_IPMP(ill))
15034 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15035 	else
15036 		grifindex = 0;
15037 
15038 	hdr->hpo_version = 1;
15039 	hdr->hpo_htype = htons(htype);
15040 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15041 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15042 	hdr->hpo_grifindex = htonl(grifindex);
15043 	hdr->hpo_zsrc = htonl(zsrc);
15044 	hdr->hpo_zdst = htonl(zdst);
15045 	hdr->hpo_pkt = imp;
15046 	hdr->hpo_ctx = ipst->ips_netstack;
15047 
15048 	if (ill->ill_isv6) {
15049 		hdr->hpo_family = AF_INET6;
15050 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15051 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15052 	} else {
15053 		hdr->hpo_family = AF_INET;
15054 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15055 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15056 	}
15057 
15058 	imp->b_cont = NULL;
15059 	freemsg(imp);
15060 }
15061 
15062 /*
15063  * Utility routine that checks if `v4srcp' is a valid address on underlying
15064  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15065  * associated with `v4srcp' on success.  NOTE: if this is not called from
15066  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15067  * group during or after this lookup.
15068  */
15069 boolean_t
15070 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15071 {
15072 	ipif_t *ipif;
15073 
15074 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15075 	if (ipif != NULL) {
15076 		if (ipifp != NULL)
15077 			*ipifp = ipif;
15078 		else
15079 			ipif_refrele(ipif);
15080 		return (B_TRUE);
15081 	}
15082 
15083 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15084 	    *v4srcp));
15085 	return (B_FALSE);
15086 }
15087