xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision fc33347812f84907261f6fd501e2409da108b8d8)
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, boolean_t);
675 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
676 		    mib2_ipIfStatsEntry_t *, ip_stack_t *, boolean_t);
677 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
678 		    ip_stack_t *, boolean_t);
679 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *,
680 		    boolean_t);
681 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
686 		    ip_stack_t *ipst, boolean_t);
687 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
688 		    ip_stack_t *ipst, boolean_t);
689 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst);
691 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
698 		    ip_stack_t *ipst);
699 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
700 		    ip_stack_t *ipst);
701 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
702 		    ip_stack_t *ipst);
703 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
704 		    ip_stack_t *ipst);
705 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
706 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
707 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
708 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
709 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
710 
711 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
712 		    mblk_t *);
713 
714 static void	conn_drain_init(ip_stack_t *);
715 static void	conn_drain_fini(ip_stack_t *);
716 static void	conn_drain(conn_t *connp, boolean_t closing);
717 
718 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
719 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
720 
721 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
722 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
723 static void	ip_stack_fini(netstackid_t stackid, void *arg);
724 
725 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
726     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
727     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
728     const in6_addr_t *);
729 
730 static int	ip_squeue_switch(int);
731 
732 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
733 static void	ip_kstat_fini(netstackid_t, kstat_t *);
734 static int	ip_kstat_update(kstat_t *kp, int rw);
735 static void	*icmp_kstat_init(netstackid_t);
736 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
737 static int	icmp_kstat_update(kstat_t *kp, int rw);
738 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
739 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
740 
741 static void	ipobs_init(ip_stack_t *);
742 static void	ipobs_fini(ip_stack_t *);
743 
744 static int	ip_tp_cpu_update(cpu_setup_t, int, void *);
745 
746 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
747 
748 static long ip_rput_pullups;
749 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
750 
751 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
752 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
753 
754 int	ip_debug;
755 
756 /*
757  * Multirouting/CGTP stuff
758  */
759 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
760 
761 /*
762  * IP tunables related declarations. Definitions are in ip_tunables.c
763  */
764 extern mod_prop_info_t ip_propinfo_tbl[];
765 extern int ip_propinfo_count;
766 
767 /*
768  * Table of IP ioctls encoding the various properties of the ioctl and
769  * indexed based on the last byte of the ioctl command. Occasionally there
770  * is a clash, and there is more than 1 ioctl with the same last byte.
771  * In such a case 1 ioctl is encoded in the ndx table and the remaining
772  * ioctls are encoded in the misc table. An entry in the ndx table is
773  * retrieved by indexing on the last byte of the ioctl command and comparing
774  * the ioctl command with the value in the ndx table. In the event of a
775  * mismatch the misc table is then searched sequentially for the desired
776  * ioctl command.
777  *
778  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
779  */
780 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
781 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
782 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
783 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
784 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
785 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
786 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
787 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
788 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
789 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
790 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
791 
792 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
793 			MISC_CMD, ip_siocaddrt, NULL },
794 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
795 			MISC_CMD, ip_siocdelrt, NULL },
796 
797 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
798 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
799 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
800 			IF_CMD, ip_sioctl_get_addr, NULL },
801 
802 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
803 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
804 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
805 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
806 
807 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
808 			IPI_PRIV | IPI_WR,
809 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
810 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
811 			IPI_MODOK | IPI_GET_CMD,
812 			IF_CMD, ip_sioctl_get_flags, NULL },
813 
814 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
815 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
816 
817 	/* copyin size cannot be coded for SIOCGIFCONF */
818 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
819 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
820 
821 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
822 			IF_CMD, ip_sioctl_mtu, NULL },
823 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
824 			IF_CMD, ip_sioctl_get_mtu, NULL },
825 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
826 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
827 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
828 			IF_CMD, ip_sioctl_brdaddr, NULL },
829 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
830 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
831 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
832 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
833 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
834 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
835 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
836 			IF_CMD, ip_sioctl_metric, NULL },
837 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
838 
839 	/* See 166-168 below for extended SIOC*XARP ioctls */
840 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
841 			ARP_CMD, ip_sioctl_arp, NULL },
842 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
843 			ARP_CMD, ip_sioctl_arp, NULL },
844 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
845 			ARP_CMD, ip_sioctl_arp, NULL },
846 
847 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
848 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
849 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
850 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
851 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
852 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
853 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
854 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
855 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
856 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
857 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
858 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
859 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
860 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
861 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
862 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
863 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
864 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
865 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
866 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
867 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
868 
869 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
870 			MISC_CMD, if_unitsel, if_unitsel_restart },
871 
872 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
873 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
874 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
875 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
876 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
877 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
878 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
879 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
880 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
881 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
882 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
883 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
884 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
885 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
886 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
887 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
888 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
889 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
890 
891 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
892 			IPI_PRIV | IPI_WR | IPI_MODOK,
893 			IF_CMD, ip_sioctl_sifname, NULL },
894 
895 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
896 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
897 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
898 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
899 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
900 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
901 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
902 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
903 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
904 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
905 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
906 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
907 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
908 
909 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
910 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
911 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
912 			IF_CMD, ip_sioctl_get_muxid, NULL },
913 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
914 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
915 
916 	/* Both if and lif variants share same func */
917 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
918 			IF_CMD, ip_sioctl_get_lifindex, NULL },
919 	/* Both if and lif variants share same func */
920 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
921 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
922 
923 	/* copyin size cannot be coded for SIOCGIFCONF */
924 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
925 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
926 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
927 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
928 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
929 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
930 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
931 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
932 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
933 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
934 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
935 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
936 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
937 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
938 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
939 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
940 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
941 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
942 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
943 
944 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
945 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
946 			ip_sioctl_removeif_restart },
947 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
948 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
949 			LIF_CMD, ip_sioctl_addif, NULL },
950 #define	SIOCLIFADDR_NDX 112
951 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
952 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
953 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
954 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
955 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
956 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
957 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
958 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
959 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
960 			IPI_PRIV | IPI_WR,
961 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
962 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
963 			IPI_GET_CMD | IPI_MODOK,
964 			LIF_CMD, ip_sioctl_get_flags, NULL },
965 
966 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
967 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
968 
969 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
970 			ip_sioctl_get_lifconf, NULL },
971 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
972 			LIF_CMD, ip_sioctl_mtu, NULL },
973 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
974 			LIF_CMD, ip_sioctl_get_mtu, NULL },
975 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
976 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
977 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
978 			LIF_CMD, ip_sioctl_brdaddr, NULL },
979 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
980 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
981 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
982 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
983 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
984 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
985 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
986 			LIF_CMD, ip_sioctl_metric, NULL },
987 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
988 			IPI_PRIV | IPI_WR | IPI_MODOK,
989 			LIF_CMD, ip_sioctl_slifname,
990 			ip_sioctl_slifname_restart },
991 
992 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
993 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
994 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
995 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
996 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
997 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
998 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
999 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1000 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1001 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1002 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1003 			LIF_CMD, ip_sioctl_token, NULL },
1004 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1005 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1006 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1007 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1008 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1009 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1010 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1011 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1012 
1013 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1014 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1015 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1016 			LIF_CMD, ip_siocdelndp_v6, NULL },
1017 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1018 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1019 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1020 			LIF_CMD, ip_siocsetndp_v6, NULL },
1021 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1022 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1023 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1024 			MISC_CMD, ip_sioctl_tonlink, NULL },
1025 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1026 			MISC_CMD, ip_sioctl_tmysite, NULL },
1027 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1030 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1031 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1032 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1033 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1034 
1035 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 
1037 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1038 			LIF_CMD, ip_sioctl_get_binding, NULL },
1039 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1040 			IPI_PRIV | IPI_WR,
1041 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1042 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1043 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1044 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1045 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1046 
1047 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1048 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 
1052 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 
1054 	/* These are handled in ip_sioctl_copyin_setup itself */
1055 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1056 			MISC_CMD, NULL, NULL },
1057 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1058 			MISC_CMD, NULL, NULL },
1059 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1060 
1061 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1062 			ip_sioctl_get_lifconf, NULL },
1063 
1064 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1065 			XARP_CMD, ip_sioctl_arp, NULL },
1066 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1067 			XARP_CMD, ip_sioctl_arp, NULL },
1068 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1069 			XARP_CMD, ip_sioctl_arp, NULL },
1070 
1071 	/* SIOCPOPSOCKFS is not handled by IP */
1072 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1073 
1074 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1075 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1076 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1077 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1078 			ip_sioctl_slifzone_restart },
1079 	/* 172-174 are SCTP ioctls and not handled by IP */
1080 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1084 			IPI_GET_CMD, LIF_CMD,
1085 			ip_sioctl_get_lifusesrc, 0 },
1086 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1087 			IPI_PRIV | IPI_WR,
1088 			LIF_CMD, ip_sioctl_slifusesrc,
1089 			NULL },
1090 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1091 			ip_sioctl_get_lifsrcof, NULL },
1092 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1093 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1094 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1095 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1096 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1097 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1098 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1099 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1100 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* SIOCSENABLESDP is handled by SDP */
1102 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1103 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1104 	/* 185 */ { IPI_DONTCARE /* SIOCGIFHWADDR */, 0, 0, 0, NULL, NULL },
1105 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1106 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1107 			ip_sioctl_ilb_cmd, NULL },
1108 	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1109 	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1110 	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1111 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1112 	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1113 			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart }
1114 };
1115 
1116 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1117 
1118 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1119 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1120 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1121 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1122 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1123 	{ ND_GET,	0, 0, 0, NULL, NULL },
1124 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1125 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1126 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1127 		MISC_CMD, mrt_ioctl},
1128 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1129 		MISC_CMD, mrt_ioctl},
1130 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1131 		MISC_CMD, mrt_ioctl}
1132 };
1133 
1134 int ip_misc_ioctl_count =
1135     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1136 
1137 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1138 					/* Settable in /etc/system */
1139 /* Defined in ip_ire.c */
1140 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1141 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1142 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1143 
1144 static nv_t	ire_nv_arr[] = {
1145 	{ IRE_BROADCAST, "BROADCAST" },
1146 	{ IRE_LOCAL, "LOCAL" },
1147 	{ IRE_LOOPBACK, "LOOPBACK" },
1148 	{ IRE_DEFAULT, "DEFAULT" },
1149 	{ IRE_PREFIX, "PREFIX" },
1150 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1151 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1152 	{ IRE_IF_CLONE, "IF_CLONE" },
1153 	{ IRE_HOST, "HOST" },
1154 	{ IRE_MULTICAST, "MULTICAST" },
1155 	{ IRE_NOROUTE, "NOROUTE" },
1156 	{ 0 }
1157 };
1158 
1159 nv_t	*ire_nv_tbl = ire_nv_arr;
1160 
1161 /* Simple ICMP IP Header Template */
1162 static ipha_t icmp_ipha = {
1163 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1164 };
1165 
1166 struct module_info ip_mod_info = {
1167 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1168 	IP_MOD_LOWAT
1169 };
1170 
1171 /*
1172  * Duplicate static symbols within a module confuses mdb; so we avoid the
1173  * problem by making the symbols here distinct from those in udp.c.
1174  */
1175 
1176 /*
1177  * Entry points for IP as a device and as a module.
1178  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1179  */
1180 static struct qinit iprinitv4 = {
1181 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1182 	&ip_mod_info
1183 };
1184 
1185 struct qinit iprinitv6 = {
1186 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1187 	&ip_mod_info
1188 };
1189 
1190 static struct qinit ipwinit = {
1191 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1192 	&ip_mod_info
1193 };
1194 
1195 static struct qinit iplrinit = {
1196 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1197 	&ip_mod_info
1198 };
1199 
1200 static struct qinit iplwinit = {
1201 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1202 	&ip_mod_info
1203 };
1204 
1205 /* For AF_INET aka /dev/ip */
1206 struct streamtab ipinfov4 = {
1207 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1208 };
1209 
1210 /* For AF_INET6 aka /dev/ip6 */
1211 struct streamtab ipinfov6 = {
1212 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1213 };
1214 
1215 #ifdef	DEBUG
1216 boolean_t skip_sctp_cksum = B_FALSE;
1217 #endif
1218 
1219 /*
1220  * Generate an ICMP fragmentation needed message.
1221  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1222  * constructed by the caller.
1223  */
1224 void
1225 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1226 {
1227 	icmph_t	icmph;
1228 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1229 
1230 	mp = icmp_pkt_err_ok(mp, ira);
1231 	if (mp == NULL)
1232 		return;
1233 
1234 	bzero(&icmph, sizeof (icmph_t));
1235 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1236 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1237 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1238 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1239 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1240 
1241 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1242 }
1243 
1244 /*
1245  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1246  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1247  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1248  * Likewise, if the ICMP error is misformed (too short, etc), then it
1249  * returns NULL. The caller uses this to determine whether or not to send
1250  * to raw sockets.
1251  *
1252  * All error messages are passed to the matching transport stream.
1253  *
1254  * The following cases are handled by icmp_inbound:
1255  * 1) It needs to send a reply back and possibly delivering it
1256  *    to the "interested" upper clients.
1257  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1258  * 3) It needs to change some values in IP only.
1259  * 4) It needs to change some values in IP and upper layers e.g TCP
1260  *    by delivering an error to the upper layers.
1261  *
1262  * We handle the above three cases in the context of IPsec in the
1263  * following way :
1264  *
1265  * 1) Send the reply back in the same way as the request came in.
1266  *    If it came in encrypted, it goes out encrypted. If it came in
1267  *    clear, it goes out in clear. Thus, this will prevent chosen
1268  *    plain text attack.
1269  * 2) The client may or may not expect things to come in secure.
1270  *    If it comes in secure, the policy constraints are checked
1271  *    before delivering it to the upper layers. If it comes in
1272  *    clear, ipsec_inbound_accept_clear will decide whether to
1273  *    accept this in clear or not. In both the cases, if the returned
1274  *    message (IP header + 8 bytes) that caused the icmp message has
1275  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1276  *    sending up. If there are only 8 bytes of returned message, then
1277  *    upper client will not be notified.
1278  * 3) Check with global policy to see whether it matches the constaints.
1279  *    But this will be done only if icmp_accept_messages_in_clear is
1280  *    zero.
1281  * 4) If we need to change both in IP and ULP, then the decision taken
1282  *    while affecting the values in IP and while delivering up to TCP
1283  *    should be the same.
1284  *
1285  * 	There are two cases.
1286  *
1287  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1288  *	   failed), we will not deliver it to the ULP, even though they
1289  *	   are *willing* to accept in *clear*. This is fine as our global
1290  *	   disposition to icmp messages asks us reject the datagram.
1291  *
1292  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1293  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1294  *	   to deliver it to ULP (policy failed), it can lead to
1295  *	   consistency problems. The cases known at this time are
1296  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1297  *	   values :
1298  *
1299  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1300  *	     and Upper layer rejects. Then the communication will
1301  *	     come to a stop. This is solved by making similar decisions
1302  *	     at both levels. Currently, when we are unable to deliver
1303  *	     to the Upper Layer (due to policy failures) while IP has
1304  *	     adjusted dce_pmtu, the next outbound datagram would
1305  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1306  *	     will be with the right level of protection. Thus the right
1307  *	     value will be communicated even if we are not able to
1308  *	     communicate when we get from the wire initially. But this
1309  *	     assumes there would be at least one outbound datagram after
1310  *	     IP has adjusted its dce_pmtu value. To make things
1311  *	     simpler, we accept in clear after the validation of
1312  *	     AH/ESP headers.
1313  *
1314  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1315  *	     upper layer depending on the level of protection the upper
1316  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1317  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1318  *	     should be accepted in clear when the Upper layer expects secure.
1319  *	     Thus the communication may get aborted by some bad ICMP
1320  *	     packets.
1321  */
1322 mblk_t *
1323 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1324 {
1325 	icmph_t		*icmph;
1326 	ipha_t		*ipha;		/* Outer header */
1327 	int		ip_hdr_length;	/* Outer header length */
1328 	boolean_t	interested;
1329 	ipif_t		*ipif;
1330 	uint32_t	ts;
1331 	uint32_t	*tsp;
1332 	timestruc_t	now;
1333 	ill_t		*ill = ira->ira_ill;
1334 	ip_stack_t	*ipst = ill->ill_ipst;
1335 	zoneid_t	zoneid = ira->ira_zoneid;
1336 	int		len_needed;
1337 	mblk_t		*mp_ret = NULL;
1338 
1339 	ipha = (ipha_t *)mp->b_rptr;
1340 
1341 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1342 
1343 	ip_hdr_length = ira->ira_ip_hdr_length;
1344 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1345 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1346 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1347 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1348 			freemsg(mp);
1349 			return (NULL);
1350 		}
1351 		/* Last chance to get real. */
1352 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1353 		if (ipha == NULL) {
1354 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1355 			freemsg(mp);
1356 			return (NULL);
1357 		}
1358 	}
1359 
1360 	/* The IP header will always be a multiple of four bytes */
1361 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1362 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1363 	    icmph->icmph_code));
1364 
1365 	/*
1366 	 * We will set "interested" to "true" if we should pass a copy to
1367 	 * the transport or if we handle the packet locally.
1368 	 */
1369 	interested = B_FALSE;
1370 	switch (icmph->icmph_type) {
1371 	case ICMP_ECHO_REPLY:
1372 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1373 		break;
1374 	case ICMP_DEST_UNREACHABLE:
1375 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1376 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1377 		interested = B_TRUE;	/* Pass up to transport */
1378 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1379 		break;
1380 	case ICMP_SOURCE_QUENCH:
1381 		interested = B_TRUE;	/* Pass up to transport */
1382 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1383 		break;
1384 	case ICMP_REDIRECT:
1385 		if (!ipst->ips_ip_ignore_redirect)
1386 			interested = B_TRUE;
1387 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1388 		break;
1389 	case ICMP_ECHO_REQUEST:
1390 		/*
1391 		 * Whether to respond to echo requests that come in as IP
1392 		 * broadcasts or as IP multicast is subject to debate
1393 		 * (what isn't?).  We aim to please, you pick it.
1394 		 * Default is do it.
1395 		 */
1396 		if (ira->ira_flags & IRAF_MULTICAST) {
1397 			/* multicast: respond based on tunable */
1398 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1399 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1400 			/* broadcast: respond based on tunable */
1401 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1402 		} else {
1403 			/* unicast: always respond */
1404 			interested = B_TRUE;
1405 		}
1406 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1407 		if (!interested) {
1408 			/* We never pass these to RAW sockets */
1409 			freemsg(mp);
1410 			return (NULL);
1411 		}
1412 
1413 		/* Check db_ref to make sure we can modify the packet. */
1414 		if (mp->b_datap->db_ref > 1) {
1415 			mblk_t	*mp1;
1416 
1417 			mp1 = copymsg(mp);
1418 			freemsg(mp);
1419 			if (!mp1) {
1420 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1421 				return (NULL);
1422 			}
1423 			mp = mp1;
1424 			ipha = (ipha_t *)mp->b_rptr;
1425 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1426 		}
1427 		icmph->icmph_type = ICMP_ECHO_REPLY;
1428 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1429 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1430 		return (NULL);
1431 
1432 	case ICMP_ROUTER_ADVERTISEMENT:
1433 	case ICMP_ROUTER_SOLICITATION:
1434 		break;
1435 	case ICMP_TIME_EXCEEDED:
1436 		interested = B_TRUE;	/* Pass up to transport */
1437 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1438 		break;
1439 	case ICMP_PARAM_PROBLEM:
1440 		interested = B_TRUE;	/* Pass up to transport */
1441 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1442 		break;
1443 	case ICMP_TIME_STAMP_REQUEST:
1444 		/* Response to Time Stamp Requests is local policy. */
1445 		if (ipst->ips_ip_g_resp_to_timestamp) {
1446 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1447 				interested =
1448 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1449 			else
1450 				interested = B_TRUE;
1451 		}
1452 		if (!interested) {
1453 			/* We never pass these to RAW sockets */
1454 			freemsg(mp);
1455 			return (NULL);
1456 		}
1457 
1458 		/* Make sure we have enough of the packet */
1459 		len_needed = ip_hdr_length + ICMPH_SIZE +
1460 		    3 * sizeof (uint32_t);
1461 
1462 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1463 			ipha = ip_pullup(mp, len_needed, ira);
1464 			if (ipha == NULL) {
1465 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1466 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1467 				    mp, ill);
1468 				freemsg(mp);
1469 				return (NULL);
1470 			}
1471 			/* Refresh following the pullup. */
1472 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1473 		}
1474 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1475 		/* Check db_ref to make sure we can modify the packet. */
1476 		if (mp->b_datap->db_ref > 1) {
1477 			mblk_t	*mp1;
1478 
1479 			mp1 = copymsg(mp);
1480 			freemsg(mp);
1481 			if (!mp1) {
1482 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1483 				return (NULL);
1484 			}
1485 			mp = mp1;
1486 			ipha = (ipha_t *)mp->b_rptr;
1487 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1488 		}
1489 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1490 		tsp = (uint32_t *)&icmph[1];
1491 		tsp++;		/* Skip past 'originate time' */
1492 		/* Compute # of milliseconds since midnight */
1493 		gethrestime(&now);
1494 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1495 		    now.tv_nsec / (NANOSEC / MILLISEC);
1496 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1497 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1498 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1499 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1500 		return (NULL);
1501 
1502 	case ICMP_TIME_STAMP_REPLY:
1503 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1504 		break;
1505 	case ICMP_INFO_REQUEST:
1506 		/* Per RFC 1122 3.2.2.7, ignore this. */
1507 	case ICMP_INFO_REPLY:
1508 		break;
1509 	case ICMP_ADDRESS_MASK_REQUEST:
1510 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1511 			interested =
1512 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1513 		} else {
1514 			interested = B_TRUE;
1515 		}
1516 		if (!interested) {
1517 			/* We never pass these to RAW sockets */
1518 			freemsg(mp);
1519 			return (NULL);
1520 		}
1521 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1522 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1523 			ipha = ip_pullup(mp, len_needed, ira);
1524 			if (ipha == NULL) {
1525 				BUMP_MIB(ill->ill_ip_mib,
1526 				    ipIfStatsInTruncatedPkts);
1527 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1528 				    ill);
1529 				freemsg(mp);
1530 				return (NULL);
1531 			}
1532 			/* Refresh following the pullup. */
1533 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1534 		}
1535 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1536 		/* Check db_ref to make sure we can modify the packet. */
1537 		if (mp->b_datap->db_ref > 1) {
1538 			mblk_t	*mp1;
1539 
1540 			mp1 = copymsg(mp);
1541 			freemsg(mp);
1542 			if (!mp1) {
1543 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1544 				return (NULL);
1545 			}
1546 			mp = mp1;
1547 			ipha = (ipha_t *)mp->b_rptr;
1548 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1549 		}
1550 		/*
1551 		 * Need the ipif with the mask be the same as the source
1552 		 * address of the mask reply. For unicast we have a specific
1553 		 * ipif. For multicast/broadcast we only handle onlink
1554 		 * senders, and use the source address to pick an ipif.
1555 		 */
1556 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1557 		if (ipif == NULL) {
1558 			/* Broadcast or multicast */
1559 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1560 			if (ipif == NULL) {
1561 				freemsg(mp);
1562 				return (NULL);
1563 			}
1564 		}
1565 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1566 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1567 		ipif_refrele(ipif);
1568 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1569 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1570 		return (NULL);
1571 
1572 	case ICMP_ADDRESS_MASK_REPLY:
1573 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1574 		break;
1575 	default:
1576 		interested = B_TRUE;	/* Pass up to transport */
1577 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1578 		break;
1579 	}
1580 	/*
1581 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1582 	 * if there isn't one.
1583 	 */
1584 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1585 		/* If there is an ICMP client and we want one too, copy it. */
1586 
1587 		if (!interested) {
1588 			/* Caller will deliver to RAW sockets */
1589 			return (mp);
1590 		}
1591 		mp_ret = copymsg(mp);
1592 		if (mp_ret == NULL) {
1593 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1594 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1595 		}
1596 	} else if (!interested) {
1597 		/* Neither we nor raw sockets are interested. Drop packet now */
1598 		freemsg(mp);
1599 		return (NULL);
1600 	}
1601 
1602 	/*
1603 	 * ICMP error or redirect packet. Make sure we have enough of
1604 	 * the header and that db_ref == 1 since we might end up modifying
1605 	 * the packet.
1606 	 */
1607 	if (mp->b_cont != NULL) {
1608 		if (ip_pullup(mp, -1, ira) == NULL) {
1609 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1610 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1611 			    mp, ill);
1612 			freemsg(mp);
1613 			return (mp_ret);
1614 		}
1615 	}
1616 
1617 	if (mp->b_datap->db_ref > 1) {
1618 		mblk_t	*mp1;
1619 
1620 		mp1 = copymsg(mp);
1621 		if (mp1 == NULL) {
1622 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1623 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1624 			freemsg(mp);
1625 			return (mp_ret);
1626 		}
1627 		freemsg(mp);
1628 		mp = mp1;
1629 	}
1630 
1631 	/*
1632 	 * In case mp has changed, verify the message before any further
1633 	 * processes.
1634 	 */
1635 	ipha = (ipha_t *)mp->b_rptr;
1636 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1637 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1638 		freemsg(mp);
1639 		return (mp_ret);
1640 	}
1641 
1642 	switch (icmph->icmph_type) {
1643 	case ICMP_REDIRECT:
1644 		icmp_redirect_v4(mp, ipha, icmph, ira);
1645 		break;
1646 	case ICMP_DEST_UNREACHABLE:
1647 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1648 			/* Update DCE and adjust MTU is icmp header if needed */
1649 			icmp_inbound_too_big_v4(icmph, ira);
1650 		}
1651 		/* FALLTHRU */
1652 	default:
1653 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1654 		break;
1655 	}
1656 	return (mp_ret);
1657 }
1658 
1659 /*
1660  * Send an ICMP echo, timestamp or address mask reply.
1661  * The caller has already updated the payload part of the packet.
1662  * We handle the ICMP checksum, IP source address selection and feed
1663  * the packet into ip_output_simple.
1664  */
1665 static void
1666 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1667     ip_recv_attr_t *ira)
1668 {
1669 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1670 	ill_t		*ill = ira->ira_ill;
1671 	ip_stack_t	*ipst = ill->ill_ipst;
1672 	ip_xmit_attr_t	ixas;
1673 
1674 	/* Send out an ICMP packet */
1675 	icmph->icmph_checksum = 0;
1676 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1677 	/* Reset time to live. */
1678 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1679 	{
1680 		/* Swap source and destination addresses */
1681 		ipaddr_t tmp;
1682 
1683 		tmp = ipha->ipha_src;
1684 		ipha->ipha_src = ipha->ipha_dst;
1685 		ipha->ipha_dst = tmp;
1686 	}
1687 	ipha->ipha_ident = 0;
1688 	if (!IS_SIMPLE_IPH(ipha))
1689 		icmp_options_update(ipha);
1690 
1691 	bzero(&ixas, sizeof (ixas));
1692 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1693 	ixas.ixa_zoneid = ira->ira_zoneid;
1694 	ixas.ixa_cred = kcred;
1695 	ixas.ixa_cpid = NOPID;
1696 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1697 	ixas.ixa_ifindex = 0;
1698 	ixas.ixa_ipst = ipst;
1699 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1700 
1701 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1702 		/*
1703 		 * This packet should go out the same way as it
1704 		 * came in i.e in clear, independent of the IPsec policy
1705 		 * for transmitting packets.
1706 		 */
1707 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1708 	} else {
1709 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1710 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1711 			/* Note: mp already consumed and ip_drop_packet done */
1712 			return;
1713 		}
1714 	}
1715 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1716 		/*
1717 		 * Not one or our addresses (IRE_LOCALs), thus we let
1718 		 * ip_output_simple pick the source.
1719 		 */
1720 		ipha->ipha_src = INADDR_ANY;
1721 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1722 	}
1723 	/* Should we send with DF and use dce_pmtu? */
1724 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1725 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1726 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1727 	}
1728 
1729 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1730 
1731 	(void) ip_output_simple(mp, &ixas);
1732 	ixa_cleanup(&ixas);
1733 }
1734 
1735 /*
1736  * Verify the ICMP messages for either for ICMP error or redirect packet.
1737  * The caller should have fully pulled up the message. If it's a redirect
1738  * packet, only basic checks on IP header will be done; otherwise, verify
1739  * the packet by looking at the included ULP header.
1740  *
1741  * Called before icmp_inbound_error_fanout_v4 is called.
1742  */
1743 static boolean_t
1744 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1745 {
1746 	ill_t		*ill = ira->ira_ill;
1747 	int		hdr_length;
1748 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1749 	conn_t		*connp;
1750 	ipha_t		*ipha;	/* Inner IP header */
1751 
1752 	ipha = (ipha_t *)&icmph[1];
1753 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1754 		goto truncated;
1755 
1756 	hdr_length = IPH_HDR_LENGTH(ipha);
1757 
1758 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1759 		goto discard_pkt;
1760 
1761 	if (hdr_length < sizeof (ipha_t))
1762 		goto truncated;
1763 
1764 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1765 		goto truncated;
1766 
1767 	/*
1768 	 * Stop here for ICMP_REDIRECT.
1769 	 */
1770 	if (icmph->icmph_type == ICMP_REDIRECT)
1771 		return (B_TRUE);
1772 
1773 	/*
1774 	 * ICMP errors only.
1775 	 */
1776 	switch (ipha->ipha_protocol) {
1777 	case IPPROTO_UDP:
1778 		/*
1779 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1780 		 * transport header.
1781 		 */
1782 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1783 		    mp->b_wptr)
1784 			goto truncated;
1785 		break;
1786 	case IPPROTO_TCP: {
1787 		tcpha_t		*tcpha;
1788 
1789 		/*
1790 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1791 		 * transport header.
1792 		 */
1793 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1794 		    mp->b_wptr)
1795 			goto truncated;
1796 
1797 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1798 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1799 		    ipst);
1800 		if (connp == NULL)
1801 			goto discard_pkt;
1802 
1803 		if ((connp->conn_verifyicmp != NULL) &&
1804 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1805 			CONN_DEC_REF(connp);
1806 			goto discard_pkt;
1807 		}
1808 		CONN_DEC_REF(connp);
1809 		break;
1810 	}
1811 	case IPPROTO_SCTP:
1812 		/*
1813 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1814 		 * transport header.
1815 		 */
1816 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1817 		    mp->b_wptr)
1818 			goto truncated;
1819 		break;
1820 	case IPPROTO_ESP:
1821 	case IPPROTO_AH:
1822 		break;
1823 	case IPPROTO_ENCAP:
1824 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1825 		    mp->b_wptr)
1826 			goto truncated;
1827 		break;
1828 	default:
1829 		break;
1830 	}
1831 
1832 	return (B_TRUE);
1833 
1834 discard_pkt:
1835 	/* Bogus ICMP error. */
1836 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1837 	return (B_FALSE);
1838 
1839 truncated:
1840 	/* We pulled up everthing already. Must be truncated */
1841 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1842 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1843 	return (B_FALSE);
1844 }
1845 
1846 /* Table from RFC 1191 */
1847 static int icmp_frag_size_table[] =
1848 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1849 
1850 /*
1851  * Process received ICMP Packet too big.
1852  * Just handles the DCE create/update, including using the above table of
1853  * PMTU guesses. The caller is responsible for validating the packet before
1854  * passing it in and also to fanout the ICMP error to any matching transport
1855  * conns. Assumes the message has been fully pulled up and verified.
1856  *
1857  * Before getting here, the caller has called icmp_inbound_verify_v4()
1858  * that should have verified with ULP to prevent undoing the changes we're
1859  * going to make to DCE. For example, TCP might have verified that the packet
1860  * which generated error is in the send window.
1861  *
1862  * In some cases modified this MTU in the ICMP header packet; the caller
1863  * should pass to the matching ULP after this returns.
1864  */
1865 static void
1866 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1867 {
1868 	dce_t		*dce;
1869 	int		old_mtu;
1870 	int		mtu, orig_mtu;
1871 	ipaddr_t	dst;
1872 	boolean_t	disable_pmtud;
1873 	ill_t		*ill = ira->ira_ill;
1874 	ip_stack_t	*ipst = ill->ill_ipst;
1875 	uint_t		hdr_length;
1876 	ipha_t		*ipha;
1877 
1878 	/* Caller already pulled up everything. */
1879 	ipha = (ipha_t *)&icmph[1];
1880 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1881 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1882 	ASSERT(ill != NULL);
1883 
1884 	hdr_length = IPH_HDR_LENGTH(ipha);
1885 
1886 	/*
1887 	 * We handle path MTU for source routed packets since the DCE
1888 	 * is looked up using the final destination.
1889 	 */
1890 	dst = ip_get_dst(ipha);
1891 
1892 	dce = dce_lookup_and_add_v4(dst, ipst);
1893 	if (dce == NULL) {
1894 		/* Couldn't add a unique one - ENOMEM */
1895 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1896 		    ntohl(dst)));
1897 		return;
1898 	}
1899 
1900 	/* Check for MTU discovery advice as described in RFC 1191 */
1901 	mtu = ntohs(icmph->icmph_du_mtu);
1902 	orig_mtu = mtu;
1903 	disable_pmtud = B_FALSE;
1904 
1905 	mutex_enter(&dce->dce_lock);
1906 	if (dce->dce_flags & DCEF_PMTU)
1907 		old_mtu = dce->dce_pmtu;
1908 	else
1909 		old_mtu = ill->ill_mtu;
1910 
1911 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1912 		uint32_t length;
1913 		int	i;
1914 
1915 		/*
1916 		 * Use the table from RFC 1191 to figure out
1917 		 * the next "plateau" based on the length in
1918 		 * the original IP packet.
1919 		 */
1920 		length = ntohs(ipha->ipha_length);
1921 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1922 		    uint32_t, length);
1923 		if (old_mtu <= length &&
1924 		    old_mtu >= length - hdr_length) {
1925 			/*
1926 			 * Handle broken BSD 4.2 systems that
1927 			 * return the wrong ipha_length in ICMP
1928 			 * errors.
1929 			 */
1930 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1931 			    length, old_mtu));
1932 			length -= hdr_length;
1933 		}
1934 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1935 			if (length > icmp_frag_size_table[i])
1936 				break;
1937 		}
1938 		if (i == A_CNT(icmp_frag_size_table)) {
1939 			/* Smaller than IP_MIN_MTU! */
1940 			ip1dbg(("Too big for packet size %d\n",
1941 			    length));
1942 			disable_pmtud = B_TRUE;
1943 			mtu = ipst->ips_ip_pmtu_min;
1944 		} else {
1945 			mtu = icmp_frag_size_table[i];
1946 			ip1dbg(("Calculated mtu %d, packet size %d, "
1947 			    "before %d\n", mtu, length, old_mtu));
1948 			if (mtu < ipst->ips_ip_pmtu_min) {
1949 				mtu = ipst->ips_ip_pmtu_min;
1950 				disable_pmtud = B_TRUE;
1951 			}
1952 		}
1953 	}
1954 	if (disable_pmtud)
1955 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1956 	else
1957 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1958 
1959 	dce->dce_pmtu = MIN(old_mtu, mtu);
1960 	/* Prepare to send the new max frag size for the ULP. */
1961 	icmph->icmph_du_zero = 0;
1962 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1963 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1964 	    dce, int, orig_mtu, int, mtu);
1965 
1966 	/* We now have a PMTU for sure */
1967 	dce->dce_flags |= DCEF_PMTU;
1968 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1969 	mutex_exit(&dce->dce_lock);
1970 	/*
1971 	 * After dropping the lock the new value is visible to everyone.
1972 	 * Then we bump the generation number so any cached values reinspect
1973 	 * the dce_t.
1974 	 */
1975 	dce_increment_generation(dce);
1976 	dce_refrele(dce);
1977 }
1978 
1979 /*
1980  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1981  * calls this function.
1982  */
1983 static mblk_t *
1984 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1985 {
1986 	int length;
1987 
1988 	ASSERT(mp->b_datap->db_type == M_DATA);
1989 
1990 	/* icmp_inbound_v4 has already pulled up the whole error packet */
1991 	ASSERT(mp->b_cont == NULL);
1992 
1993 	/*
1994 	 * The length that we want to overlay is the inner header
1995 	 * and what follows it.
1996 	 */
1997 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
1998 
1999 	/*
2000 	 * Overlay the inner header and whatever follows it over the
2001 	 * outer header.
2002 	 */
2003 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2004 
2005 	/* Adjust for what we removed */
2006 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2007 	return (mp);
2008 }
2009 
2010 /*
2011  * Try to pass the ICMP message upstream in case the ULP cares.
2012  *
2013  * If the packet that caused the ICMP error is secure, we send
2014  * it to AH/ESP to make sure that the attached packet has a
2015  * valid association. ipha in the code below points to the
2016  * IP header of the packet that caused the error.
2017  *
2018  * For IPsec cases, we let the next-layer-up (which has access to
2019  * cached policy on the conn_t, or can query the SPD directly)
2020  * subtract out any IPsec overhead if they must.  We therefore make no
2021  * adjustments here for IPsec overhead.
2022  *
2023  * IFN could have been generated locally or by some router.
2024  *
2025  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2026  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2027  *	    This happens because IP adjusted its value of MTU on an
2028  *	    earlier IFN message and could not tell the upper layer,
2029  *	    the new adjusted value of MTU e.g. Packet was encrypted
2030  *	    or there was not enough information to fanout to upper
2031  *	    layers. Thus on the next outbound datagram, ire_send_wire
2032  *	    generates the IFN, where IPsec processing has *not* been
2033  *	    done.
2034  *
2035  *	    Note that we retain ixa_fragsize across IPsec thus once
2036  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2037  *	    no change the fragsize even if the path MTU changes before
2038  *	    we reach ip_output_post_ipsec.
2039  *
2040  *	    In the local case, IRAF_LOOPBACK will be set indicating
2041  *	    that IFN was generated locally.
2042  *
2043  * ROUTER : IFN could be secure or non-secure.
2044  *
2045  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2046  *	      packet in error has AH/ESP headers to validate the AH/ESP
2047  *	      headers. AH/ESP will verify whether there is a valid SA or
2048  *	      not and send it back. We will fanout again if we have more
2049  *	      data in the packet.
2050  *
2051  *	      If the packet in error does not have AH/ESP, we handle it
2052  *	      like any other case.
2053  *
2054  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2055  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2056  *	      valid SA or not and send it back. We will fanout again if
2057  *	      we have more data in the packet.
2058  *
2059  *	      If the packet in error does not have AH/ESP, we handle it
2060  *	      like any other case.
2061  *
2062  * The caller must have called icmp_inbound_verify_v4.
2063  */
2064 static void
2065 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2066 {
2067 	uint16_t	*up;	/* Pointer to ports in ULP header */
2068 	uint32_t	ports;	/* reversed ports for fanout */
2069 	ipha_t		ripha;	/* With reversed addresses */
2070 	ipha_t		*ipha;  /* Inner IP header */
2071 	uint_t		hdr_length; /* Inner IP header length */
2072 	tcpha_t		*tcpha;
2073 	conn_t		*connp;
2074 	ill_t		*ill = ira->ira_ill;
2075 	ip_stack_t	*ipst = ill->ill_ipst;
2076 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2077 	ill_t		*rill = ira->ira_rill;
2078 
2079 	/* Caller already pulled up everything. */
2080 	ipha = (ipha_t *)&icmph[1];
2081 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2082 	ASSERT(mp->b_cont == NULL);
2083 
2084 	hdr_length = IPH_HDR_LENGTH(ipha);
2085 	ira->ira_protocol = ipha->ipha_protocol;
2086 
2087 	/*
2088 	 * We need a separate IP header with the source and destination
2089 	 * addresses reversed to do fanout/classification because the ipha in
2090 	 * the ICMP error is in the form we sent it out.
2091 	 */
2092 	ripha.ipha_src = ipha->ipha_dst;
2093 	ripha.ipha_dst = ipha->ipha_src;
2094 	ripha.ipha_protocol = ipha->ipha_protocol;
2095 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2096 
2097 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2098 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2099 	    ntohl(ipha->ipha_dst),
2100 	    icmph->icmph_type, icmph->icmph_code));
2101 
2102 	switch (ipha->ipha_protocol) {
2103 	case IPPROTO_UDP:
2104 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2105 
2106 		/* Attempt to find a client stream based on port. */
2107 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2108 		    ntohs(up[0]), ntohs(up[1])));
2109 
2110 		/* Note that we send error to all matches. */
2111 		ira->ira_flags |= IRAF_ICMP_ERROR;
2112 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2113 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2114 		return;
2115 
2116 	case IPPROTO_TCP:
2117 		/*
2118 		 * Find a TCP client stream for this packet.
2119 		 * Note that we do a reverse lookup since the header is
2120 		 * in the form we sent it out.
2121 		 */
2122 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2123 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2124 		    ipst);
2125 		if (connp == NULL)
2126 			goto discard_pkt;
2127 
2128 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2129 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2130 			mp = ipsec_check_inbound_policy(mp, connp,
2131 			    ipha, NULL, ira);
2132 			if (mp == NULL) {
2133 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2134 				/* Note that mp is NULL */
2135 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2136 				CONN_DEC_REF(connp);
2137 				return;
2138 			}
2139 		}
2140 
2141 		ira->ira_flags |= IRAF_ICMP_ERROR;
2142 		ira->ira_ill = ira->ira_rill = NULL;
2143 		if (IPCL_IS_TCP(connp)) {
2144 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2145 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2146 			    SQTAG_TCP_INPUT_ICMP_ERR);
2147 		} else {
2148 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2149 			(connp->conn_recv)(connp, mp, NULL, ira);
2150 			CONN_DEC_REF(connp);
2151 		}
2152 		ira->ira_ill = ill;
2153 		ira->ira_rill = rill;
2154 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2155 		return;
2156 
2157 	case IPPROTO_SCTP:
2158 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2159 		/* Find a SCTP client stream for this packet. */
2160 		((uint16_t *)&ports)[0] = up[1];
2161 		((uint16_t *)&ports)[1] = up[0];
2162 
2163 		ira->ira_flags |= IRAF_ICMP_ERROR;
2164 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2165 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2166 		return;
2167 
2168 	case IPPROTO_ESP:
2169 	case IPPROTO_AH:
2170 		if (!ipsec_loaded(ipss)) {
2171 			ip_proto_not_sup(mp, ira);
2172 			return;
2173 		}
2174 
2175 		if (ipha->ipha_protocol == IPPROTO_ESP)
2176 			mp = ipsecesp_icmp_error(mp, ira);
2177 		else
2178 			mp = ipsecah_icmp_error(mp, ira);
2179 		if (mp == NULL)
2180 			return;
2181 
2182 		/* Just in case ipsec didn't preserve the NULL b_cont */
2183 		if (mp->b_cont != NULL) {
2184 			if (!pullupmsg(mp, -1))
2185 				goto discard_pkt;
2186 		}
2187 
2188 		/*
2189 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2190 		 * correct, but we don't use them any more here.
2191 		 *
2192 		 * If succesful, the mp has been modified to not include
2193 		 * the ESP/AH header so we can fanout to the ULP's icmp
2194 		 * error handler.
2195 		 */
2196 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2197 			goto truncated;
2198 
2199 		/* Verify the modified message before any further processes. */
2200 		ipha = (ipha_t *)mp->b_rptr;
2201 		hdr_length = IPH_HDR_LENGTH(ipha);
2202 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2203 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2204 			freemsg(mp);
2205 			return;
2206 		}
2207 
2208 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2209 		return;
2210 
2211 	case IPPROTO_ENCAP: {
2212 		/* Look for self-encapsulated packets that caused an error */
2213 		ipha_t *in_ipha;
2214 
2215 		/*
2216 		 * Caller has verified that length has to be
2217 		 * at least the size of IP header.
2218 		 */
2219 		ASSERT(hdr_length >= sizeof (ipha_t));
2220 		/*
2221 		 * Check the sanity of the inner IP header like
2222 		 * we did for the outer header.
2223 		 */
2224 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2225 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2226 			goto discard_pkt;
2227 		}
2228 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2229 			goto discard_pkt;
2230 		}
2231 		/* Check for Self-encapsulated tunnels */
2232 		if (in_ipha->ipha_src == ipha->ipha_src &&
2233 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2234 
2235 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2236 			    in_ipha);
2237 			if (mp == NULL)
2238 				goto discard_pkt;
2239 
2240 			/*
2241 			 * Just in case self_encap didn't preserve the NULL
2242 			 * b_cont
2243 			 */
2244 			if (mp->b_cont != NULL) {
2245 				if (!pullupmsg(mp, -1))
2246 					goto discard_pkt;
2247 			}
2248 			/*
2249 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2250 			 * longer correct, but we don't use them any more here.
2251 			 */
2252 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2253 				goto truncated;
2254 
2255 			/*
2256 			 * Verify the modified message before any further
2257 			 * processes.
2258 			 */
2259 			ipha = (ipha_t *)mp->b_rptr;
2260 			hdr_length = IPH_HDR_LENGTH(ipha);
2261 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2262 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2263 				freemsg(mp);
2264 				return;
2265 			}
2266 
2267 			/*
2268 			 * The packet in error is self-encapsualted.
2269 			 * And we are finding it further encapsulated
2270 			 * which we could not have possibly generated.
2271 			 */
2272 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2273 				goto discard_pkt;
2274 			}
2275 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2276 			return;
2277 		}
2278 		/* No self-encapsulated */
2279 		/* FALLTHRU */
2280 	}
2281 	case IPPROTO_IPV6:
2282 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2283 		    &ripha.ipha_dst, ipst)) != NULL) {
2284 			ira->ira_flags |= IRAF_ICMP_ERROR;
2285 			connp->conn_recvicmp(connp, mp, NULL, ira);
2286 			CONN_DEC_REF(connp);
2287 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2288 			return;
2289 		}
2290 		/*
2291 		 * No IP tunnel is interested, fallthrough and see
2292 		 * if a raw socket will want it.
2293 		 */
2294 		/* FALLTHRU */
2295 	default:
2296 		ira->ira_flags |= IRAF_ICMP_ERROR;
2297 		ip_fanout_proto_v4(mp, &ripha, ira);
2298 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2299 		return;
2300 	}
2301 	/* NOTREACHED */
2302 discard_pkt:
2303 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2304 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2305 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2306 	freemsg(mp);
2307 	return;
2308 
2309 truncated:
2310 	/* We pulled up everthing already. Must be truncated */
2311 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2312 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2313 	freemsg(mp);
2314 }
2315 
2316 /*
2317  * Common IP options parser.
2318  *
2319  * Setup routine: fill in *optp with options-parsing state, then
2320  * tail-call ipoptp_next to return the first option.
2321  */
2322 uint8_t
2323 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2324 {
2325 	uint32_t totallen; /* total length of all options */
2326 
2327 	totallen = ipha->ipha_version_and_hdr_length -
2328 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2329 	totallen <<= 2;
2330 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2331 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2332 	optp->ipoptp_flags = 0;
2333 	return (ipoptp_next(optp));
2334 }
2335 
2336 /* Like above but without an ipha_t */
2337 uint8_t
2338 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2339 {
2340 	optp->ipoptp_next = opt;
2341 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2342 	optp->ipoptp_flags = 0;
2343 	return (ipoptp_next(optp));
2344 }
2345 
2346 /*
2347  * Common IP options parser: extract next option.
2348  */
2349 uint8_t
2350 ipoptp_next(ipoptp_t *optp)
2351 {
2352 	uint8_t *end = optp->ipoptp_end;
2353 	uint8_t *cur = optp->ipoptp_next;
2354 	uint8_t opt, len, pointer;
2355 
2356 	/*
2357 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2358 	 * has been corrupted.
2359 	 */
2360 	ASSERT(cur <= end);
2361 
2362 	if (cur == end)
2363 		return (IPOPT_EOL);
2364 
2365 	opt = cur[IPOPT_OPTVAL];
2366 
2367 	/*
2368 	 * Skip any NOP options.
2369 	 */
2370 	while (opt == IPOPT_NOP) {
2371 		cur++;
2372 		if (cur == end)
2373 			return (IPOPT_EOL);
2374 		opt = cur[IPOPT_OPTVAL];
2375 	}
2376 
2377 	if (opt == IPOPT_EOL)
2378 		return (IPOPT_EOL);
2379 
2380 	/*
2381 	 * Option requiring a length.
2382 	 */
2383 	if ((cur + 1) >= end) {
2384 		optp->ipoptp_flags |= IPOPTP_ERROR;
2385 		return (IPOPT_EOL);
2386 	}
2387 	len = cur[IPOPT_OLEN];
2388 	if (len < 2) {
2389 		optp->ipoptp_flags |= IPOPTP_ERROR;
2390 		return (IPOPT_EOL);
2391 	}
2392 	optp->ipoptp_cur = cur;
2393 	optp->ipoptp_len = len;
2394 	optp->ipoptp_next = cur + len;
2395 	if (cur + len > end) {
2396 		optp->ipoptp_flags |= IPOPTP_ERROR;
2397 		return (IPOPT_EOL);
2398 	}
2399 
2400 	/*
2401 	 * For the options which require a pointer field, make sure
2402 	 * its there, and make sure it points to either something
2403 	 * inside this option, or the end of the option.
2404 	 */
2405 	switch (opt) {
2406 	case IPOPT_RR:
2407 	case IPOPT_TS:
2408 	case IPOPT_LSRR:
2409 	case IPOPT_SSRR:
2410 		if (len <= IPOPT_OFFSET) {
2411 			optp->ipoptp_flags |= IPOPTP_ERROR;
2412 			return (opt);
2413 		}
2414 		pointer = cur[IPOPT_OFFSET];
2415 		if (pointer - 1 > len) {
2416 			optp->ipoptp_flags |= IPOPTP_ERROR;
2417 			return (opt);
2418 		}
2419 		break;
2420 	}
2421 
2422 	/*
2423 	 * Sanity check the pointer field based on the type of the
2424 	 * option.
2425 	 */
2426 	switch (opt) {
2427 	case IPOPT_RR:
2428 	case IPOPT_SSRR:
2429 	case IPOPT_LSRR:
2430 		if (pointer < IPOPT_MINOFF_SR)
2431 			optp->ipoptp_flags |= IPOPTP_ERROR;
2432 		break;
2433 	case IPOPT_TS:
2434 		if (pointer < IPOPT_MINOFF_IT)
2435 			optp->ipoptp_flags |= IPOPTP_ERROR;
2436 		/*
2437 		 * Note that the Internet Timestamp option also
2438 		 * contains two four bit fields (the Overflow field,
2439 		 * and the Flag field), which follow the pointer
2440 		 * field.  We don't need to check that these fields
2441 		 * fall within the length of the option because this
2442 		 * was implicitely done above.  We've checked that the
2443 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2444 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2445 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2446 		 */
2447 		ASSERT(len > IPOPT_POS_OV_FLG);
2448 		break;
2449 	}
2450 
2451 	return (opt);
2452 }
2453 
2454 /*
2455  * Use the outgoing IP header to create an IP_OPTIONS option the way
2456  * it was passed down from the application.
2457  *
2458  * This is compatible with BSD in that it returns
2459  * the reverse source route with the final destination
2460  * as the last entry. The first 4 bytes of the option
2461  * will contain the final destination.
2462  */
2463 int
2464 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2465 {
2466 	ipoptp_t	opts;
2467 	uchar_t		*opt;
2468 	uint8_t		optval;
2469 	uint8_t		optlen;
2470 	uint32_t	len = 0;
2471 	uchar_t		*buf1 = buf;
2472 	uint32_t	totallen;
2473 	ipaddr_t	dst;
2474 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2475 
2476 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2477 		return (0);
2478 
2479 	totallen = ipp->ipp_ipv4_options_len;
2480 	if (totallen & 0x3)
2481 		return (0);
2482 
2483 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2484 	len += IP_ADDR_LEN;
2485 	bzero(buf1, IP_ADDR_LEN);
2486 
2487 	dst = connp->conn_faddr_v4;
2488 
2489 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2490 	    optval != IPOPT_EOL;
2491 	    optval = ipoptp_next(&opts)) {
2492 		int	off;
2493 
2494 		opt = opts.ipoptp_cur;
2495 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2496 			break;
2497 		}
2498 		optlen = opts.ipoptp_len;
2499 
2500 		switch (optval) {
2501 		case IPOPT_SSRR:
2502 		case IPOPT_LSRR:
2503 
2504 			/*
2505 			 * Insert destination as the first entry in the source
2506 			 * route and move down the entries on step.
2507 			 * The last entry gets placed at buf1.
2508 			 */
2509 			buf[IPOPT_OPTVAL] = optval;
2510 			buf[IPOPT_OLEN] = optlen;
2511 			buf[IPOPT_OFFSET] = optlen;
2512 
2513 			off = optlen - IP_ADDR_LEN;
2514 			if (off < 0) {
2515 				/* No entries in source route */
2516 				break;
2517 			}
2518 			/* Last entry in source route if not already set */
2519 			if (dst == INADDR_ANY)
2520 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2521 			off -= IP_ADDR_LEN;
2522 
2523 			while (off > 0) {
2524 				bcopy(opt + off,
2525 				    buf + off + IP_ADDR_LEN,
2526 				    IP_ADDR_LEN);
2527 				off -= IP_ADDR_LEN;
2528 			}
2529 			/* ipha_dst into first slot */
2530 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2531 			    IP_ADDR_LEN);
2532 			buf += optlen;
2533 			len += optlen;
2534 			break;
2535 
2536 		default:
2537 			bcopy(opt, buf, optlen);
2538 			buf += optlen;
2539 			len += optlen;
2540 			break;
2541 		}
2542 	}
2543 done:
2544 	/* Pad the resulting options */
2545 	while (len & 0x3) {
2546 		*buf++ = IPOPT_EOL;
2547 		len++;
2548 	}
2549 	return (len);
2550 }
2551 
2552 /*
2553  * Update any record route or timestamp options to include this host.
2554  * Reverse any source route option.
2555  * This routine assumes that the options are well formed i.e. that they
2556  * have already been checked.
2557  */
2558 static void
2559 icmp_options_update(ipha_t *ipha)
2560 {
2561 	ipoptp_t	opts;
2562 	uchar_t		*opt;
2563 	uint8_t		optval;
2564 	ipaddr_t	src;		/* Our local address */
2565 	ipaddr_t	dst;
2566 
2567 	ip2dbg(("icmp_options_update\n"));
2568 	src = ipha->ipha_src;
2569 	dst = ipha->ipha_dst;
2570 
2571 	for (optval = ipoptp_first(&opts, ipha);
2572 	    optval != IPOPT_EOL;
2573 	    optval = ipoptp_next(&opts)) {
2574 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2575 		opt = opts.ipoptp_cur;
2576 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2577 		    optval, opts.ipoptp_len));
2578 		switch (optval) {
2579 			int off1, off2;
2580 		case IPOPT_SSRR:
2581 		case IPOPT_LSRR:
2582 			/*
2583 			 * Reverse the source route.  The first entry
2584 			 * should be the next to last one in the current
2585 			 * source route (the last entry is our address).
2586 			 * The last entry should be the final destination.
2587 			 */
2588 			off1 = IPOPT_MINOFF_SR - 1;
2589 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2590 			if (off2 < 0) {
2591 				/* No entries in source route */
2592 				ip1dbg((
2593 				    "icmp_options_update: bad src route\n"));
2594 				break;
2595 			}
2596 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2597 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2598 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2599 			off2 -= IP_ADDR_LEN;
2600 
2601 			while (off1 < off2) {
2602 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2603 				bcopy((char *)opt + off2, (char *)opt + off1,
2604 				    IP_ADDR_LEN);
2605 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2606 				off1 += IP_ADDR_LEN;
2607 				off2 -= IP_ADDR_LEN;
2608 			}
2609 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2610 			break;
2611 		}
2612 	}
2613 }
2614 
2615 /*
2616  * Process received ICMP Redirect messages.
2617  * Assumes the caller has verified that the headers are in the pulled up mblk.
2618  * Consumes mp.
2619  */
2620 static void
2621 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2622 {
2623 	ire_t		*ire, *nire;
2624 	ire_t		*prev_ire;
2625 	ipaddr_t  	src, dst, gateway;
2626 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2627 	ipha_t		*inner_ipha;	/* Inner IP header */
2628 
2629 	/* Caller already pulled up everything. */
2630 	inner_ipha = (ipha_t *)&icmph[1];
2631 	src = ipha->ipha_src;
2632 	dst = inner_ipha->ipha_dst;
2633 	gateway = icmph->icmph_rd_gateway;
2634 	/* Make sure the new gateway is reachable somehow. */
2635 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2636 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2637 	/*
2638 	 * Make sure we had a route for the dest in question and that
2639 	 * that route was pointing to the old gateway (the source of the
2640 	 * redirect packet.)
2641 	 * We do longest match and then compare ire_gateway_addr below.
2642 	 */
2643 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2644 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2645 	/*
2646 	 * Check that
2647 	 *	the redirect was not from ourselves
2648 	 *	the new gateway and the old gateway are directly reachable
2649 	 */
2650 	if (prev_ire == NULL || ire == NULL ||
2651 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2652 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2653 	    !(ire->ire_type & IRE_IF_ALL) ||
2654 	    prev_ire->ire_gateway_addr != src) {
2655 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2656 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2657 		freemsg(mp);
2658 		if (ire != NULL)
2659 			ire_refrele(ire);
2660 		if (prev_ire != NULL)
2661 			ire_refrele(prev_ire);
2662 		return;
2663 	}
2664 
2665 	ire_refrele(prev_ire);
2666 	ire_refrele(ire);
2667 
2668 	/*
2669 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2670 	 * require TOS routing
2671 	 */
2672 	switch (icmph->icmph_code) {
2673 	case 0:
2674 	case 1:
2675 		/* TODO: TOS specificity for cases 2 and 3 */
2676 	case 2:
2677 	case 3:
2678 		break;
2679 	default:
2680 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2681 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2682 		freemsg(mp);
2683 		return;
2684 	}
2685 	/*
2686 	 * Create a Route Association.  This will allow us to remember that
2687 	 * someone we believe told us to use the particular gateway.
2688 	 */
2689 	ire = ire_create(
2690 	    (uchar_t *)&dst,			/* dest addr */
2691 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2692 	    (uchar_t *)&gateway,		/* gateway addr */
2693 	    IRE_HOST,
2694 	    NULL,				/* ill */
2695 	    ALL_ZONES,
2696 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2697 	    NULL,				/* tsol_gc_t */
2698 	    ipst);
2699 
2700 	if (ire == NULL) {
2701 		freemsg(mp);
2702 		return;
2703 	}
2704 	nire = ire_add(ire);
2705 	/* Check if it was a duplicate entry */
2706 	if (nire != NULL && nire != ire) {
2707 		ASSERT(nire->ire_identical_ref > 1);
2708 		ire_delete(nire);
2709 		ire_refrele(nire);
2710 		nire = NULL;
2711 	}
2712 	ire = nire;
2713 	if (ire != NULL) {
2714 		ire_refrele(ire);		/* Held in ire_add */
2715 
2716 		/* tell routing sockets that we received a redirect */
2717 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2718 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2719 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2720 	}
2721 
2722 	/*
2723 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2724 	 * This together with the added IRE has the effect of
2725 	 * modifying an existing redirect.
2726 	 */
2727 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2728 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2729 	if (prev_ire != NULL) {
2730 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2731 			ire_delete(prev_ire);
2732 		ire_refrele(prev_ire);
2733 	}
2734 
2735 	freemsg(mp);
2736 }
2737 
2738 /*
2739  * Generate an ICMP parameter problem message.
2740  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2741  * constructed by the caller.
2742  */
2743 static void
2744 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2745 {
2746 	icmph_t	icmph;
2747 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2748 
2749 	mp = icmp_pkt_err_ok(mp, ira);
2750 	if (mp == NULL)
2751 		return;
2752 
2753 	bzero(&icmph, sizeof (icmph_t));
2754 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2755 	icmph.icmph_pp_ptr = ptr;
2756 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2757 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2758 }
2759 
2760 /*
2761  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2762  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2763  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2764  * an icmp error packet can be sent.
2765  * Assigns an appropriate source address to the packet. If ipha_dst is
2766  * one of our addresses use it for source. Otherwise let ip_output_simple
2767  * pick the source address.
2768  */
2769 static void
2770 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2771 {
2772 	ipaddr_t dst;
2773 	icmph_t	*icmph;
2774 	ipha_t	*ipha;
2775 	uint_t	len_needed;
2776 	size_t	msg_len;
2777 	mblk_t	*mp1;
2778 	ipaddr_t src;
2779 	ire_t	*ire;
2780 	ip_xmit_attr_t ixas;
2781 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2782 
2783 	ipha = (ipha_t *)mp->b_rptr;
2784 
2785 	bzero(&ixas, sizeof (ixas));
2786 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2787 	ixas.ixa_zoneid = ira->ira_zoneid;
2788 	ixas.ixa_ifindex = 0;
2789 	ixas.ixa_ipst = ipst;
2790 	ixas.ixa_cred = kcred;
2791 	ixas.ixa_cpid = NOPID;
2792 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2793 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2794 
2795 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2796 		/*
2797 		 * Apply IPsec based on how IPsec was applied to
2798 		 * the packet that had the error.
2799 		 *
2800 		 * If it was an outbound packet that caused the ICMP
2801 		 * error, then the caller will have setup the IRA
2802 		 * appropriately.
2803 		 */
2804 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2805 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2806 			/* Note: mp already consumed and ip_drop_packet done */
2807 			return;
2808 		}
2809 	} else {
2810 		/*
2811 		 * This is in clear. The icmp message we are building
2812 		 * here should go out in clear, independent of our policy.
2813 		 */
2814 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2815 	}
2816 
2817 	/* Remember our eventual destination */
2818 	dst = ipha->ipha_src;
2819 
2820 	/*
2821 	 * If the packet was for one of our unicast addresses, make
2822 	 * sure we respond with that as the source. Otherwise
2823 	 * have ip_output_simple pick the source address.
2824 	 */
2825 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2826 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2827 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2828 	if (ire != NULL) {
2829 		ire_refrele(ire);
2830 		src = ipha->ipha_dst;
2831 	} else {
2832 		src = INADDR_ANY;
2833 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2834 	}
2835 
2836 	/*
2837 	 * Check if we can send back more then 8 bytes in addition to
2838 	 * the IP header.  We try to send 64 bytes of data and the internal
2839 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2840 	 */
2841 	len_needed = IPH_HDR_LENGTH(ipha);
2842 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2843 	    ipha->ipha_protocol == IPPROTO_IPV6) {
2844 		if (!pullupmsg(mp, -1)) {
2845 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2846 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2847 			freemsg(mp);
2848 			return;
2849 		}
2850 		ipha = (ipha_t *)mp->b_rptr;
2851 
2852 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2853 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2854 			    len_needed));
2855 		} else {
2856 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2857 
2858 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2859 			len_needed += ip_hdr_length_v6(mp, ip6h);
2860 		}
2861 	}
2862 	len_needed += ipst->ips_ip_icmp_return;
2863 	msg_len = msgdsize(mp);
2864 	if (msg_len > len_needed) {
2865 		(void) adjmsg(mp, len_needed - msg_len);
2866 		msg_len = len_needed;
2867 	}
2868 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2869 	if (mp1 == NULL) {
2870 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2871 		freemsg(mp);
2872 		return;
2873 	}
2874 	mp1->b_cont = mp;
2875 	mp = mp1;
2876 
2877 	/*
2878 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2879 	 * node generates be accepted in peace by all on-host destinations.
2880 	 * If we do NOT assume that all on-host destinations trust
2881 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2882 	 * (Look for IXAF_TRUSTED_ICMP).
2883 	 */
2884 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2885 
2886 	ipha = (ipha_t *)mp->b_rptr;
2887 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2888 	*ipha = icmp_ipha;
2889 	ipha->ipha_src = src;
2890 	ipha->ipha_dst = dst;
2891 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2892 	msg_len += sizeof (icmp_ipha) + len;
2893 	if (msg_len > IP_MAXPACKET) {
2894 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
2895 		msg_len = IP_MAXPACKET;
2896 	}
2897 	ipha->ipha_length = htons((uint16_t)msg_len);
2898 	icmph = (icmph_t *)&ipha[1];
2899 	bcopy(stuff, icmph, len);
2900 	icmph->icmph_checksum = 0;
2901 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2902 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2903 
2904 	(void) ip_output_simple(mp, &ixas);
2905 	ixa_cleanup(&ixas);
2906 }
2907 
2908 /*
2909  * Determine if an ICMP error packet can be sent given the rate limit.
2910  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2911  * in milliseconds) and a burst size. Burst size number of packets can
2912  * be sent arbitrarely closely spaced.
2913  * The state is tracked using two variables to implement an approximate
2914  * token bucket filter:
2915  *	icmp_pkt_err_last - lbolt value when the last burst started
2916  *	icmp_pkt_err_sent - number of packets sent in current burst
2917  */
2918 boolean_t
2919 icmp_err_rate_limit(ip_stack_t *ipst)
2920 {
2921 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2922 	uint_t refilled; /* Number of packets refilled in tbf since last */
2923 	/* Guard against changes by loading into local variable */
2924 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2925 
2926 	if (err_interval == 0)
2927 		return (B_FALSE);
2928 
2929 	if (ipst->ips_icmp_pkt_err_last > now) {
2930 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2931 		ipst->ips_icmp_pkt_err_last = 0;
2932 		ipst->ips_icmp_pkt_err_sent = 0;
2933 	}
2934 	/*
2935 	 * If we are in a burst update the token bucket filter.
2936 	 * Update the "last" time to be close to "now" but make sure
2937 	 * we don't loose precision.
2938 	 */
2939 	if (ipst->ips_icmp_pkt_err_sent != 0) {
2940 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2941 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
2942 			ipst->ips_icmp_pkt_err_sent = 0;
2943 		} else {
2944 			ipst->ips_icmp_pkt_err_sent -= refilled;
2945 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2946 		}
2947 	}
2948 	if (ipst->ips_icmp_pkt_err_sent == 0) {
2949 		/* Start of new burst */
2950 		ipst->ips_icmp_pkt_err_last = now;
2951 	}
2952 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2953 		ipst->ips_icmp_pkt_err_sent++;
2954 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2955 		    ipst->ips_icmp_pkt_err_sent));
2956 		return (B_FALSE);
2957 	}
2958 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
2959 	return (B_TRUE);
2960 }
2961 
2962 /*
2963  * Check if it is ok to send an IPv4 ICMP error packet in
2964  * response to the IPv4 packet in mp.
2965  * Free the message and return null if no
2966  * ICMP error packet should be sent.
2967  */
2968 static mblk_t *
2969 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2970 {
2971 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2972 	icmph_t	*icmph;
2973 	ipha_t	*ipha;
2974 	uint_t	len_needed;
2975 
2976 	if (!mp)
2977 		return (NULL);
2978 	ipha = (ipha_t *)mp->b_rptr;
2979 	if (ip_csum_hdr(ipha)) {
2980 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2981 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2982 		freemsg(mp);
2983 		return (NULL);
2984 	}
2985 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2986 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2987 	    CLASSD(ipha->ipha_dst) ||
2988 	    CLASSD(ipha->ipha_src) ||
2989 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2990 		/* Note: only errors to the fragment with offset 0 */
2991 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2992 		freemsg(mp);
2993 		return (NULL);
2994 	}
2995 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
2996 		/*
2997 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
2998 		 * errors in response to any ICMP errors.
2999 		 */
3000 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3001 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3002 			if (!pullupmsg(mp, len_needed)) {
3003 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3004 				freemsg(mp);
3005 				return (NULL);
3006 			}
3007 			ipha = (ipha_t *)mp->b_rptr;
3008 		}
3009 		icmph = (icmph_t *)
3010 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3011 		switch (icmph->icmph_type) {
3012 		case ICMP_DEST_UNREACHABLE:
3013 		case ICMP_SOURCE_QUENCH:
3014 		case ICMP_TIME_EXCEEDED:
3015 		case ICMP_PARAM_PROBLEM:
3016 		case ICMP_REDIRECT:
3017 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3018 			freemsg(mp);
3019 			return (NULL);
3020 		default:
3021 			break;
3022 		}
3023 	}
3024 	/*
3025 	 * If this is a labeled system, then check to see if we're allowed to
3026 	 * send a response to this particular sender.  If not, then just drop.
3027 	 */
3028 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3029 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3030 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3031 		freemsg(mp);
3032 		return (NULL);
3033 	}
3034 	if (icmp_err_rate_limit(ipst)) {
3035 		/*
3036 		 * Only send ICMP error packets every so often.
3037 		 * This should be done on a per port/source basis,
3038 		 * but for now this will suffice.
3039 		 */
3040 		freemsg(mp);
3041 		return (NULL);
3042 	}
3043 	return (mp);
3044 }
3045 
3046 /*
3047  * Called when a packet was sent out the same link that it arrived on.
3048  * Check if it is ok to send a redirect and then send it.
3049  */
3050 void
3051 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3052     ip_recv_attr_t *ira)
3053 {
3054 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3055 	ipaddr_t	src, nhop;
3056 	mblk_t		*mp1;
3057 	ire_t		*nhop_ire;
3058 
3059 	/*
3060 	 * Check the source address to see if it originated
3061 	 * on the same logical subnet it is going back out on.
3062 	 * If so, we should be able to send it a redirect.
3063 	 * Avoid sending a redirect if the destination
3064 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3065 	 * or if the packet was source routed out this interface.
3066 	 *
3067 	 * We avoid sending a redirect if the
3068 	 * destination is directly connected
3069 	 * because it is possible that multiple
3070 	 * IP subnets may have been configured on
3071 	 * the link, and the source may not
3072 	 * be on the same subnet as ip destination,
3073 	 * even though they are on the same
3074 	 * physical link.
3075 	 */
3076 	if ((ire->ire_type & IRE_ONLINK) ||
3077 	    ip_source_routed(ipha, ipst))
3078 		return;
3079 
3080 	nhop_ire = ire_nexthop(ire);
3081 	if (nhop_ire == NULL)
3082 		return;
3083 
3084 	nhop = nhop_ire->ire_addr;
3085 
3086 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3087 		ire_t	*ire2;
3088 
3089 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3090 		mutex_enter(&nhop_ire->ire_lock);
3091 		ire2 = nhop_ire->ire_dep_parent;
3092 		if (ire2 != NULL)
3093 			ire_refhold(ire2);
3094 		mutex_exit(&nhop_ire->ire_lock);
3095 		ire_refrele(nhop_ire);
3096 		nhop_ire = ire2;
3097 	}
3098 	if (nhop_ire == NULL)
3099 		return;
3100 
3101 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3102 
3103 	src = ipha->ipha_src;
3104 
3105 	/*
3106 	 * We look at the interface ire for the nexthop,
3107 	 * to see if ipha_src is in the same subnet
3108 	 * as the nexthop.
3109 	 */
3110 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3111 		/*
3112 		 * The source is directly connected.
3113 		 */
3114 		mp1 = copymsg(mp);
3115 		if (mp1 != NULL) {
3116 			icmp_send_redirect(mp1, nhop, ira);
3117 		}
3118 	}
3119 	ire_refrele(nhop_ire);
3120 }
3121 
3122 /*
3123  * Generate an ICMP redirect message.
3124  */
3125 static void
3126 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3127 {
3128 	icmph_t	icmph;
3129 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3130 
3131 	mp = icmp_pkt_err_ok(mp, ira);
3132 	if (mp == NULL)
3133 		return;
3134 
3135 	bzero(&icmph, sizeof (icmph_t));
3136 	icmph.icmph_type = ICMP_REDIRECT;
3137 	icmph.icmph_code = 1;
3138 	icmph.icmph_rd_gateway = gateway;
3139 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3140 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3141 }
3142 
3143 /*
3144  * Generate an ICMP time exceeded message.
3145  */
3146 void
3147 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3148 {
3149 	icmph_t	icmph;
3150 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3151 
3152 	mp = icmp_pkt_err_ok(mp, ira);
3153 	if (mp == NULL)
3154 		return;
3155 
3156 	bzero(&icmph, sizeof (icmph_t));
3157 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3158 	icmph.icmph_code = code;
3159 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3160 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3161 }
3162 
3163 /*
3164  * Generate an ICMP unreachable message.
3165  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3166  * constructed by the caller.
3167  */
3168 void
3169 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3170 {
3171 	icmph_t	icmph;
3172 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3173 
3174 	mp = icmp_pkt_err_ok(mp, ira);
3175 	if (mp == NULL)
3176 		return;
3177 
3178 	bzero(&icmph, sizeof (icmph_t));
3179 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3180 	icmph.icmph_code = code;
3181 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3182 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3183 }
3184 
3185 /*
3186  * Latch in the IPsec state for a stream based the policy in the listener
3187  * and the actions in the ip_recv_attr_t.
3188  * Called directly from TCP and SCTP.
3189  */
3190 boolean_t
3191 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3192 {
3193 	ASSERT(lconnp->conn_policy != NULL);
3194 	ASSERT(connp->conn_policy == NULL);
3195 
3196 	IPPH_REFHOLD(lconnp->conn_policy);
3197 	connp->conn_policy = lconnp->conn_policy;
3198 
3199 	if (ira->ira_ipsec_action != NULL) {
3200 		if (connp->conn_latch == NULL) {
3201 			connp->conn_latch = iplatch_create();
3202 			if (connp->conn_latch == NULL)
3203 				return (B_FALSE);
3204 		}
3205 		ipsec_latch_inbound(connp, ira);
3206 	}
3207 	return (B_TRUE);
3208 }
3209 
3210 /*
3211  * Verify whether or not the IP address is a valid local address.
3212  * Could be a unicast, including one for a down interface.
3213  * If allow_mcbc then a multicast or broadcast address is also
3214  * acceptable.
3215  *
3216  * In the case of a broadcast/multicast address, however, the
3217  * upper protocol is expected to reset the src address
3218  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3219  * no packets are emitted with broadcast/multicast address as
3220  * source address (that violates hosts requirements RFC 1122)
3221  * The addresses valid for bind are:
3222  *	(1) - INADDR_ANY (0)
3223  *	(2) - IP address of an UP interface
3224  *	(3) - IP address of a DOWN interface
3225  *	(4) - valid local IP broadcast addresses. In this case
3226  *	the conn will only receive packets destined to
3227  *	the specified broadcast address.
3228  *	(5) - a multicast address. In this case
3229  *	the conn will only receive packets destined to
3230  *	the specified multicast address. Note: the
3231  *	application still has to issue an
3232  *	IP_ADD_MEMBERSHIP socket option.
3233  *
3234  * In all the above cases, the bound address must be valid in the current zone.
3235  * When the address is loopback, multicast or broadcast, there might be many
3236  * matching IREs so bind has to look up based on the zone.
3237  */
3238 ip_laddr_t
3239 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3240     ip_stack_t *ipst, boolean_t allow_mcbc)
3241 {
3242 	ire_t *src_ire;
3243 
3244 	ASSERT(src_addr != INADDR_ANY);
3245 
3246 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3247 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3248 
3249 	/*
3250 	 * If an address other than in6addr_any is requested,
3251 	 * we verify that it is a valid address for bind
3252 	 * Note: Following code is in if-else-if form for
3253 	 * readability compared to a condition check.
3254 	 */
3255 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3256 		/*
3257 		 * (2) Bind to address of local UP interface
3258 		 */
3259 		ire_refrele(src_ire);
3260 		return (IPVL_UNICAST_UP);
3261 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3262 		/*
3263 		 * (4) Bind to broadcast address
3264 		 */
3265 		ire_refrele(src_ire);
3266 		if (allow_mcbc)
3267 			return (IPVL_BCAST);
3268 		else
3269 			return (IPVL_BAD);
3270 	} else if (CLASSD(src_addr)) {
3271 		/* (5) bind to multicast address. */
3272 		if (src_ire != NULL)
3273 			ire_refrele(src_ire);
3274 
3275 		if (allow_mcbc)
3276 			return (IPVL_MCAST);
3277 		else
3278 			return (IPVL_BAD);
3279 	} else {
3280 		ipif_t *ipif;
3281 
3282 		/*
3283 		 * (3) Bind to address of local DOWN interface?
3284 		 * (ipif_lookup_addr() looks up all interfaces
3285 		 * but we do not get here for UP interfaces
3286 		 * - case (2) above)
3287 		 */
3288 		if (src_ire != NULL)
3289 			ire_refrele(src_ire);
3290 
3291 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3292 		if (ipif == NULL)
3293 			return (IPVL_BAD);
3294 
3295 		/* Not a useful source? */
3296 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3297 			ipif_refrele(ipif);
3298 			return (IPVL_BAD);
3299 		}
3300 		ipif_refrele(ipif);
3301 		return (IPVL_UNICAST_DOWN);
3302 	}
3303 }
3304 
3305 /*
3306  * Insert in the bind fanout for IPv4 and IPv6.
3307  * The caller should already have used ip_laddr_verify_v*() before calling
3308  * this.
3309  */
3310 int
3311 ip_laddr_fanout_insert(conn_t *connp)
3312 {
3313 	int		error;
3314 
3315 	/*
3316 	 * Allow setting new policies. For example, disconnects result
3317 	 * in us being called. As we would have set conn_policy_cached
3318 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3319 	 * can change after the disconnect.
3320 	 */
3321 	connp->conn_policy_cached = B_FALSE;
3322 
3323 	error = ipcl_bind_insert(connp);
3324 	if (error != 0) {
3325 		if (connp->conn_anon_port) {
3326 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3327 			    connp->conn_mlp_type, connp->conn_proto,
3328 			    ntohs(connp->conn_lport), B_FALSE);
3329 		}
3330 		connp->conn_mlp_type = mlptSingle;
3331 	}
3332 	return (error);
3333 }
3334 
3335 /*
3336  * Verify that both the source and destination addresses are valid. If
3337  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3338  * i.e. have no route to it.  Protocols like TCP want to verify destination
3339  * reachability, while tunnels do not.
3340  *
3341  * Determine the route, the interface, and (optionally) the source address
3342  * to use to reach a given destination.
3343  * Note that we allow connect to broadcast and multicast addresses when
3344  * IPDF_ALLOW_MCBC is set.
3345  * first_hop and dst_addr are normally the same, but if source routing
3346  * they will differ; in that case the first_hop is what we'll use for the
3347  * routing lookup but the dce and label checks will be done on dst_addr,
3348  *
3349  * If uinfo is set, then we fill in the best available information
3350  * we have for the destination. This is based on (in priority order) any
3351  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3352  * ill_mtu.
3353  *
3354  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3355  * always do the label check on dst_addr.
3356  */
3357 int
3358 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3359     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3360 {
3361 	ire_t		*ire = NULL;
3362 	int		error = 0;
3363 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3364 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3365 	ip_stack_t	*ipst = ixa->ixa_ipst;
3366 	dce_t		*dce;
3367 	uint_t		pmtu;
3368 	uint_t		generation;
3369 	nce_t		*nce;
3370 	ill_t		*ill = NULL;
3371 	boolean_t	multirt = B_FALSE;
3372 
3373 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3374 
3375 	/*
3376 	 * We never send to zero; the ULPs map it to the loopback address.
3377 	 * We can't allow it since we use zero to mean unitialized in some
3378 	 * places.
3379 	 */
3380 	ASSERT(dst_addr != INADDR_ANY);
3381 
3382 	if (is_system_labeled()) {
3383 		ts_label_t *tsl = NULL;
3384 
3385 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3386 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3387 		if (error != 0)
3388 			return (error);
3389 		if (tsl != NULL) {
3390 			/* Update the label */
3391 			ip_xmit_attr_replace_tsl(ixa, tsl);
3392 		}
3393 	}
3394 
3395 	setsrc = INADDR_ANY;
3396 	/*
3397 	 * Select a route; For IPMP interfaces, we would only select
3398 	 * a "hidden" route (i.e., going through a specific under_ill)
3399 	 * if ixa_ifindex has been specified.
3400 	 */
3401 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3402 	    &generation, &setsrc, &error, &multirt);
3403 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3404 	if (error != 0)
3405 		goto bad_addr;
3406 
3407 	/*
3408 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3409 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3410 	 * Otherwise the destination needn't be reachable.
3411 	 *
3412 	 * If we match on a reject or black hole, then we've got a
3413 	 * local failure.  May as well fail out the connect() attempt,
3414 	 * since it's never going to succeed.
3415 	 */
3416 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3417 		/*
3418 		 * If we're verifying destination reachability, we always want
3419 		 * to complain here.
3420 		 *
3421 		 * If we're not verifying destination reachability but the
3422 		 * destination has a route, we still want to fail on the
3423 		 * temporary address and broadcast address tests.
3424 		 *
3425 		 * In both cases do we let the code continue so some reasonable
3426 		 * information is returned to the caller. That enables the
3427 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3428 		 * use the generation mismatch path to check for the unreachable
3429 		 * case thereby avoiding any specific check in the main path.
3430 		 */
3431 		ASSERT(generation == IRE_GENERATION_VERIFY);
3432 		if (flags & IPDF_VERIFY_DST) {
3433 			/*
3434 			 * Set errno but continue to set up ixa_ire to be
3435 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3436 			 * That allows callers to use ip_output to get an
3437 			 * ICMP error back.
3438 			 */
3439 			if (!(ire->ire_type & IRE_HOST))
3440 				error = ENETUNREACH;
3441 			else
3442 				error = EHOSTUNREACH;
3443 		}
3444 	}
3445 
3446 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3447 	    !(flags & IPDF_ALLOW_MCBC)) {
3448 		ire_refrele(ire);
3449 		ire = ire_reject(ipst, B_FALSE);
3450 		generation = IRE_GENERATION_VERIFY;
3451 		error = ENETUNREACH;
3452 	}
3453 
3454 	/* Cache things */
3455 	if (ixa->ixa_ire != NULL)
3456 		ire_refrele_notr(ixa->ixa_ire);
3457 #ifdef DEBUG
3458 	ire_refhold_notr(ire);
3459 	ire_refrele(ire);
3460 #endif
3461 	ixa->ixa_ire = ire;
3462 	ixa->ixa_ire_generation = generation;
3463 
3464 	/*
3465 	 * Ensure that ixa_dce is always set any time that ixa_ire is set,
3466 	 * since some callers will send a packet to conn_ip_output() even if
3467 	 * there's an error.
3468 	 */
3469 	if (flags & IPDF_UNIQUE_DCE) {
3470 		/* Fallback to the default dce if allocation fails */
3471 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3472 		if (dce != NULL)
3473 			generation = dce->dce_generation;
3474 		else
3475 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3476 	} else {
3477 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3478 	}
3479 	ASSERT(dce != NULL);
3480 	if (ixa->ixa_dce != NULL)
3481 		dce_refrele_notr(ixa->ixa_dce);
3482 #ifdef DEBUG
3483 	dce_refhold_notr(dce);
3484 	dce_refrele(dce);
3485 #endif
3486 	ixa->ixa_dce = dce;
3487 	ixa->ixa_dce_generation = generation;
3488 
3489 	/*
3490 	 * For multicast with multirt we have a flag passed back from
3491 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3492 	 * possible multicast address.
3493 	 * We also need a flag for multicast since we can't check
3494 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3495 	 */
3496 	if (multirt) {
3497 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3498 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3499 	} else {
3500 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3501 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3502 	}
3503 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3504 		/* Get an nce to cache. */
3505 		nce = ire_to_nce(ire, firsthop, NULL);
3506 		if (nce == NULL) {
3507 			/* Allocation failure? */
3508 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3509 		} else {
3510 			if (ixa->ixa_nce != NULL)
3511 				nce_refrele(ixa->ixa_nce);
3512 			ixa->ixa_nce = nce;
3513 		}
3514 	}
3515 
3516 	/*
3517 	 * If the source address is a loopback address, the
3518 	 * destination had best be local or multicast.
3519 	 * If we are sending to an IRE_LOCAL using a loopback source then
3520 	 * it had better be the same zoneid.
3521 	 */
3522 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3523 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3524 			ire = NULL;	/* Stored in ixa_ire */
3525 			error = EADDRNOTAVAIL;
3526 			goto bad_addr;
3527 		}
3528 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3529 			ire = NULL;	/* Stored in ixa_ire */
3530 			error = EADDRNOTAVAIL;
3531 			goto bad_addr;
3532 		}
3533 	}
3534 	if (ire->ire_type & IRE_BROADCAST) {
3535 		/*
3536 		 * If the ULP didn't have a specified source, then we
3537 		 * make sure we reselect the source when sending
3538 		 * broadcasts out different interfaces.
3539 		 */
3540 		if (flags & IPDF_SELECT_SRC)
3541 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3542 		else
3543 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3544 	}
3545 
3546 	/*
3547 	 * Does the caller want us to pick a source address?
3548 	 */
3549 	if (flags & IPDF_SELECT_SRC) {
3550 		ipaddr_t	src_addr;
3551 
3552 		/*
3553 		 * We use use ire_nexthop_ill to avoid the under ipmp
3554 		 * interface for source address selection. Note that for ipmp
3555 		 * probe packets, ixa_ifindex would have been specified, and
3556 		 * the ip_select_route() invocation would have picked an ire
3557 		 * will ire_ill pointing at an under interface.
3558 		 */
3559 		ill = ire_nexthop_ill(ire);
3560 
3561 		/* If unreachable we have no ill but need some source */
3562 		if (ill == NULL) {
3563 			src_addr = htonl(INADDR_LOOPBACK);
3564 			/* Make sure we look for a better source address */
3565 			generation = SRC_GENERATION_VERIFY;
3566 		} else {
3567 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3568 			    ixa->ixa_multicast_ifaddr, zoneid,
3569 			    ipst, &src_addr, &generation, NULL);
3570 			if (error != 0) {
3571 				ire = NULL;	/* Stored in ixa_ire */
3572 				goto bad_addr;
3573 			}
3574 		}
3575 
3576 		/*
3577 		 * We allow the source address to to down.
3578 		 * However, we check that we don't use the loopback address
3579 		 * as a source when sending out on the wire.
3580 		 */
3581 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3582 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3583 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3584 			ire = NULL;	/* Stored in ixa_ire */
3585 			error = EADDRNOTAVAIL;
3586 			goto bad_addr;
3587 		}
3588 
3589 		*src_addrp = src_addr;
3590 		ixa->ixa_src_generation = generation;
3591 	}
3592 
3593 	/*
3594 	 * Make sure we don't leave an unreachable ixa_nce in place
3595 	 * since ip_select_route is used when we unplumb i.e., remove
3596 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3597 	 */
3598 	nce = ixa->ixa_nce;
3599 	if (nce != NULL && nce->nce_is_condemned) {
3600 		nce_refrele(nce);
3601 		ixa->ixa_nce = NULL;
3602 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3603 	}
3604 
3605 	/*
3606 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3607 	 * However, we can't do it for IPv4 multicast or broadcast.
3608 	 */
3609 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3610 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3611 
3612 	/*
3613 	 * Set initial value for fragmentation limit. Either conn_ip_output
3614 	 * or ULP might updates it when there are routing changes.
3615 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3616 	 */
3617 	pmtu = ip_get_pmtu(ixa);
3618 	ixa->ixa_fragsize = pmtu;
3619 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3620 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3621 		ixa->ixa_pmtu = pmtu;
3622 
3623 	/*
3624 	 * Extract information useful for some transports.
3625 	 * First we look for DCE metrics. Then we take what we have in
3626 	 * the metrics in the route, where the offlink is used if we have
3627 	 * one.
3628 	 */
3629 	if (uinfo != NULL) {
3630 		bzero(uinfo, sizeof (*uinfo));
3631 
3632 		if (dce->dce_flags & DCEF_UINFO)
3633 			*uinfo = dce->dce_uinfo;
3634 
3635 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3636 
3637 		/* Allow ire_metrics to decrease the path MTU from above */
3638 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3639 			uinfo->iulp_mtu = pmtu;
3640 
3641 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3642 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3643 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3644 	}
3645 
3646 	if (ill != NULL)
3647 		ill_refrele(ill);
3648 
3649 	return (error);
3650 
3651 bad_addr:
3652 	if (ire != NULL)
3653 		ire_refrele(ire);
3654 
3655 	if (ill != NULL)
3656 		ill_refrele(ill);
3657 
3658 	/*
3659 	 * Make sure we don't leave an unreachable ixa_nce in place
3660 	 * since ip_select_route is used when we unplumb i.e., remove
3661 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3662 	 */
3663 	nce = ixa->ixa_nce;
3664 	if (nce != NULL && nce->nce_is_condemned) {
3665 		nce_refrele(nce);
3666 		ixa->ixa_nce = NULL;
3667 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3668 	}
3669 
3670 	return (error);
3671 }
3672 
3673 
3674 /*
3675  * Get the base MTU for the case when path MTU discovery is not used.
3676  * Takes the MTU of the IRE into account.
3677  */
3678 uint_t
3679 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3680 {
3681 	uint_t mtu = ill->ill_mtu;
3682 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3683 
3684 	if (iremtu != 0 && iremtu < mtu)
3685 		mtu = iremtu;
3686 
3687 	return (mtu);
3688 }
3689 
3690 /*
3691  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3692  * Assumes that ixa_ire, dce, and nce have already been set up.
3693  *
3694  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3695  * We avoid path MTU discovery if it is disabled with ndd.
3696  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3697  *
3698  * NOTE: We also used to turn it off for source routed packets. That
3699  * is no longer required since the dce is per final destination.
3700  */
3701 uint_t
3702 ip_get_pmtu(ip_xmit_attr_t *ixa)
3703 {
3704 	ip_stack_t	*ipst = ixa->ixa_ipst;
3705 	dce_t		*dce;
3706 	nce_t		*nce;
3707 	ire_t		*ire;
3708 	uint_t		pmtu;
3709 
3710 	ire = ixa->ixa_ire;
3711 	dce = ixa->ixa_dce;
3712 	nce = ixa->ixa_nce;
3713 
3714 	/*
3715 	 * If path MTU discovery has been turned off by ndd, then we ignore
3716 	 * any dce_pmtu and for IPv4 we will not set DF.
3717 	 */
3718 	if (!ipst->ips_ip_path_mtu_discovery)
3719 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3720 
3721 	pmtu = IP_MAXPACKET;
3722 	/*
3723 	 * Decide whether whether IPv4 sets DF
3724 	 * For IPv6 "no DF" means to use the 1280 mtu
3725 	 */
3726 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3727 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3728 	} else {
3729 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3730 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3731 			pmtu = IPV6_MIN_MTU;
3732 	}
3733 
3734 	/* Check if the PMTU is to old before we use it */
3735 	if ((dce->dce_flags & DCEF_PMTU) &&
3736 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3737 	    ipst->ips_ip_pathmtu_interval) {
3738 		/*
3739 		 * Older than 20 minutes. Drop the path MTU information.
3740 		 */
3741 		mutex_enter(&dce->dce_lock);
3742 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3743 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3744 		mutex_exit(&dce->dce_lock);
3745 		dce_increment_generation(dce);
3746 	}
3747 
3748 	/* The metrics on the route can lower the path MTU */
3749 	if (ire->ire_metrics.iulp_mtu != 0 &&
3750 	    ire->ire_metrics.iulp_mtu < pmtu)
3751 		pmtu = ire->ire_metrics.iulp_mtu;
3752 
3753 	/*
3754 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3755 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3756 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3757 	 */
3758 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3759 		if (dce->dce_flags & DCEF_PMTU) {
3760 			if (dce->dce_pmtu < pmtu)
3761 				pmtu = dce->dce_pmtu;
3762 
3763 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3764 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3765 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3766 			} else {
3767 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3768 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3769 			}
3770 		} else {
3771 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3772 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3773 		}
3774 	}
3775 
3776 	/*
3777 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3778 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3779 	 * mtu as IRE_LOOPBACK.
3780 	 */
3781 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3782 		uint_t loopback_mtu;
3783 
3784 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3785 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3786 
3787 		if (loopback_mtu < pmtu)
3788 			pmtu = loopback_mtu;
3789 	} else if (nce != NULL) {
3790 		/*
3791 		 * Make sure we don't exceed the interface MTU.
3792 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3793 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3794 		 * to tell the transport something larger than zero.
3795 		 */
3796 		if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3797 			pmtu = nce->nce_common->ncec_ill->ill_mtu;
3798 		if (nce->nce_common->ncec_ill != nce->nce_ill &&
3799 		    nce->nce_ill->ill_mtu < pmtu) {
3800 			/*
3801 			 * for interfaces in an IPMP group, the mtu of
3802 			 * the nce_ill (under_ill) could be different
3803 			 * from the mtu of the ncec_ill, so we take the
3804 			 * min of the two.
3805 			 */
3806 			pmtu = nce->nce_ill->ill_mtu;
3807 		}
3808 	}
3809 
3810 	/*
3811 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3812 	 * Only applies to IPv6.
3813 	 */
3814 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3815 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3816 			switch (ixa->ixa_use_min_mtu) {
3817 			case IPV6_USE_MIN_MTU_MULTICAST:
3818 				if (ire->ire_type & IRE_MULTICAST)
3819 					pmtu = IPV6_MIN_MTU;
3820 				break;
3821 			case IPV6_USE_MIN_MTU_ALWAYS:
3822 				pmtu = IPV6_MIN_MTU;
3823 				break;
3824 			case IPV6_USE_MIN_MTU_NEVER:
3825 				break;
3826 			}
3827 		} else {
3828 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3829 			if (ire->ire_type & IRE_MULTICAST)
3830 				pmtu = IPV6_MIN_MTU;
3831 		}
3832 	}
3833 
3834 	/*
3835 	 * After receiving an ICMPv6 "packet too big" message with a
3836 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3837 	 * will insert a 8-byte fragment header in every packet. We compensate
3838 	 * for those cases by returning a smaller path MTU to the ULP.
3839 	 *
3840 	 * In the case of CGTP then ip_output will add a fragment header.
3841 	 * Make sure there is room for it by telling a smaller number
3842 	 * to the transport.
3843 	 *
3844 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3845 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3846 	 * which is the size of the packets it can send.
3847 	 */
3848 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3849 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
3850 		    (ire->ire_flags & RTF_MULTIRT) ||
3851 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3852 			pmtu -= sizeof (ip6_frag_t);
3853 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3854 		}
3855 	}
3856 
3857 	return (pmtu);
3858 }
3859 
3860 /*
3861  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3862  * the final piece where we don't.  Return a pointer to the first mblk in the
3863  * result, and update the pointer to the next mblk to chew on.  If anything
3864  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3865  * NULL pointer.
3866  */
3867 mblk_t *
3868 ip_carve_mp(mblk_t **mpp, ssize_t len)
3869 {
3870 	mblk_t	*mp0;
3871 	mblk_t	*mp1;
3872 	mblk_t	*mp2;
3873 
3874 	if (!len || !mpp || !(mp0 = *mpp))
3875 		return (NULL);
3876 	/* If we aren't going to consume the first mblk, we need a dup. */
3877 	if (mp0->b_wptr - mp0->b_rptr > len) {
3878 		mp1 = dupb(mp0);
3879 		if (mp1) {
3880 			/* Partition the data between the two mblks. */
3881 			mp1->b_wptr = mp1->b_rptr + len;
3882 			mp0->b_rptr = mp1->b_wptr;
3883 			/*
3884 			 * after adjustments if mblk not consumed is now
3885 			 * unaligned, try to align it. If this fails free
3886 			 * all messages and let upper layer recover.
3887 			 */
3888 			if (!OK_32PTR(mp0->b_rptr)) {
3889 				if (!pullupmsg(mp0, -1)) {
3890 					freemsg(mp0);
3891 					freemsg(mp1);
3892 					*mpp = NULL;
3893 					return (NULL);
3894 				}
3895 			}
3896 		}
3897 		return (mp1);
3898 	}
3899 	/* Eat through as many mblks as we need to get len bytes. */
3900 	len -= mp0->b_wptr - mp0->b_rptr;
3901 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3902 		if (mp2->b_wptr - mp2->b_rptr > len) {
3903 			/*
3904 			 * We won't consume the entire last mblk.  Like
3905 			 * above, dup and partition it.
3906 			 */
3907 			mp1->b_cont = dupb(mp2);
3908 			mp1 = mp1->b_cont;
3909 			if (!mp1) {
3910 				/*
3911 				 * Trouble.  Rather than go to a lot of
3912 				 * trouble to clean up, we free the messages.
3913 				 * This won't be any worse than losing it on
3914 				 * the wire.
3915 				 */
3916 				freemsg(mp0);
3917 				freemsg(mp2);
3918 				*mpp = NULL;
3919 				return (NULL);
3920 			}
3921 			mp1->b_wptr = mp1->b_rptr + len;
3922 			mp2->b_rptr = mp1->b_wptr;
3923 			/*
3924 			 * after adjustments if mblk not consumed is now
3925 			 * unaligned, try to align it. If this fails free
3926 			 * all messages and let upper layer recover.
3927 			 */
3928 			if (!OK_32PTR(mp2->b_rptr)) {
3929 				if (!pullupmsg(mp2, -1)) {
3930 					freemsg(mp0);
3931 					freemsg(mp2);
3932 					*mpp = NULL;
3933 					return (NULL);
3934 				}
3935 			}
3936 			*mpp = mp2;
3937 			return (mp0);
3938 		}
3939 		/* Decrement len by the amount we just got. */
3940 		len -= mp2->b_wptr - mp2->b_rptr;
3941 	}
3942 	/*
3943 	 * len should be reduced to zero now.  If not our caller has
3944 	 * screwed up.
3945 	 */
3946 	if (len) {
3947 		/* Shouldn't happen! */
3948 		freemsg(mp0);
3949 		*mpp = NULL;
3950 		return (NULL);
3951 	}
3952 	/*
3953 	 * We consumed up to exactly the end of an mblk.  Detach the part
3954 	 * we are returning from the rest of the chain.
3955 	 */
3956 	mp1->b_cont = NULL;
3957 	*mpp = mp2;
3958 	return (mp0);
3959 }
3960 
3961 /* The ill stream is being unplumbed. Called from ip_close */
3962 int
3963 ip_modclose(ill_t *ill)
3964 {
3965 	boolean_t success;
3966 	ipsq_t	*ipsq;
3967 	ipif_t	*ipif;
3968 	queue_t	*q = ill->ill_rq;
3969 	ip_stack_t	*ipst = ill->ill_ipst;
3970 	int	i;
3971 	arl_ill_common_t *ai = ill->ill_common;
3972 
3973 	/*
3974 	 * The punlink prior to this may have initiated a capability
3975 	 * negotiation. But ipsq_enter will block until that finishes or
3976 	 * times out.
3977 	 */
3978 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
3979 
3980 	/*
3981 	 * Open/close/push/pop is guaranteed to be single threaded
3982 	 * per stream by STREAMS. FS guarantees that all references
3983 	 * from top are gone before close is called. So there can't
3984 	 * be another close thread that has set CONDEMNED on this ill.
3985 	 * and cause ipsq_enter to return failure.
3986 	 */
3987 	ASSERT(success);
3988 	ipsq = ill->ill_phyint->phyint_ipsq;
3989 
3990 	/*
3991 	 * Mark it condemned. No new reference will be made to this ill.
3992 	 * Lookup functions will return an error. Threads that try to
3993 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
3994 	 * that the refcnt will drop down to zero.
3995 	 */
3996 	mutex_enter(&ill->ill_lock);
3997 	ill->ill_state_flags |= ILL_CONDEMNED;
3998 	for (ipif = ill->ill_ipif; ipif != NULL;
3999 	    ipif = ipif->ipif_next) {
4000 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4001 	}
4002 	/*
4003 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4004 	 * returns  error if ILL_CONDEMNED is set
4005 	 */
4006 	cv_broadcast(&ill->ill_cv);
4007 	mutex_exit(&ill->ill_lock);
4008 
4009 	/*
4010 	 * Send all the deferred DLPI messages downstream which came in
4011 	 * during the small window right before ipsq_enter(). We do this
4012 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4013 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4014 	 */
4015 	ill_dlpi_send_deferred(ill);
4016 
4017 	/*
4018 	 * Shut down fragmentation reassembly.
4019 	 * ill_frag_timer won't start a timer again.
4020 	 * Now cancel any existing timer
4021 	 */
4022 	(void) untimeout(ill->ill_frag_timer_id);
4023 	(void) ill_frag_timeout(ill, 0);
4024 
4025 	/*
4026 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4027 	 * this ill. Then wait for the refcnts to drop to zero.
4028 	 * ill_is_freeable checks whether the ill is really quiescent.
4029 	 * Then make sure that threads that are waiting to enter the
4030 	 * ipsq have seen the error returned by ipsq_enter and have
4031 	 * gone away. Then we call ill_delete_tail which does the
4032 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4033 	 */
4034 	ill_delete(ill);
4035 	mutex_enter(&ill->ill_lock);
4036 	while (!ill_is_freeable(ill))
4037 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4038 
4039 	while (ill->ill_waiters)
4040 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4041 
4042 	mutex_exit(&ill->ill_lock);
4043 
4044 	/*
4045 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4046 	 * it held until the end of the function since the cleanup
4047 	 * below needs to be able to use the ip_stack_t.
4048 	 */
4049 	netstack_hold(ipst->ips_netstack);
4050 
4051 	/* qprocsoff is done via ill_delete_tail */
4052 	ill_delete_tail(ill);
4053 	/*
4054 	 * synchronously wait for arp stream to unbind. After this, we
4055 	 * cannot get any data packets up from the driver.
4056 	 */
4057 	arp_unbind_complete(ill);
4058 	ASSERT(ill->ill_ipst == NULL);
4059 
4060 	/*
4061 	 * Walk through all conns and qenable those that have queued data.
4062 	 * Close synchronization needs this to
4063 	 * be done to ensure that all upper layers blocked
4064 	 * due to flow control to the closing device
4065 	 * get unblocked.
4066 	 */
4067 	ip1dbg(("ip_wsrv: walking\n"));
4068 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4069 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4070 	}
4071 
4072 	/*
4073 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4074 	 * stream is being torn down before ARP was plumbed (e.g.,
4075 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4076 	 * an error
4077 	 */
4078 	if (ai != NULL) {
4079 		ASSERT(!ill->ill_isv6);
4080 		mutex_enter(&ai->ai_lock);
4081 		ai->ai_ill = NULL;
4082 		if (ai->ai_arl == NULL) {
4083 			mutex_destroy(&ai->ai_lock);
4084 			kmem_free(ai, sizeof (*ai));
4085 		} else {
4086 			cv_signal(&ai->ai_ill_unplumb_done);
4087 			mutex_exit(&ai->ai_lock);
4088 		}
4089 	}
4090 
4091 	mutex_enter(&ipst->ips_ip_mi_lock);
4092 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4093 	mutex_exit(&ipst->ips_ip_mi_lock);
4094 
4095 	/*
4096 	 * credp could be null if the open didn't succeed and ip_modopen
4097 	 * itself calls ip_close.
4098 	 */
4099 	if (ill->ill_credp != NULL)
4100 		crfree(ill->ill_credp);
4101 
4102 	mutex_destroy(&ill->ill_saved_ire_lock);
4103 	mutex_destroy(&ill->ill_lock);
4104 	rw_destroy(&ill->ill_mcast_lock);
4105 	mutex_destroy(&ill->ill_mcast_serializer);
4106 	list_destroy(&ill->ill_nce);
4107 
4108 	/*
4109 	 * Now we are done with the module close pieces that
4110 	 * need the netstack_t.
4111 	 */
4112 	netstack_rele(ipst->ips_netstack);
4113 
4114 	mi_close_free((IDP)ill);
4115 	q->q_ptr = WR(q)->q_ptr = NULL;
4116 
4117 	ipsq_exit(ipsq);
4118 
4119 	return (0);
4120 }
4121 
4122 /*
4123  * This is called as part of close() for IP, UDP, ICMP, and RTS
4124  * in order to quiesce the conn.
4125  */
4126 void
4127 ip_quiesce_conn(conn_t *connp)
4128 {
4129 	boolean_t	drain_cleanup_reqd = B_FALSE;
4130 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4131 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4132 	ip_stack_t	*ipst;
4133 
4134 	ASSERT(!IPCL_IS_TCP(connp));
4135 	ipst = connp->conn_netstack->netstack_ip;
4136 
4137 	/*
4138 	 * Mark the conn as closing, and this conn must not be
4139 	 * inserted in future into any list. Eg. conn_drain_insert(),
4140 	 * won't insert this conn into the conn_drain_list.
4141 	 *
4142 	 * conn_idl, and conn_ilg cannot get set henceforth.
4143 	 */
4144 	mutex_enter(&connp->conn_lock);
4145 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4146 	connp->conn_state_flags |= CONN_CLOSING;
4147 	if (connp->conn_idl != NULL)
4148 		drain_cleanup_reqd = B_TRUE;
4149 	if (connp->conn_oper_pending_ill != NULL)
4150 		conn_ioctl_cleanup_reqd = B_TRUE;
4151 	if (connp->conn_dhcpinit_ill != NULL) {
4152 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4153 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4154 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4155 		connp->conn_dhcpinit_ill = NULL;
4156 	}
4157 	if (connp->conn_ilg != NULL)
4158 		ilg_cleanup_reqd = B_TRUE;
4159 	mutex_exit(&connp->conn_lock);
4160 
4161 	if (conn_ioctl_cleanup_reqd)
4162 		conn_ioctl_cleanup(connp);
4163 
4164 	if (is_system_labeled() && connp->conn_anon_port) {
4165 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4166 		    connp->conn_mlp_type, connp->conn_proto,
4167 		    ntohs(connp->conn_lport), B_FALSE);
4168 		connp->conn_anon_port = 0;
4169 	}
4170 	connp->conn_mlp_type = mlptSingle;
4171 
4172 	/*
4173 	 * Remove this conn from any fanout list it is on.
4174 	 * and then wait for any threads currently operating
4175 	 * on this endpoint to finish
4176 	 */
4177 	ipcl_hash_remove(connp);
4178 
4179 	/*
4180 	 * Remove this conn from the drain list, and do any other cleanup that
4181 	 * may be required.  (TCP conns are never flow controlled, and
4182 	 * conn_idl will be NULL.)
4183 	 */
4184 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4185 		idl_t *idl = connp->conn_idl;
4186 
4187 		mutex_enter(&idl->idl_lock);
4188 		conn_drain(connp, B_TRUE);
4189 		mutex_exit(&idl->idl_lock);
4190 	}
4191 
4192 	if (connp == ipst->ips_ip_g_mrouter)
4193 		(void) ip_mrouter_done(ipst);
4194 
4195 	if (ilg_cleanup_reqd)
4196 		ilg_delete_all(connp);
4197 
4198 	/*
4199 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4200 	 * callers from write side can't be there now because close
4201 	 * is in progress. The only other caller is ipcl_walk
4202 	 * which checks for the condemned flag.
4203 	 */
4204 	mutex_enter(&connp->conn_lock);
4205 	connp->conn_state_flags |= CONN_CONDEMNED;
4206 	while (connp->conn_ref != 1)
4207 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4208 	connp->conn_state_flags |= CONN_QUIESCED;
4209 	mutex_exit(&connp->conn_lock);
4210 }
4211 
4212 /* ARGSUSED */
4213 int
4214 ip_close(queue_t *q, int flags)
4215 {
4216 	conn_t		*connp;
4217 
4218 	/*
4219 	 * Call the appropriate delete routine depending on whether this is
4220 	 * a module or device.
4221 	 */
4222 	if (WR(q)->q_next != NULL) {
4223 		/* This is a module close */
4224 		return (ip_modclose((ill_t *)q->q_ptr));
4225 	}
4226 
4227 	connp = q->q_ptr;
4228 	ip_quiesce_conn(connp);
4229 
4230 	qprocsoff(q);
4231 
4232 	/*
4233 	 * Now we are truly single threaded on this stream, and can
4234 	 * delete the things hanging off the connp, and finally the connp.
4235 	 * We removed this connp from the fanout list, it cannot be
4236 	 * accessed thru the fanouts, and we already waited for the
4237 	 * conn_ref to drop to 0. We are already in close, so
4238 	 * there cannot be any other thread from the top. qprocsoff
4239 	 * has completed, and service has completed or won't run in
4240 	 * future.
4241 	 */
4242 	ASSERT(connp->conn_ref == 1);
4243 
4244 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4245 
4246 	connp->conn_ref--;
4247 	ipcl_conn_destroy(connp);
4248 
4249 	q->q_ptr = WR(q)->q_ptr = NULL;
4250 	return (0);
4251 }
4252 
4253 /*
4254  * Wapper around putnext() so that ip_rts_request can merely use
4255  * conn_recv.
4256  */
4257 /*ARGSUSED2*/
4258 static void
4259 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4260 {
4261 	conn_t *connp = (conn_t *)arg1;
4262 
4263 	putnext(connp->conn_rq, mp);
4264 }
4265 
4266 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4267 /* ARGSUSED */
4268 static void
4269 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4270 {
4271 	freemsg(mp);
4272 }
4273 
4274 /*
4275  * Called when the module is about to be unloaded
4276  */
4277 void
4278 ip_ddi_destroy(void)
4279 {
4280 	/* This needs to be called before destroying any transports. */
4281 	mutex_enter(&cpu_lock);
4282 	unregister_cpu_setup_func(ip_tp_cpu_update, NULL);
4283 	mutex_exit(&cpu_lock);
4284 
4285 	tnet_fini();
4286 
4287 	icmp_ddi_g_destroy();
4288 	rts_ddi_g_destroy();
4289 	udp_ddi_g_destroy();
4290 	sctp_ddi_g_destroy();
4291 	tcp_ddi_g_destroy();
4292 	ilb_ddi_g_destroy();
4293 	dce_g_destroy();
4294 	ipsec_policy_g_destroy();
4295 	ipcl_g_destroy();
4296 	ip_net_g_destroy();
4297 	ip_ire_g_fini();
4298 	inet_minor_destroy(ip_minor_arena_sa);
4299 #if defined(_LP64)
4300 	inet_minor_destroy(ip_minor_arena_la);
4301 #endif
4302 
4303 #ifdef DEBUG
4304 	list_destroy(&ip_thread_list);
4305 	rw_destroy(&ip_thread_rwlock);
4306 	tsd_destroy(&ip_thread_data);
4307 #endif
4308 
4309 	netstack_unregister(NS_IP);
4310 }
4311 
4312 /*
4313  * First step in cleanup.
4314  */
4315 /* ARGSUSED */
4316 static void
4317 ip_stack_shutdown(netstackid_t stackid, void *arg)
4318 {
4319 	ip_stack_t *ipst = (ip_stack_t *)arg;
4320 
4321 #ifdef NS_DEBUG
4322 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4323 #endif
4324 
4325 	/*
4326 	 * Perform cleanup for special interfaces (loopback and IPMP).
4327 	 */
4328 	ip_interface_cleanup(ipst);
4329 
4330 	/*
4331 	 * The *_hook_shutdown()s start the process of notifying any
4332 	 * consumers that things are going away.... nothing is destroyed.
4333 	 */
4334 	ipv4_hook_shutdown(ipst);
4335 	ipv6_hook_shutdown(ipst);
4336 	arp_hook_shutdown(ipst);
4337 
4338 	mutex_enter(&ipst->ips_capab_taskq_lock);
4339 	ipst->ips_capab_taskq_quit = B_TRUE;
4340 	cv_signal(&ipst->ips_capab_taskq_cv);
4341 	mutex_exit(&ipst->ips_capab_taskq_lock);
4342 }
4343 
4344 /*
4345  * Free the IP stack instance.
4346  */
4347 static void
4348 ip_stack_fini(netstackid_t stackid, void *arg)
4349 {
4350 	ip_stack_t *ipst = (ip_stack_t *)arg;
4351 	int ret;
4352 
4353 #ifdef NS_DEBUG
4354 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4355 #endif
4356 	/*
4357 	 * At this point, all of the notifications that the events and
4358 	 * protocols are going away have been run, meaning that we can
4359 	 * now set about starting to clean things up.
4360 	 */
4361 	ipobs_fini(ipst);
4362 	ipv4_hook_destroy(ipst);
4363 	ipv6_hook_destroy(ipst);
4364 	arp_hook_destroy(ipst);
4365 	ip_net_destroy(ipst);
4366 
4367 	ipmp_destroy(ipst);
4368 
4369 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4370 	ipst->ips_ip_mibkp = NULL;
4371 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4372 	ipst->ips_icmp_mibkp = NULL;
4373 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4374 	ipst->ips_ip_kstat = NULL;
4375 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4376 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4377 	ipst->ips_ip6_kstat = NULL;
4378 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4379 
4380 	kmem_free(ipst->ips_propinfo_tbl,
4381 	    ip_propinfo_count * sizeof (mod_prop_info_t));
4382 	ipst->ips_propinfo_tbl = NULL;
4383 
4384 	dce_stack_destroy(ipst);
4385 	ip_mrouter_stack_destroy(ipst);
4386 
4387 	ret = untimeout(ipst->ips_igmp_timeout_id);
4388 	if (ret == -1) {
4389 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4390 	} else {
4391 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4392 		ipst->ips_igmp_timeout_id = 0;
4393 	}
4394 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4395 	if (ret == -1) {
4396 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4397 	} else {
4398 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4399 		ipst->ips_igmp_slowtimeout_id = 0;
4400 	}
4401 	ret = untimeout(ipst->ips_mld_timeout_id);
4402 	if (ret == -1) {
4403 		ASSERT(ipst->ips_mld_timeout_id == 0);
4404 	} else {
4405 		ASSERT(ipst->ips_mld_timeout_id != 0);
4406 		ipst->ips_mld_timeout_id = 0;
4407 	}
4408 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4409 	if (ret == -1) {
4410 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4411 	} else {
4412 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4413 		ipst->ips_mld_slowtimeout_id = 0;
4414 	}
4415 
4416 	ip_ire_fini(ipst);
4417 	ip6_asp_free(ipst);
4418 	conn_drain_fini(ipst);
4419 	ipcl_destroy(ipst);
4420 
4421 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4422 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4423 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4424 	ipst->ips_ndp4 = NULL;
4425 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4426 	ipst->ips_ndp6 = NULL;
4427 
4428 	if (ipst->ips_loopback_ksp != NULL) {
4429 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4430 		ipst->ips_loopback_ksp = NULL;
4431 	}
4432 
4433 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4434 	cv_destroy(&ipst->ips_capab_taskq_cv);
4435 
4436 	rw_destroy(&ipst->ips_srcid_lock);
4437 
4438 	mutex_destroy(&ipst->ips_ip_mi_lock);
4439 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4440 
4441 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4442 	mutex_destroy(&ipst->ips_mld_timer_lock);
4443 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4444 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4445 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4446 	rw_destroy(&ipst->ips_ill_g_lock);
4447 
4448 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4449 	ipst->ips_phyint_g_list = NULL;
4450 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4451 	ipst->ips_ill_g_heads = NULL;
4452 
4453 	ldi_ident_release(ipst->ips_ldi_ident);
4454 	kmem_free(ipst, sizeof (*ipst));
4455 }
4456 
4457 /*
4458  * This function is called from the TSD destructor, and is used to debug
4459  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4460  * details.
4461  */
4462 static void
4463 ip_thread_exit(void *phash)
4464 {
4465 	th_hash_t *thh = phash;
4466 
4467 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4468 	list_remove(&ip_thread_list, thh);
4469 	rw_exit(&ip_thread_rwlock);
4470 	mod_hash_destroy_hash(thh->thh_hash);
4471 	kmem_free(thh, sizeof (*thh));
4472 }
4473 
4474 /*
4475  * Called when the IP kernel module is loaded into the kernel
4476  */
4477 void
4478 ip_ddi_init(void)
4479 {
4480 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4481 
4482 	/*
4483 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4484 	 * initial devices: ip, ip6, tcp, tcp6.
4485 	 */
4486 	/*
4487 	 * If this is a 64-bit kernel, then create two separate arenas -
4488 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4489 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4490 	 */
4491 	ip_minor_arena_la = NULL;
4492 	ip_minor_arena_sa = NULL;
4493 #if defined(_LP64)
4494 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4495 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4496 		cmn_err(CE_PANIC,
4497 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4498 	}
4499 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4500 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4501 		cmn_err(CE_PANIC,
4502 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4503 	}
4504 #else
4505 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4506 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4507 		cmn_err(CE_PANIC,
4508 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4509 	}
4510 #endif
4511 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4512 
4513 	ipcl_g_init();
4514 	ip_ire_g_init();
4515 	ip_net_g_init();
4516 
4517 #ifdef DEBUG
4518 	tsd_create(&ip_thread_data, ip_thread_exit);
4519 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4520 	list_create(&ip_thread_list, sizeof (th_hash_t),
4521 	    offsetof(th_hash_t, thh_link));
4522 #endif
4523 	ipsec_policy_g_init();
4524 	tcp_ddi_g_init();
4525 	sctp_ddi_g_init();
4526 	dce_g_init();
4527 
4528 	/*
4529 	 * We want to be informed each time a stack is created or
4530 	 * destroyed in the kernel, so we can maintain the
4531 	 * set of udp_stack_t's.
4532 	 */
4533 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4534 	    ip_stack_fini);
4535 
4536 	tnet_init();
4537 
4538 	udp_ddi_g_init();
4539 	rts_ddi_g_init();
4540 	icmp_ddi_g_init();
4541 	ilb_ddi_g_init();
4542 
4543 	/* This needs to be called after all transports are initialized. */
4544 	mutex_enter(&cpu_lock);
4545 	register_cpu_setup_func(ip_tp_cpu_update, NULL);
4546 	mutex_exit(&cpu_lock);
4547 }
4548 
4549 /*
4550  * Initialize the IP stack instance.
4551  */
4552 static void *
4553 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4554 {
4555 	ip_stack_t	*ipst;
4556 	size_t		arrsz;
4557 	major_t		major;
4558 
4559 #ifdef NS_DEBUG
4560 	printf("ip_stack_init(stack %d)\n", stackid);
4561 #endif
4562 
4563 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4564 	ipst->ips_netstack = ns;
4565 
4566 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4567 	    KM_SLEEP);
4568 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4569 	    KM_SLEEP);
4570 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4571 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4572 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4573 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4574 
4575 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4576 	ipst->ips_igmp_deferred_next = INFINITY;
4577 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4578 	ipst->ips_mld_deferred_next = INFINITY;
4579 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4580 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4581 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4582 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4583 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4584 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4585 
4586 	ipcl_init(ipst);
4587 	ip_ire_init(ipst);
4588 	ip6_asp_init(ipst);
4589 	ipif_init(ipst);
4590 	conn_drain_init(ipst);
4591 	ip_mrouter_stack_init(ipst);
4592 	dce_stack_init(ipst);
4593 
4594 	ipst->ips_ip_multirt_log_interval = 1000;
4595 
4596 	ipst->ips_ill_index = 1;
4597 
4598 	ipst->ips_saved_ip_forwarding = -1;
4599 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4600 
4601 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4602 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4603 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4604 
4605 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4606 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4607 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4608 	ipst->ips_ip6_kstat =
4609 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4610 
4611 	ipst->ips_ip_src_id = 1;
4612 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4613 
4614 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4615 
4616 	ip_net_init(ipst, ns);
4617 	ipv4_hook_init(ipst);
4618 	ipv6_hook_init(ipst);
4619 	arp_hook_init(ipst);
4620 	ipmp_init(ipst);
4621 	ipobs_init(ipst);
4622 
4623 	/*
4624 	 * Create the taskq dispatcher thread and initialize related stuff.
4625 	 */
4626 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4627 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4628 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4629 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4630 
4631 	major = mod_name_to_major(INET_NAME);
4632 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4633 	return (ipst);
4634 }
4635 
4636 /*
4637  * Allocate and initialize a DLPI template of the specified length.  (May be
4638  * called as writer.)
4639  */
4640 mblk_t *
4641 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4642 {
4643 	mblk_t	*mp;
4644 
4645 	mp = allocb(len, BPRI_MED);
4646 	if (!mp)
4647 		return (NULL);
4648 
4649 	/*
4650 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4651 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4652 	 * that other DLPI are M_PROTO.
4653 	 */
4654 	if (prim == DL_INFO_REQ) {
4655 		mp->b_datap->db_type = M_PCPROTO;
4656 	} else {
4657 		mp->b_datap->db_type = M_PROTO;
4658 	}
4659 
4660 	mp->b_wptr = mp->b_rptr + len;
4661 	bzero(mp->b_rptr, len);
4662 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4663 	return (mp);
4664 }
4665 
4666 /*
4667  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4668  */
4669 mblk_t *
4670 ip_dlnotify_alloc(uint_t notification, uint_t data)
4671 {
4672 	dl_notify_ind_t	*notifyp;
4673 	mblk_t		*mp;
4674 
4675 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4676 		return (NULL);
4677 
4678 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4679 	notifyp->dl_notification = notification;
4680 	notifyp->dl_data = data;
4681 	return (mp);
4682 }
4683 
4684 /*
4685  * Debug formatting routine.  Returns a character string representation of the
4686  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4687  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4688  *
4689  * Once the ndd table-printing interfaces are removed, this can be changed to
4690  * standard dotted-decimal form.
4691  */
4692 char *
4693 ip_dot_addr(ipaddr_t addr, char *buf)
4694 {
4695 	uint8_t *ap = (uint8_t *)&addr;
4696 
4697 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4698 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4699 	return (buf);
4700 }
4701 
4702 /*
4703  * Write the given MAC address as a printable string in the usual colon-
4704  * separated format.
4705  */
4706 const char *
4707 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4708 {
4709 	char *bp;
4710 
4711 	if (alen == 0 || buflen < 4)
4712 		return ("?");
4713 	bp = buf;
4714 	for (;;) {
4715 		/*
4716 		 * If there are more MAC address bytes available, but we won't
4717 		 * have any room to print them, then add "..." to the string
4718 		 * instead.  See below for the 'magic number' explanation.
4719 		 */
4720 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4721 			(void) strcpy(bp, "...");
4722 			break;
4723 		}
4724 		(void) sprintf(bp, "%02x", *addr++);
4725 		bp += 2;
4726 		if (--alen == 0)
4727 			break;
4728 		*bp++ = ':';
4729 		buflen -= 3;
4730 		/*
4731 		 * At this point, based on the first 'if' statement above,
4732 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4733 		 * buflen >= 4.  The first case leaves room for the final "xx"
4734 		 * number and trailing NUL byte.  The second leaves room for at
4735 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4736 		 * that statement.
4737 		 */
4738 	}
4739 	return (buf);
4740 }
4741 
4742 /*
4743  * Called when it is conceptually a ULP that would sent the packet
4744  * e.g., port unreachable and protocol unreachable. Check that the packet
4745  * would have passed the IPsec global policy before sending the error.
4746  *
4747  * Send an ICMP error after patching up the packet appropriately.
4748  * Uses ip_drop_input and bumps the appropriate MIB.
4749  */
4750 void
4751 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4752     ip_recv_attr_t *ira)
4753 {
4754 	ipha_t		*ipha;
4755 	boolean_t	secure;
4756 	ill_t		*ill = ira->ira_ill;
4757 	ip_stack_t	*ipst = ill->ill_ipst;
4758 	netstack_t	*ns = ipst->ips_netstack;
4759 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4760 
4761 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4762 
4763 	/*
4764 	 * We are generating an icmp error for some inbound packet.
4765 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4766 	 * Before we generate an error, check with global policy
4767 	 * to see whether this is allowed to enter the system. As
4768 	 * there is no "conn", we are checking with global policy.
4769 	 */
4770 	ipha = (ipha_t *)mp->b_rptr;
4771 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4772 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4773 		if (mp == NULL)
4774 			return;
4775 	}
4776 
4777 	/* We never send errors for protocols that we do implement */
4778 	if (ira->ira_protocol == IPPROTO_ICMP ||
4779 	    ira->ira_protocol == IPPROTO_IGMP) {
4780 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4781 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4782 		freemsg(mp);
4783 		return;
4784 	}
4785 	/*
4786 	 * Have to correct checksum since
4787 	 * the packet might have been
4788 	 * fragmented and the reassembly code in ip_rput
4789 	 * does not restore the IP checksum.
4790 	 */
4791 	ipha->ipha_hdr_checksum = 0;
4792 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4793 
4794 	switch (icmp_type) {
4795 	case ICMP_DEST_UNREACHABLE:
4796 		switch (icmp_code) {
4797 		case ICMP_PROTOCOL_UNREACHABLE:
4798 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4799 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4800 			break;
4801 		case ICMP_PORT_UNREACHABLE:
4802 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4803 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4804 			break;
4805 		}
4806 
4807 		icmp_unreachable(mp, icmp_code, ira);
4808 		break;
4809 	default:
4810 #ifdef DEBUG
4811 		panic("ip_fanout_send_icmp_v4: wrong type");
4812 		/*NOTREACHED*/
4813 #else
4814 		freemsg(mp);
4815 		break;
4816 #endif
4817 	}
4818 }
4819 
4820 /*
4821  * Used to send an ICMP error message when a packet is received for
4822  * a protocol that is not supported. The mblk passed as argument
4823  * is consumed by this function.
4824  */
4825 void
4826 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4827 {
4828 	ipha_t		*ipha;
4829 
4830 	ipha = (ipha_t *)mp->b_rptr;
4831 	if (ira->ira_flags & IRAF_IS_IPV4) {
4832 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4833 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4834 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4835 	} else {
4836 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4837 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4838 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4839 	}
4840 }
4841 
4842 /*
4843  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4844  * Handles IPv4 and IPv6.
4845  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4846  * Caller is responsible for dropping references to the conn.
4847  */
4848 void
4849 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4850     ip_recv_attr_t *ira)
4851 {
4852 	ill_t		*ill = ira->ira_ill;
4853 	ip_stack_t	*ipst = ill->ill_ipst;
4854 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4855 	boolean_t	secure;
4856 	uint_t		protocol = ira->ira_protocol;
4857 	iaflags_t	iraflags = ira->ira_flags;
4858 	queue_t		*rq;
4859 
4860 	secure = iraflags & IRAF_IPSEC_SECURE;
4861 
4862 	rq = connp->conn_rq;
4863 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4864 		switch (protocol) {
4865 		case IPPROTO_ICMPV6:
4866 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4867 			break;
4868 		case IPPROTO_ICMP:
4869 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4870 			break;
4871 		default:
4872 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4873 			break;
4874 		}
4875 		freemsg(mp);
4876 		return;
4877 	}
4878 
4879 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4880 
4881 	if (((iraflags & IRAF_IS_IPV4) ?
4882 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4883 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4884 	    secure) {
4885 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4886 		    ip6h, ira);
4887 		if (mp == NULL) {
4888 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4889 			/* Note that mp is NULL */
4890 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4891 			return;
4892 		}
4893 	}
4894 
4895 	if (iraflags & IRAF_ICMP_ERROR) {
4896 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4897 	} else {
4898 		ill_t *rill = ira->ira_rill;
4899 
4900 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4901 		ira->ira_ill = ira->ira_rill = NULL;
4902 		/* Send it upstream */
4903 		(connp->conn_recv)(connp, mp, NULL, ira);
4904 		ira->ira_ill = ill;
4905 		ira->ira_rill = rill;
4906 	}
4907 }
4908 
4909 /*
4910  * Handle protocols with which IP is less intimate.  There
4911  * can be more than one stream bound to a particular
4912  * protocol.  When this is the case, normally each one gets a copy
4913  * of any incoming packets.
4914  *
4915  * IPsec NOTE :
4916  *
4917  * Don't allow a secure packet going up a non-secure connection.
4918  * We don't allow this because
4919  *
4920  * 1) Reply might go out in clear which will be dropped at
4921  *    the sending side.
4922  * 2) If the reply goes out in clear it will give the
4923  *    adversary enough information for getting the key in
4924  *    most of the cases.
4925  *
4926  * Moreover getting a secure packet when we expect clear
4927  * implies that SA's were added without checking for
4928  * policy on both ends. This should not happen once ISAKMP
4929  * is used to negotiate SAs as SAs will be added only after
4930  * verifying the policy.
4931  *
4932  * Zones notes:
4933  * Earlier in ip_input on a system with multiple shared-IP zones we
4934  * duplicate the multicast and broadcast packets and send them up
4935  * with each explicit zoneid that exists on that ill.
4936  * This means that here we can match the zoneid with SO_ALLZONES being special.
4937  */
4938 void
4939 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
4940 {
4941 	mblk_t		*mp1;
4942 	ipaddr_t	laddr;
4943 	conn_t		*connp, *first_connp, *next_connp;
4944 	connf_t		*connfp;
4945 	ill_t		*ill = ira->ira_ill;
4946 	ip_stack_t	*ipst = ill->ill_ipst;
4947 
4948 	laddr = ipha->ipha_dst;
4949 
4950 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
4951 	mutex_enter(&connfp->connf_lock);
4952 	connp = connfp->connf_head;
4953 	for (connp = connfp->connf_head; connp != NULL;
4954 	    connp = connp->conn_next) {
4955 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4956 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4957 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4958 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
4959 			break;
4960 		}
4961 	}
4962 
4963 	if (connp == NULL) {
4964 		/*
4965 		 * No one bound to these addresses.  Is
4966 		 * there a client that wants all
4967 		 * unclaimed datagrams?
4968 		 */
4969 		mutex_exit(&connfp->connf_lock);
4970 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4971 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4972 		return;
4973 	}
4974 
4975 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
4976 
4977 	CONN_INC_REF(connp);
4978 	first_connp = connp;
4979 	connp = connp->conn_next;
4980 
4981 	for (;;) {
4982 		while (connp != NULL) {
4983 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4984 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4985 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4986 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
4987 			    ira, connp)))
4988 				break;
4989 			connp = connp->conn_next;
4990 		}
4991 
4992 		if (connp == NULL) {
4993 			/* No more interested clients */
4994 			connp = first_connp;
4995 			break;
4996 		}
4997 		if (((mp1 = dupmsg(mp)) == NULL) &&
4998 		    ((mp1 = copymsg(mp)) == NULL)) {
4999 			/* Memory allocation failed */
5000 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5001 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5002 			connp = first_connp;
5003 			break;
5004 		}
5005 
5006 		CONN_INC_REF(connp);
5007 		mutex_exit(&connfp->connf_lock);
5008 
5009 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5010 		    ira);
5011 
5012 		mutex_enter(&connfp->connf_lock);
5013 		/* Follow the next pointer before releasing the conn. */
5014 		next_connp = connp->conn_next;
5015 		CONN_DEC_REF(connp);
5016 		connp = next_connp;
5017 	}
5018 
5019 	/* Last one.  Send it upstream. */
5020 	mutex_exit(&connfp->connf_lock);
5021 
5022 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5023 
5024 	CONN_DEC_REF(connp);
5025 }
5026 
5027 /*
5028  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5029  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5030  * is not consumed.
5031  *
5032  * One of three things can happen, all of which affect the passed-in mblk:
5033  *
5034  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5035  *
5036  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5037  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5038  *
5039  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5040  */
5041 mblk_t *
5042 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5043 {
5044 	int shift, plen, iph_len;
5045 	ipha_t *ipha;
5046 	udpha_t *udpha;
5047 	uint32_t *spi;
5048 	uint32_t esp_ports;
5049 	uint8_t *orptr;
5050 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5051 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5052 
5053 	ipha = (ipha_t *)mp->b_rptr;
5054 	iph_len = ira->ira_ip_hdr_length;
5055 	plen = ira->ira_pktlen;
5056 
5057 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5058 		/*
5059 		 * Most likely a keepalive for the benefit of an intervening
5060 		 * NAT.  These aren't for us, per se, so drop it.
5061 		 *
5062 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5063 		 * byte packets (keepalives are 1-byte), but we'll drop them
5064 		 * also.
5065 		 */
5066 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5067 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5068 		return (NULL);
5069 	}
5070 
5071 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5072 		/* might as well pull it all up - it might be ESP. */
5073 		if (!pullupmsg(mp, -1)) {
5074 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5075 			    DROPPER(ipss, ipds_esp_nomem),
5076 			    &ipss->ipsec_dropper);
5077 			return (NULL);
5078 		}
5079 
5080 		ipha = (ipha_t *)mp->b_rptr;
5081 	}
5082 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5083 	if (*spi == 0) {
5084 		/* UDP packet - remove 0-spi. */
5085 		shift = sizeof (uint32_t);
5086 	} else {
5087 		/* ESP-in-UDP packet - reduce to ESP. */
5088 		ipha->ipha_protocol = IPPROTO_ESP;
5089 		shift = sizeof (udpha_t);
5090 	}
5091 
5092 	/* Fix IP header */
5093 	ira->ira_pktlen = (plen - shift);
5094 	ipha->ipha_length = htons(ira->ira_pktlen);
5095 	ipha->ipha_hdr_checksum = 0;
5096 
5097 	orptr = mp->b_rptr;
5098 	mp->b_rptr += shift;
5099 
5100 	udpha = (udpha_t *)(orptr + iph_len);
5101 	if (*spi == 0) {
5102 		ASSERT((uint8_t *)ipha == orptr);
5103 		udpha->uha_length = htons(plen - shift - iph_len);
5104 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5105 		esp_ports = 0;
5106 	} else {
5107 		esp_ports = *((uint32_t *)udpha);
5108 		ASSERT(esp_ports != 0);
5109 	}
5110 	ovbcopy(orptr, orptr + shift, iph_len);
5111 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5112 		ipha = (ipha_t *)(orptr + shift);
5113 
5114 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5115 		ira->ira_esp_udp_ports = esp_ports;
5116 		ip_fanout_v4(mp, ipha, ira);
5117 		return (NULL);
5118 	}
5119 	return (mp);
5120 }
5121 
5122 /*
5123  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5124  * Handles IPv4 and IPv6.
5125  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5126  * Caller is responsible for dropping references to the conn.
5127  */
5128 void
5129 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5130     ip_recv_attr_t *ira)
5131 {
5132 	ill_t		*ill = ira->ira_ill;
5133 	ip_stack_t	*ipst = ill->ill_ipst;
5134 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5135 	boolean_t	secure;
5136 	iaflags_t	iraflags = ira->ira_flags;
5137 
5138 	secure = iraflags & IRAF_IPSEC_SECURE;
5139 
5140 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5141 	    !canputnext(connp->conn_rq)) {
5142 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5143 		freemsg(mp);
5144 		return;
5145 	}
5146 
5147 	if (((iraflags & IRAF_IS_IPV4) ?
5148 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5149 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5150 	    secure) {
5151 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5152 		    ip6h, ira);
5153 		if (mp == NULL) {
5154 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5155 			/* Note that mp is NULL */
5156 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5157 			return;
5158 		}
5159 	}
5160 
5161 	/*
5162 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5163 	 * check. Only ip_fanout_v4 has that check.
5164 	 */
5165 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5166 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5167 	} else {
5168 		ill_t *rill = ira->ira_rill;
5169 
5170 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5171 		ira->ira_ill = ira->ira_rill = NULL;
5172 		/* Send it upstream */
5173 		(connp->conn_recv)(connp, mp, NULL, ira);
5174 		ira->ira_ill = ill;
5175 		ira->ira_rill = rill;
5176 	}
5177 }
5178 
5179 /*
5180  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5181  * (Unicast fanout is handled in ip_input_v4.)
5182  *
5183  * If SO_REUSEADDR is set all multicast and broadcast packets
5184  * will be delivered to all conns bound to the same port.
5185  *
5186  * If there is at least one matching AF_INET receiver, then we will
5187  * ignore any AF_INET6 receivers.
5188  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5189  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5190  * packets.
5191  *
5192  * Zones notes:
5193  * Earlier in ip_input on a system with multiple shared-IP zones we
5194  * duplicate the multicast and broadcast packets and send them up
5195  * with each explicit zoneid that exists on that ill.
5196  * This means that here we can match the zoneid with SO_ALLZONES being special.
5197  */
5198 void
5199 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5200     ip_recv_attr_t *ira)
5201 {
5202 	ipaddr_t	laddr;
5203 	in6_addr_t	v6faddr;
5204 	conn_t		*connp;
5205 	connf_t		*connfp;
5206 	ipaddr_t	faddr;
5207 	ill_t		*ill = ira->ira_ill;
5208 	ip_stack_t	*ipst = ill->ill_ipst;
5209 
5210 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5211 
5212 	laddr = ipha->ipha_dst;
5213 	faddr = ipha->ipha_src;
5214 
5215 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5216 	mutex_enter(&connfp->connf_lock);
5217 	connp = connfp->connf_head;
5218 
5219 	/*
5220 	 * If SO_REUSEADDR has been set on the first we send the
5221 	 * packet to all clients that have joined the group and
5222 	 * match the port.
5223 	 */
5224 	while (connp != NULL) {
5225 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5226 		    conn_wantpacket(connp, ira, ipha) &&
5227 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5228 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5229 			break;
5230 		connp = connp->conn_next;
5231 	}
5232 
5233 	if (connp == NULL)
5234 		goto notfound;
5235 
5236 	CONN_INC_REF(connp);
5237 
5238 	if (connp->conn_reuseaddr) {
5239 		conn_t		*first_connp = connp;
5240 		conn_t		*next_connp;
5241 		mblk_t		*mp1;
5242 
5243 		connp = connp->conn_next;
5244 		for (;;) {
5245 			while (connp != NULL) {
5246 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5247 				    fport, faddr) &&
5248 				    conn_wantpacket(connp, ira, ipha) &&
5249 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5250 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5251 				    ira, connp)))
5252 					break;
5253 				connp = connp->conn_next;
5254 			}
5255 			if (connp == NULL) {
5256 				/* No more interested clients */
5257 				connp = first_connp;
5258 				break;
5259 			}
5260 			if (((mp1 = dupmsg(mp)) == NULL) &&
5261 			    ((mp1 = copymsg(mp)) == NULL)) {
5262 				/* Memory allocation failed */
5263 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5264 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5265 				connp = first_connp;
5266 				break;
5267 			}
5268 			CONN_INC_REF(connp);
5269 			mutex_exit(&connfp->connf_lock);
5270 
5271 			IP_STAT(ipst, ip_udp_fanmb);
5272 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5273 			    NULL, ira);
5274 			mutex_enter(&connfp->connf_lock);
5275 			/* Follow the next pointer before releasing the conn */
5276 			next_connp = connp->conn_next;
5277 			CONN_DEC_REF(connp);
5278 			connp = next_connp;
5279 		}
5280 	}
5281 
5282 	/* Last one.  Send it upstream. */
5283 	mutex_exit(&connfp->connf_lock);
5284 	IP_STAT(ipst, ip_udp_fanmb);
5285 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5286 	CONN_DEC_REF(connp);
5287 	return;
5288 
5289 notfound:
5290 	mutex_exit(&connfp->connf_lock);
5291 	/*
5292 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5293 	 * have already been matched above, since they live in the IPv4
5294 	 * fanout tables. This implies we only need to
5295 	 * check for IPv6 in6addr_any endpoints here.
5296 	 * Thus we compare using ipv6_all_zeros instead of the destination
5297 	 * address, except for the multicast group membership lookup which
5298 	 * uses the IPv4 destination.
5299 	 */
5300 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5301 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5302 	mutex_enter(&connfp->connf_lock);
5303 	connp = connfp->connf_head;
5304 	/*
5305 	 * IPv4 multicast packet being delivered to an AF_INET6
5306 	 * in6addr_any endpoint.
5307 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5308 	 * and not conn_wantpacket_v6() since any multicast membership is
5309 	 * for an IPv4-mapped multicast address.
5310 	 */
5311 	while (connp != NULL) {
5312 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5313 		    fport, v6faddr) &&
5314 		    conn_wantpacket(connp, ira, ipha) &&
5315 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5316 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5317 			break;
5318 		connp = connp->conn_next;
5319 	}
5320 
5321 	if (connp == NULL) {
5322 		/*
5323 		 * No one bound to this port.  Is
5324 		 * there a client that wants all
5325 		 * unclaimed datagrams?
5326 		 */
5327 		mutex_exit(&connfp->connf_lock);
5328 
5329 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5330 		    NULL) {
5331 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5332 			ip_fanout_proto_v4(mp, ipha, ira);
5333 		} else {
5334 			/*
5335 			 * We used to attempt to send an icmp error here, but
5336 			 * since this is known to be a multicast packet
5337 			 * and we don't send icmp errors in response to
5338 			 * multicast, just drop the packet and give up sooner.
5339 			 */
5340 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5341 			freemsg(mp);
5342 		}
5343 		return;
5344 	}
5345 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5346 
5347 	/*
5348 	 * If SO_REUSEADDR has been set on the first we send the
5349 	 * packet to all clients that have joined the group and
5350 	 * match the port.
5351 	 */
5352 	if (connp->conn_reuseaddr) {
5353 		conn_t		*first_connp = connp;
5354 		conn_t		*next_connp;
5355 		mblk_t		*mp1;
5356 
5357 		CONN_INC_REF(connp);
5358 		connp = connp->conn_next;
5359 		for (;;) {
5360 			while (connp != NULL) {
5361 				if (IPCL_UDP_MATCH_V6(connp, lport,
5362 				    ipv6_all_zeros, fport, v6faddr) &&
5363 				    conn_wantpacket(connp, ira, ipha) &&
5364 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5365 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5366 				    ira, connp)))
5367 					break;
5368 				connp = connp->conn_next;
5369 			}
5370 			if (connp == NULL) {
5371 				/* No more interested clients */
5372 				connp = first_connp;
5373 				break;
5374 			}
5375 			if (((mp1 = dupmsg(mp)) == NULL) &&
5376 			    ((mp1 = copymsg(mp)) == NULL)) {
5377 				/* Memory allocation failed */
5378 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5379 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5380 				connp = first_connp;
5381 				break;
5382 			}
5383 			CONN_INC_REF(connp);
5384 			mutex_exit(&connfp->connf_lock);
5385 
5386 			IP_STAT(ipst, ip_udp_fanmb);
5387 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5388 			    NULL, ira);
5389 			mutex_enter(&connfp->connf_lock);
5390 			/* Follow the next pointer before releasing the conn */
5391 			next_connp = connp->conn_next;
5392 			CONN_DEC_REF(connp);
5393 			connp = next_connp;
5394 		}
5395 	}
5396 
5397 	/* Last one.  Send it upstream. */
5398 	mutex_exit(&connfp->connf_lock);
5399 	IP_STAT(ipst, ip_udp_fanmb);
5400 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5401 	CONN_DEC_REF(connp);
5402 }
5403 
5404 /*
5405  * Split an incoming packet's IPv4 options into the label and the other options.
5406  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5407  * clearing out any leftover label or options.
5408  * Otherwise it just makes ipp point into the packet.
5409  *
5410  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5411  */
5412 int
5413 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5414 {
5415 	uchar_t		*opt;
5416 	uint32_t	totallen;
5417 	uint32_t	optval;
5418 	uint32_t	optlen;
5419 
5420 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5421 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5422 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5423 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5424 
5425 	/*
5426 	 * Get length (in 4 byte octets) of IP header options.
5427 	 */
5428 	totallen = ipha->ipha_version_and_hdr_length -
5429 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5430 
5431 	if (totallen == 0) {
5432 		if (!allocate)
5433 			return (0);
5434 
5435 		/* Clear out anything from a previous packet */
5436 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5437 			kmem_free(ipp->ipp_ipv4_options,
5438 			    ipp->ipp_ipv4_options_len);
5439 			ipp->ipp_ipv4_options = NULL;
5440 			ipp->ipp_ipv4_options_len = 0;
5441 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5442 		}
5443 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5444 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5445 			ipp->ipp_label_v4 = NULL;
5446 			ipp->ipp_label_len_v4 = 0;
5447 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5448 		}
5449 		return (0);
5450 	}
5451 
5452 	totallen <<= 2;
5453 	opt = (uchar_t *)&ipha[1];
5454 	if (!is_system_labeled()) {
5455 
5456 	copyall:
5457 		if (!allocate) {
5458 			if (totallen != 0) {
5459 				ipp->ipp_ipv4_options = opt;
5460 				ipp->ipp_ipv4_options_len = totallen;
5461 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5462 			}
5463 			return (0);
5464 		}
5465 		/* Just copy all of options */
5466 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5467 			if (totallen == ipp->ipp_ipv4_options_len) {
5468 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5469 				return (0);
5470 			}
5471 			kmem_free(ipp->ipp_ipv4_options,
5472 			    ipp->ipp_ipv4_options_len);
5473 			ipp->ipp_ipv4_options = NULL;
5474 			ipp->ipp_ipv4_options_len = 0;
5475 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5476 		}
5477 		if (totallen == 0)
5478 			return (0);
5479 
5480 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5481 		if (ipp->ipp_ipv4_options == NULL)
5482 			return (ENOMEM);
5483 		ipp->ipp_ipv4_options_len = totallen;
5484 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5485 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5486 		return (0);
5487 	}
5488 
5489 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5490 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5491 		ipp->ipp_label_v4 = NULL;
5492 		ipp->ipp_label_len_v4 = 0;
5493 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5494 	}
5495 
5496 	/*
5497 	 * Search for CIPSO option.
5498 	 * We assume CIPSO is first in options if it is present.
5499 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5500 	 * prior to the CIPSO option.
5501 	 */
5502 	while (totallen != 0) {
5503 		switch (optval = opt[IPOPT_OPTVAL]) {
5504 		case IPOPT_EOL:
5505 			return (0);
5506 		case IPOPT_NOP:
5507 			optlen = 1;
5508 			break;
5509 		default:
5510 			if (totallen <= IPOPT_OLEN)
5511 				return (EINVAL);
5512 			optlen = opt[IPOPT_OLEN];
5513 			if (optlen < 2)
5514 				return (EINVAL);
5515 		}
5516 		if (optlen > totallen)
5517 			return (EINVAL);
5518 
5519 		switch (optval) {
5520 		case IPOPT_COMSEC:
5521 			if (!allocate) {
5522 				ipp->ipp_label_v4 = opt;
5523 				ipp->ipp_label_len_v4 = optlen;
5524 				ipp->ipp_fields |= IPPF_LABEL_V4;
5525 			} else {
5526 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5527 				    KM_NOSLEEP);
5528 				if (ipp->ipp_label_v4 == NULL)
5529 					return (ENOMEM);
5530 				ipp->ipp_label_len_v4 = optlen;
5531 				ipp->ipp_fields |= IPPF_LABEL_V4;
5532 				bcopy(opt, ipp->ipp_label_v4, optlen);
5533 			}
5534 			totallen -= optlen;
5535 			opt += optlen;
5536 
5537 			/* Skip padding bytes until we get to a multiple of 4 */
5538 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5539 				totallen--;
5540 				opt++;
5541 			}
5542 			/* Remaining as ipp_ipv4_options */
5543 			goto copyall;
5544 		}
5545 		totallen -= optlen;
5546 		opt += optlen;
5547 	}
5548 	/* No CIPSO found; return everything as ipp_ipv4_options */
5549 	totallen = ipha->ipha_version_and_hdr_length -
5550 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5551 	totallen <<= 2;
5552 	opt = (uchar_t *)&ipha[1];
5553 	goto copyall;
5554 }
5555 
5556 /*
5557  * Efficient versions of lookup for an IRE when we only
5558  * match the address.
5559  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5560  * Does not handle multicast addresses.
5561  */
5562 uint_t
5563 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5564 {
5565 	ire_t *ire;
5566 	uint_t result;
5567 
5568 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5569 	ASSERT(ire != NULL);
5570 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5571 		result = IRE_NOROUTE;
5572 	else
5573 		result = ire->ire_type;
5574 	ire_refrele(ire);
5575 	return (result);
5576 }
5577 
5578 /*
5579  * Efficient versions of lookup for an IRE when we only
5580  * match the address.
5581  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5582  * Does not handle multicast addresses.
5583  */
5584 uint_t
5585 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5586 {
5587 	ire_t *ire;
5588 	uint_t result;
5589 
5590 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5591 	ASSERT(ire != NULL);
5592 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5593 		result = IRE_NOROUTE;
5594 	else
5595 		result = ire->ire_type;
5596 	ire_refrele(ire);
5597 	return (result);
5598 }
5599 
5600 /*
5601  * Nobody should be sending
5602  * packets up this stream
5603  */
5604 static void
5605 ip_lrput(queue_t *q, mblk_t *mp)
5606 {
5607 	switch (mp->b_datap->db_type) {
5608 	case M_FLUSH:
5609 		/* Turn around */
5610 		if (*mp->b_rptr & FLUSHW) {
5611 			*mp->b_rptr &= ~FLUSHR;
5612 			qreply(q, mp);
5613 			return;
5614 		}
5615 		break;
5616 	}
5617 	freemsg(mp);
5618 }
5619 
5620 /* Nobody should be sending packets down this stream */
5621 /* ARGSUSED */
5622 void
5623 ip_lwput(queue_t *q, mblk_t *mp)
5624 {
5625 	freemsg(mp);
5626 }
5627 
5628 /*
5629  * Move the first hop in any source route to ipha_dst and remove that part of
5630  * the source route.  Called by other protocols.  Errors in option formatting
5631  * are ignored - will be handled by ip_output_options. Return the final
5632  * destination (either ipha_dst or the last entry in a source route.)
5633  */
5634 ipaddr_t
5635 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5636 {
5637 	ipoptp_t	opts;
5638 	uchar_t		*opt;
5639 	uint8_t		optval;
5640 	uint8_t		optlen;
5641 	ipaddr_t	dst;
5642 	int		i;
5643 	ip_stack_t	*ipst = ns->netstack_ip;
5644 
5645 	ip2dbg(("ip_massage_options\n"));
5646 	dst = ipha->ipha_dst;
5647 	for (optval = ipoptp_first(&opts, ipha);
5648 	    optval != IPOPT_EOL;
5649 	    optval = ipoptp_next(&opts)) {
5650 		opt = opts.ipoptp_cur;
5651 		switch (optval) {
5652 			uint8_t off;
5653 		case IPOPT_SSRR:
5654 		case IPOPT_LSRR:
5655 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5656 				ip1dbg(("ip_massage_options: bad src route\n"));
5657 				break;
5658 			}
5659 			optlen = opts.ipoptp_len;
5660 			off = opt[IPOPT_OFFSET];
5661 			off--;
5662 		redo_srr:
5663 			if (optlen < IP_ADDR_LEN ||
5664 			    off > optlen - IP_ADDR_LEN) {
5665 				/* End of source route */
5666 				ip1dbg(("ip_massage_options: end of SR\n"));
5667 				break;
5668 			}
5669 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5670 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5671 			    ntohl(dst)));
5672 			/*
5673 			 * Check if our address is present more than
5674 			 * once as consecutive hops in source route.
5675 			 * XXX verify per-interface ip_forwarding
5676 			 * for source route?
5677 			 */
5678 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5679 				off += IP_ADDR_LEN;
5680 				goto redo_srr;
5681 			}
5682 			if (dst == htonl(INADDR_LOOPBACK)) {
5683 				ip1dbg(("ip_massage_options: loopback addr in "
5684 				    "source route!\n"));
5685 				break;
5686 			}
5687 			/*
5688 			 * Update ipha_dst to be the first hop and remove the
5689 			 * first hop from the source route (by overwriting
5690 			 * part of the option with NOP options).
5691 			 */
5692 			ipha->ipha_dst = dst;
5693 			/* Put the last entry in dst */
5694 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5695 			    3;
5696 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5697 
5698 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5699 			    ntohl(dst)));
5700 			/* Move down and overwrite */
5701 			opt[IP_ADDR_LEN] = opt[0];
5702 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5703 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5704 			for (i = 0; i < IP_ADDR_LEN; i++)
5705 				opt[i] = IPOPT_NOP;
5706 			break;
5707 		}
5708 	}
5709 	return (dst);
5710 }
5711 
5712 /*
5713  * Return the network mask
5714  * associated with the specified address.
5715  */
5716 ipaddr_t
5717 ip_net_mask(ipaddr_t addr)
5718 {
5719 	uchar_t	*up = (uchar_t *)&addr;
5720 	ipaddr_t mask = 0;
5721 	uchar_t	*maskp = (uchar_t *)&mask;
5722 
5723 #if defined(__i386) || defined(__amd64)
5724 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5725 #endif
5726 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5727 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5728 #endif
5729 	if (CLASSD(addr)) {
5730 		maskp[0] = 0xF0;
5731 		return (mask);
5732 	}
5733 
5734 	/* We assume Class E default netmask to be 32 */
5735 	if (CLASSE(addr))
5736 		return (0xffffffffU);
5737 
5738 	if (addr == 0)
5739 		return (0);
5740 	maskp[0] = 0xFF;
5741 	if ((up[0] & 0x80) == 0)
5742 		return (mask);
5743 
5744 	maskp[1] = 0xFF;
5745 	if ((up[0] & 0xC0) == 0x80)
5746 		return (mask);
5747 
5748 	maskp[2] = 0xFF;
5749 	if ((up[0] & 0xE0) == 0xC0)
5750 		return (mask);
5751 
5752 	/* Otherwise return no mask */
5753 	return ((ipaddr_t)0);
5754 }
5755 
5756 /* Name/Value Table Lookup Routine */
5757 char *
5758 ip_nv_lookup(nv_t *nv, int value)
5759 {
5760 	if (!nv)
5761 		return (NULL);
5762 	for (; nv->nv_name; nv++) {
5763 		if (nv->nv_value == value)
5764 			return (nv->nv_name);
5765 	}
5766 	return ("unknown");
5767 }
5768 
5769 static int
5770 ip_wait_for_info_ack(ill_t *ill)
5771 {
5772 	int err;
5773 
5774 	mutex_enter(&ill->ill_lock);
5775 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5776 		/*
5777 		 * Return value of 0 indicates a pending signal.
5778 		 */
5779 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5780 		if (err == 0) {
5781 			mutex_exit(&ill->ill_lock);
5782 			return (EINTR);
5783 		}
5784 	}
5785 	mutex_exit(&ill->ill_lock);
5786 	/*
5787 	 * ip_rput_other could have set an error  in ill_error on
5788 	 * receipt of M_ERROR.
5789 	 */
5790 	return (ill->ill_error);
5791 }
5792 
5793 /*
5794  * This is a module open, i.e. this is a control stream for access
5795  * to a DLPI device.  We allocate an ill_t as the instance data in
5796  * this case.
5797  */
5798 static int
5799 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5800 {
5801 	ill_t	*ill;
5802 	int	err;
5803 	zoneid_t zoneid;
5804 	netstack_t *ns;
5805 	ip_stack_t *ipst;
5806 
5807 	/*
5808 	 * Prevent unprivileged processes from pushing IP so that
5809 	 * they can't send raw IP.
5810 	 */
5811 	if (secpolicy_net_rawaccess(credp) != 0)
5812 		return (EPERM);
5813 
5814 	ns = netstack_find_by_cred(credp);
5815 	ASSERT(ns != NULL);
5816 	ipst = ns->netstack_ip;
5817 	ASSERT(ipst != NULL);
5818 
5819 	/*
5820 	 * For exclusive stacks we set the zoneid to zero
5821 	 * to make IP operate as if in the global zone.
5822 	 */
5823 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5824 		zoneid = GLOBAL_ZONEID;
5825 	else
5826 		zoneid = crgetzoneid(credp);
5827 
5828 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5829 	q->q_ptr = WR(q)->q_ptr = ill;
5830 	ill->ill_ipst = ipst;
5831 	ill->ill_zoneid = zoneid;
5832 
5833 	/*
5834 	 * ill_init initializes the ill fields and then sends down
5835 	 * down a DL_INFO_REQ after calling qprocson.
5836 	 */
5837 	err = ill_init(q, ill);
5838 
5839 	if (err != 0) {
5840 		mi_free(ill);
5841 		netstack_rele(ipst->ips_netstack);
5842 		q->q_ptr = NULL;
5843 		WR(q)->q_ptr = NULL;
5844 		return (err);
5845 	}
5846 
5847 	/*
5848 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5849 	 *
5850 	 * ill_init initializes the ipsq marking this thread as
5851 	 * writer
5852 	 */
5853 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5854 	err = ip_wait_for_info_ack(ill);
5855 	if (err == 0)
5856 		ill->ill_credp = credp;
5857 	else
5858 		goto fail;
5859 
5860 	crhold(credp);
5861 
5862 	mutex_enter(&ipst->ips_ip_mi_lock);
5863 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5864 	    sflag, credp);
5865 	mutex_exit(&ipst->ips_ip_mi_lock);
5866 fail:
5867 	if (err) {
5868 		(void) ip_close(q, 0);
5869 		return (err);
5870 	}
5871 	return (0);
5872 }
5873 
5874 /* For /dev/ip aka AF_INET open */
5875 int
5876 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5877 {
5878 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5879 }
5880 
5881 /* For /dev/ip6 aka AF_INET6 open */
5882 int
5883 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5884 {
5885 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5886 }
5887 
5888 /* IP open routine. */
5889 int
5890 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5891     boolean_t isv6)
5892 {
5893 	conn_t 		*connp;
5894 	major_t		maj;
5895 	zoneid_t	zoneid;
5896 	netstack_t	*ns;
5897 	ip_stack_t	*ipst;
5898 
5899 	/* Allow reopen. */
5900 	if (q->q_ptr != NULL)
5901 		return (0);
5902 
5903 	if (sflag & MODOPEN) {
5904 		/* This is a module open */
5905 		return (ip_modopen(q, devp, flag, sflag, credp));
5906 	}
5907 
5908 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5909 		/*
5910 		 * Non streams based socket looking for a stream
5911 		 * to access IP
5912 		 */
5913 		return (ip_helper_stream_setup(q, devp, flag, sflag,
5914 		    credp, isv6));
5915 	}
5916 
5917 	ns = netstack_find_by_cred(credp);
5918 	ASSERT(ns != NULL);
5919 	ipst = ns->netstack_ip;
5920 	ASSERT(ipst != NULL);
5921 
5922 	/*
5923 	 * For exclusive stacks we set the zoneid to zero
5924 	 * to make IP operate as if in the global zone.
5925 	 */
5926 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5927 		zoneid = GLOBAL_ZONEID;
5928 	else
5929 		zoneid = crgetzoneid(credp);
5930 
5931 	/*
5932 	 * We are opening as a device. This is an IP client stream, and we
5933 	 * allocate an conn_t as the instance data.
5934 	 */
5935 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
5936 
5937 	/*
5938 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
5939 	 * done by netstack_find_by_cred()
5940 	 */
5941 	netstack_rele(ipst->ips_netstack);
5942 
5943 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
5944 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
5945 	connp->conn_ixa->ixa_zoneid = zoneid;
5946 	connp->conn_zoneid = zoneid;
5947 
5948 	connp->conn_rq = q;
5949 	q->q_ptr = WR(q)->q_ptr = connp;
5950 
5951 	/* Minor tells us which /dev entry was opened */
5952 	if (isv6) {
5953 		connp->conn_family = AF_INET6;
5954 		connp->conn_ipversion = IPV6_VERSION;
5955 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
5956 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
5957 	} else {
5958 		connp->conn_family = AF_INET;
5959 		connp->conn_ipversion = IPV4_VERSION;
5960 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
5961 	}
5962 
5963 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
5964 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
5965 		connp->conn_minor_arena = ip_minor_arena_la;
5966 	} else {
5967 		/*
5968 		 * Either minor numbers in the large arena were exhausted
5969 		 * or a non socket application is doing the open.
5970 		 * Try to allocate from the small arena.
5971 		 */
5972 		if ((connp->conn_dev =
5973 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
5974 			/* CONN_DEC_REF takes care of netstack_rele() */
5975 			q->q_ptr = WR(q)->q_ptr = NULL;
5976 			CONN_DEC_REF(connp);
5977 			return (EBUSY);
5978 		}
5979 		connp->conn_minor_arena = ip_minor_arena_sa;
5980 	}
5981 
5982 	maj = getemajor(*devp);
5983 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
5984 
5985 	/*
5986 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
5987 	 */
5988 	connp->conn_cred = credp;
5989 	connp->conn_cpid = curproc->p_pid;
5990 	/* Cache things in ixa without an extra refhold */
5991 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
5992 	connp->conn_ixa->ixa_cred = connp->conn_cred;
5993 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
5994 	if (is_system_labeled())
5995 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
5996 
5997 	/*
5998 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
5999 	 */
6000 	connp->conn_recv = ip_conn_input;
6001 	connp->conn_recvicmp = ip_conn_input_icmp;
6002 
6003 	crhold(connp->conn_cred);
6004 
6005 	/*
6006 	 * If the caller has the process-wide flag set, then default to MAC
6007 	 * exempt mode.  This allows read-down to unlabeled hosts.
6008 	 */
6009 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6010 		connp->conn_mac_mode = CONN_MAC_AWARE;
6011 
6012 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6013 
6014 	connp->conn_rq = q;
6015 	connp->conn_wq = WR(q);
6016 
6017 	/* Non-zero default values */
6018 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6019 
6020 	/*
6021 	 * Make the conn globally visible to walkers
6022 	 */
6023 	ASSERT(connp->conn_ref == 1);
6024 	mutex_enter(&connp->conn_lock);
6025 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6026 	mutex_exit(&connp->conn_lock);
6027 
6028 	qprocson(q);
6029 
6030 	return (0);
6031 }
6032 
6033 /*
6034  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6035  * all of them are copied to the conn_t. If the req is "zero", the policy is
6036  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6037  * fields.
6038  * We keep only the latest setting of the policy and thus policy setting
6039  * is not incremental/cumulative.
6040  *
6041  * Requests to set policies with multiple alternative actions will
6042  * go through a different API.
6043  */
6044 int
6045 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6046 {
6047 	uint_t ah_req = 0;
6048 	uint_t esp_req = 0;
6049 	uint_t se_req = 0;
6050 	ipsec_act_t *actp = NULL;
6051 	uint_t nact;
6052 	ipsec_policy_head_t *ph;
6053 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6054 	int error = 0;
6055 	netstack_t	*ns = connp->conn_netstack;
6056 	ip_stack_t	*ipst = ns->netstack_ip;
6057 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6058 
6059 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6060 
6061 	/*
6062 	 * The IP_SEC_OPT option does not allow variable length parameters,
6063 	 * hence a request cannot be NULL.
6064 	 */
6065 	if (req == NULL)
6066 		return (EINVAL);
6067 
6068 	ah_req = req->ipsr_ah_req;
6069 	esp_req = req->ipsr_esp_req;
6070 	se_req = req->ipsr_self_encap_req;
6071 
6072 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6073 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6074 		return (EINVAL);
6075 
6076 	/*
6077 	 * Are we dealing with a request to reset the policy (i.e.
6078 	 * zero requests).
6079 	 */
6080 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6081 	    (esp_req & REQ_MASK) == 0 &&
6082 	    (se_req & REQ_MASK) == 0);
6083 
6084 	if (!is_pol_reset) {
6085 		/*
6086 		 * If we couldn't load IPsec, fail with "protocol
6087 		 * not supported".
6088 		 * IPsec may not have been loaded for a request with zero
6089 		 * policies, so we don't fail in this case.
6090 		 */
6091 		mutex_enter(&ipss->ipsec_loader_lock);
6092 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6093 			mutex_exit(&ipss->ipsec_loader_lock);
6094 			return (EPROTONOSUPPORT);
6095 		}
6096 		mutex_exit(&ipss->ipsec_loader_lock);
6097 
6098 		/*
6099 		 * Test for valid requests. Invalid algorithms
6100 		 * need to be tested by IPsec code because new
6101 		 * algorithms can be added dynamically.
6102 		 */
6103 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6104 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6105 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6106 			return (EINVAL);
6107 		}
6108 
6109 		/*
6110 		 * Only privileged users can issue these
6111 		 * requests.
6112 		 */
6113 		if (((ah_req & IPSEC_PREF_NEVER) ||
6114 		    (esp_req & IPSEC_PREF_NEVER) ||
6115 		    (se_req & IPSEC_PREF_NEVER)) &&
6116 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6117 			return (EPERM);
6118 		}
6119 
6120 		/*
6121 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6122 		 * are mutually exclusive.
6123 		 */
6124 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6125 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6126 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6127 			/* Both of them are set */
6128 			return (EINVAL);
6129 		}
6130 	}
6131 
6132 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6133 
6134 	/*
6135 	 * If we have already cached policies in conn_connect(), don't
6136 	 * let them change now. We cache policies for connections
6137 	 * whose src,dst [addr, port] is known.
6138 	 */
6139 	if (connp->conn_policy_cached) {
6140 		return (EINVAL);
6141 	}
6142 
6143 	/*
6144 	 * We have a zero policies, reset the connection policy if already
6145 	 * set. This will cause the connection to inherit the
6146 	 * global policy, if any.
6147 	 */
6148 	if (is_pol_reset) {
6149 		if (connp->conn_policy != NULL) {
6150 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6151 			connp->conn_policy = NULL;
6152 		}
6153 		connp->conn_in_enforce_policy = B_FALSE;
6154 		connp->conn_out_enforce_policy = B_FALSE;
6155 		return (0);
6156 	}
6157 
6158 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6159 	    ipst->ips_netstack);
6160 	if (ph == NULL)
6161 		goto enomem;
6162 
6163 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6164 	if (actp == NULL)
6165 		goto enomem;
6166 
6167 	/*
6168 	 * Always insert IPv4 policy entries, since they can also apply to
6169 	 * ipv6 sockets being used in ipv4-compat mode.
6170 	 */
6171 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6172 	    IPSEC_TYPE_INBOUND, ns))
6173 		goto enomem;
6174 	is_pol_inserted = B_TRUE;
6175 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6176 	    IPSEC_TYPE_OUTBOUND, ns))
6177 		goto enomem;
6178 
6179 	/*
6180 	 * We're looking at a v6 socket, also insert the v6-specific
6181 	 * entries.
6182 	 */
6183 	if (connp->conn_family == AF_INET6) {
6184 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6185 		    IPSEC_TYPE_INBOUND, ns))
6186 			goto enomem;
6187 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6188 		    IPSEC_TYPE_OUTBOUND, ns))
6189 			goto enomem;
6190 	}
6191 
6192 	ipsec_actvec_free(actp, nact);
6193 
6194 	/*
6195 	 * If the requests need security, set enforce_policy.
6196 	 * If the requests are IPSEC_PREF_NEVER, one should
6197 	 * still set conn_out_enforce_policy so that ip_set_destination
6198 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6199 	 * for connections that we don't cache policy in at connect time,
6200 	 * if global policy matches in ip_output_attach_policy, we
6201 	 * don't wrongly inherit global policy. Similarly, we need
6202 	 * to set conn_in_enforce_policy also so that we don't verify
6203 	 * policy wrongly.
6204 	 */
6205 	if ((ah_req & REQ_MASK) != 0 ||
6206 	    (esp_req & REQ_MASK) != 0 ||
6207 	    (se_req & REQ_MASK) != 0) {
6208 		connp->conn_in_enforce_policy = B_TRUE;
6209 		connp->conn_out_enforce_policy = B_TRUE;
6210 	}
6211 
6212 	return (error);
6213 #undef REQ_MASK
6214 
6215 	/*
6216 	 * Common memory-allocation-failure exit path.
6217 	 */
6218 enomem:
6219 	if (actp != NULL)
6220 		ipsec_actvec_free(actp, nact);
6221 	if (is_pol_inserted)
6222 		ipsec_polhead_flush(ph, ns);
6223 	return (ENOMEM);
6224 }
6225 
6226 /*
6227  * Set socket options for joining and leaving multicast groups.
6228  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6229  * The caller has already check that the option name is consistent with
6230  * the address family of the socket.
6231  */
6232 int
6233 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6234     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6235 {
6236 	int		*i1 = (int *)invalp;
6237 	int		error = 0;
6238 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6239 	struct ip_mreq	*v4_mreqp;
6240 	struct ipv6_mreq *v6_mreqp;
6241 	struct group_req *greqp;
6242 	ire_t *ire;
6243 	boolean_t done = B_FALSE;
6244 	ipaddr_t ifaddr;
6245 	in6_addr_t v6group;
6246 	uint_t ifindex;
6247 	boolean_t mcast_opt = B_TRUE;
6248 	mcast_record_t fmode;
6249 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6250 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6251 
6252 	switch (name) {
6253 	case IP_ADD_MEMBERSHIP:
6254 	case IPV6_JOIN_GROUP:
6255 		mcast_opt = B_FALSE;
6256 		/* FALLTHRU */
6257 	case MCAST_JOIN_GROUP:
6258 		fmode = MODE_IS_EXCLUDE;
6259 		optfn = ip_opt_add_group;
6260 		break;
6261 
6262 	case IP_DROP_MEMBERSHIP:
6263 	case IPV6_LEAVE_GROUP:
6264 		mcast_opt = B_FALSE;
6265 		/* FALLTHRU */
6266 	case MCAST_LEAVE_GROUP:
6267 		fmode = MODE_IS_INCLUDE;
6268 		optfn = ip_opt_delete_group;
6269 		break;
6270 	default:
6271 		ASSERT(0);
6272 	}
6273 
6274 	if (mcast_opt) {
6275 		struct sockaddr_in *sin;
6276 		struct sockaddr_in6 *sin6;
6277 
6278 		greqp = (struct group_req *)i1;
6279 		if (greqp->gr_group.ss_family == AF_INET) {
6280 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6281 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6282 		} else {
6283 			if (!inet6)
6284 				return (EINVAL);	/* Not on INET socket */
6285 
6286 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6287 			v6group = sin6->sin6_addr;
6288 		}
6289 		ifaddr = INADDR_ANY;
6290 		ifindex = greqp->gr_interface;
6291 	} else if (inet6) {
6292 		v6_mreqp = (struct ipv6_mreq *)i1;
6293 		v6group = v6_mreqp->ipv6mr_multiaddr;
6294 		ifaddr = INADDR_ANY;
6295 		ifindex = v6_mreqp->ipv6mr_interface;
6296 	} else {
6297 		v4_mreqp = (struct ip_mreq *)i1;
6298 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6299 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6300 		ifindex = 0;
6301 	}
6302 
6303 	/*
6304 	 * In the multirouting case, we need to replicate
6305 	 * the request on all interfaces that will take part
6306 	 * in replication.  We do so because multirouting is
6307 	 * reflective, thus we will probably receive multi-
6308 	 * casts on those interfaces.
6309 	 * The ip_multirt_apply_membership() succeeds if
6310 	 * the operation succeeds on at least one interface.
6311 	 */
6312 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6313 		ipaddr_t group;
6314 
6315 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6316 
6317 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6318 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6319 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6320 	} else {
6321 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6322 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6323 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6324 	}
6325 	if (ire != NULL) {
6326 		if (ire->ire_flags & RTF_MULTIRT) {
6327 			error = ip_multirt_apply_membership(optfn, ire, connp,
6328 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6329 			done = B_TRUE;
6330 		}
6331 		ire_refrele(ire);
6332 	}
6333 
6334 	if (!done) {
6335 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6336 		    fmode, &ipv6_all_zeros);
6337 	}
6338 	return (error);
6339 }
6340 
6341 /*
6342  * Set socket options for joining and leaving multicast groups
6343  * for specific sources.
6344  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6345  * The caller has already check that the option name is consistent with
6346  * the address family of the socket.
6347  */
6348 int
6349 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6350     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6351 {
6352 	int		*i1 = (int *)invalp;
6353 	int		error = 0;
6354 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6355 	struct ip_mreq_source *imreqp;
6356 	struct group_source_req *gsreqp;
6357 	in6_addr_t v6group, v6src;
6358 	uint32_t ifindex;
6359 	ipaddr_t ifaddr;
6360 	boolean_t mcast_opt = B_TRUE;
6361 	mcast_record_t fmode;
6362 	ire_t *ire;
6363 	boolean_t done = B_FALSE;
6364 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6365 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6366 
6367 	switch (name) {
6368 	case IP_BLOCK_SOURCE:
6369 		mcast_opt = B_FALSE;
6370 		/* FALLTHRU */
6371 	case MCAST_BLOCK_SOURCE:
6372 		fmode = MODE_IS_EXCLUDE;
6373 		optfn = ip_opt_add_group;
6374 		break;
6375 
6376 	case IP_UNBLOCK_SOURCE:
6377 		mcast_opt = B_FALSE;
6378 		/* FALLTHRU */
6379 	case MCAST_UNBLOCK_SOURCE:
6380 		fmode = MODE_IS_EXCLUDE;
6381 		optfn = ip_opt_delete_group;
6382 		break;
6383 
6384 	case IP_ADD_SOURCE_MEMBERSHIP:
6385 		mcast_opt = B_FALSE;
6386 		/* FALLTHRU */
6387 	case MCAST_JOIN_SOURCE_GROUP:
6388 		fmode = MODE_IS_INCLUDE;
6389 		optfn = ip_opt_add_group;
6390 		break;
6391 
6392 	case IP_DROP_SOURCE_MEMBERSHIP:
6393 		mcast_opt = B_FALSE;
6394 		/* FALLTHRU */
6395 	case MCAST_LEAVE_SOURCE_GROUP:
6396 		fmode = MODE_IS_INCLUDE;
6397 		optfn = ip_opt_delete_group;
6398 		break;
6399 	default:
6400 		ASSERT(0);
6401 	}
6402 
6403 	if (mcast_opt) {
6404 		gsreqp = (struct group_source_req *)i1;
6405 		ifindex = gsreqp->gsr_interface;
6406 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6407 			struct sockaddr_in *s;
6408 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6409 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6410 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6411 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6412 		} else {
6413 			struct sockaddr_in6 *s6;
6414 
6415 			if (!inet6)
6416 				return (EINVAL);	/* Not on INET socket */
6417 
6418 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6419 			v6group = s6->sin6_addr;
6420 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6421 			v6src = s6->sin6_addr;
6422 		}
6423 		ifaddr = INADDR_ANY;
6424 	} else {
6425 		imreqp = (struct ip_mreq_source *)i1;
6426 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6427 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6428 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6429 		ifindex = 0;
6430 	}
6431 
6432 	/*
6433 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6434 	 */
6435 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6436 		v6src = ipv6_all_zeros;
6437 
6438 	/*
6439 	 * In the multirouting case, we need to replicate
6440 	 * the request as noted in the mcast cases above.
6441 	 */
6442 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6443 		ipaddr_t group;
6444 
6445 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6446 
6447 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6448 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6449 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6450 	} else {
6451 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6452 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6453 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6454 	}
6455 	if (ire != NULL) {
6456 		if (ire->ire_flags & RTF_MULTIRT) {
6457 			error = ip_multirt_apply_membership(optfn, ire, connp,
6458 			    checkonly, &v6group, fmode, &v6src);
6459 			done = B_TRUE;
6460 		}
6461 		ire_refrele(ire);
6462 	}
6463 	if (!done) {
6464 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6465 		    fmode, &v6src);
6466 	}
6467 	return (error);
6468 }
6469 
6470 /*
6471  * Given a destination address and a pointer to where to put the information
6472  * this routine fills in the mtuinfo.
6473  * The socket must be connected.
6474  * For sctp conn_faddr is the primary address.
6475  */
6476 int
6477 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6478 {
6479 	uint32_t	pmtu = IP_MAXPACKET;
6480 	uint_t		scopeid;
6481 
6482 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6483 		return (-1);
6484 
6485 	/* In case we never sent or called ip_set_destination_v4/v6 */
6486 	if (ixa->ixa_ire != NULL)
6487 		pmtu = ip_get_pmtu(ixa);
6488 
6489 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6490 		scopeid = ixa->ixa_scopeid;
6491 	else
6492 		scopeid = 0;
6493 
6494 	bzero(mtuinfo, sizeof (*mtuinfo));
6495 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6496 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6497 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6498 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6499 	mtuinfo->ip6m_mtu = pmtu;
6500 
6501 	return (sizeof (struct ip6_mtuinfo));
6502 }
6503 
6504 /*
6505  * When the src multihoming is changed from weak to [strong, preferred]
6506  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6507  * and identify routes that were created by user-applications in the
6508  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6509  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6510  * is selected by finding an interface route for the gateway.
6511  */
6512 /* ARGSUSED */
6513 void
6514 ip_ire_rebind_walker(ire_t *ire, void *notused)
6515 {
6516 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6517 		return;
6518 	ire_rebind(ire);
6519 	ire_delete(ire);
6520 }
6521 
6522 /*
6523  * When the src multihoming is changed from  [strong, preferred] to weak,
6524  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6525  * set any entries that were created by user-applications in the unbound state
6526  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6527  */
6528 /* ARGSUSED */
6529 void
6530 ip_ire_unbind_walker(ire_t *ire, void *notused)
6531 {
6532 	ire_t *new_ire;
6533 
6534 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6535 		return;
6536 	if (ire->ire_ipversion == IPV6_VERSION) {
6537 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6538 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6539 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6540 	} else {
6541 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6542 		    (uchar_t *)&ire->ire_mask,
6543 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6544 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6545 	}
6546 	if (new_ire == NULL)
6547 		return;
6548 	new_ire->ire_unbound = B_TRUE;
6549 	/*
6550 	 * The bound ire must first be deleted so that we don't return
6551 	 * the existing one on the attempt to add the unbound new_ire.
6552 	 */
6553 	ire_delete(ire);
6554 	new_ire = ire_add(new_ire);
6555 	if (new_ire != NULL)
6556 		ire_refrele(new_ire);
6557 }
6558 
6559 /*
6560  * When the settings of ip*_strict_src_multihoming tunables are changed,
6561  * all cached routes need to be recomputed. This recomputation needs to be
6562  * done when going from weaker to stronger modes so that the cached ire
6563  * for the connection does not violate the current ip*_strict_src_multihoming
6564  * setting. It also needs to be done when going from stronger to weaker modes,
6565  * so that we fall back to matching on the longest-matching-route (as opposed
6566  * to a shorter match that may have been selected in the strong mode
6567  * to satisfy src_multihoming settings).
6568  *
6569  * The cached ixa_ire entires for all conn_t entries are marked as
6570  * "verify" so that they will be recomputed for the next packet.
6571  */
6572 void
6573 conn_ire_revalidate(conn_t *connp, void *arg)
6574 {
6575 	boolean_t isv6 = (boolean_t)arg;
6576 
6577 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6578 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6579 		return;
6580 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6581 }
6582 
6583 /*
6584  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6585  * When an ipf is passed here for the first time, if
6586  * we already have in-order fragments on the queue, we convert from the fast-
6587  * path reassembly scheme to the hard-case scheme.  From then on, additional
6588  * fragments are reassembled here.  We keep track of the start and end offsets
6589  * of each piece, and the number of holes in the chain.  When the hole count
6590  * goes to zero, we are done!
6591  *
6592  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6593  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6594  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6595  * after the call to ip_reassemble().
6596  */
6597 int
6598 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6599     size_t msg_len)
6600 {
6601 	uint_t	end;
6602 	mblk_t	*next_mp;
6603 	mblk_t	*mp1;
6604 	uint_t	offset;
6605 	boolean_t incr_dups = B_TRUE;
6606 	boolean_t offset_zero_seen = B_FALSE;
6607 	boolean_t pkt_boundary_checked = B_FALSE;
6608 
6609 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6610 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6611 
6612 	/* Add in byte count */
6613 	ipf->ipf_count += msg_len;
6614 	if (ipf->ipf_end) {
6615 		/*
6616 		 * We were part way through in-order reassembly, but now there
6617 		 * is a hole.  We walk through messages already queued, and
6618 		 * mark them for hard case reassembly.  We know that up till
6619 		 * now they were in order starting from offset zero.
6620 		 */
6621 		offset = 0;
6622 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6623 			IP_REASS_SET_START(mp1, offset);
6624 			if (offset == 0) {
6625 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6626 				offset = -ipf->ipf_nf_hdr_len;
6627 			}
6628 			offset += mp1->b_wptr - mp1->b_rptr;
6629 			IP_REASS_SET_END(mp1, offset);
6630 		}
6631 		/* One hole at the end. */
6632 		ipf->ipf_hole_cnt = 1;
6633 		/* Brand it as a hard case, forever. */
6634 		ipf->ipf_end = 0;
6635 	}
6636 	/* Walk through all the new pieces. */
6637 	do {
6638 		end = start + (mp->b_wptr - mp->b_rptr);
6639 		/*
6640 		 * If start is 0, decrease 'end' only for the first mblk of
6641 		 * the fragment. Otherwise 'end' can get wrong value in the
6642 		 * second pass of the loop if first mblk is exactly the
6643 		 * size of ipf_nf_hdr_len.
6644 		 */
6645 		if (start == 0 && !offset_zero_seen) {
6646 			/* First segment */
6647 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6648 			end -= ipf->ipf_nf_hdr_len;
6649 			offset_zero_seen = B_TRUE;
6650 		}
6651 		next_mp = mp->b_cont;
6652 		/*
6653 		 * We are checking to see if there is any interesing data
6654 		 * to process.  If there isn't and the mblk isn't the
6655 		 * one which carries the unfragmentable header then we
6656 		 * drop it.  It's possible to have just the unfragmentable
6657 		 * header come through without any data.  That needs to be
6658 		 * saved.
6659 		 *
6660 		 * If the assert at the top of this function holds then the
6661 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6662 		 * is infrequently traveled enough that the test is left in
6663 		 * to protect against future code changes which break that
6664 		 * invariant.
6665 		 */
6666 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6667 			/* Empty.  Blast it. */
6668 			IP_REASS_SET_START(mp, 0);
6669 			IP_REASS_SET_END(mp, 0);
6670 			/*
6671 			 * If the ipf points to the mblk we are about to free,
6672 			 * update ipf to point to the next mblk (or NULL
6673 			 * if none).
6674 			 */
6675 			if (ipf->ipf_mp->b_cont == mp)
6676 				ipf->ipf_mp->b_cont = next_mp;
6677 			freeb(mp);
6678 			continue;
6679 		}
6680 		mp->b_cont = NULL;
6681 		IP_REASS_SET_START(mp, start);
6682 		IP_REASS_SET_END(mp, end);
6683 		if (!ipf->ipf_tail_mp) {
6684 			ipf->ipf_tail_mp = mp;
6685 			ipf->ipf_mp->b_cont = mp;
6686 			if (start == 0 || !more) {
6687 				ipf->ipf_hole_cnt = 1;
6688 				/*
6689 				 * if the first fragment comes in more than one
6690 				 * mblk, this loop will be executed for each
6691 				 * mblk. Need to adjust hole count so exiting
6692 				 * this routine will leave hole count at 1.
6693 				 */
6694 				if (next_mp)
6695 					ipf->ipf_hole_cnt++;
6696 			} else
6697 				ipf->ipf_hole_cnt = 2;
6698 			continue;
6699 		} else if (ipf->ipf_last_frag_seen && !more &&
6700 		    !pkt_boundary_checked) {
6701 			/*
6702 			 * We check datagram boundary only if this fragment
6703 			 * claims to be the last fragment and we have seen a
6704 			 * last fragment in the past too. We do this only
6705 			 * once for a given fragment.
6706 			 *
6707 			 * start cannot be 0 here as fragments with start=0
6708 			 * and MF=0 gets handled as a complete packet. These
6709 			 * fragments should not reach here.
6710 			 */
6711 
6712 			if (start + msgdsize(mp) !=
6713 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6714 				/*
6715 				 * We have two fragments both of which claim
6716 				 * to be the last fragment but gives conflicting
6717 				 * information about the whole datagram size.
6718 				 * Something fishy is going on. Drop the
6719 				 * fragment and free up the reassembly list.
6720 				 */
6721 				return (IP_REASS_FAILED);
6722 			}
6723 
6724 			/*
6725 			 * We shouldn't come to this code block again for this
6726 			 * particular fragment.
6727 			 */
6728 			pkt_boundary_checked = B_TRUE;
6729 		}
6730 
6731 		/* New stuff at or beyond tail? */
6732 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6733 		if (start >= offset) {
6734 			if (ipf->ipf_last_frag_seen) {
6735 				/* current fragment is beyond last fragment */
6736 				return (IP_REASS_FAILED);
6737 			}
6738 			/* Link it on end. */
6739 			ipf->ipf_tail_mp->b_cont = mp;
6740 			ipf->ipf_tail_mp = mp;
6741 			if (more) {
6742 				if (start != offset)
6743 					ipf->ipf_hole_cnt++;
6744 			} else if (start == offset && next_mp == NULL)
6745 					ipf->ipf_hole_cnt--;
6746 			continue;
6747 		}
6748 		mp1 = ipf->ipf_mp->b_cont;
6749 		offset = IP_REASS_START(mp1);
6750 		/* New stuff at the front? */
6751 		if (start < offset) {
6752 			if (start == 0) {
6753 				if (end >= offset) {
6754 					/* Nailed the hole at the begining. */
6755 					ipf->ipf_hole_cnt--;
6756 				}
6757 			} else if (end < offset) {
6758 				/*
6759 				 * A hole, stuff, and a hole where there used
6760 				 * to be just a hole.
6761 				 */
6762 				ipf->ipf_hole_cnt++;
6763 			}
6764 			mp->b_cont = mp1;
6765 			/* Check for overlap. */
6766 			while (end > offset) {
6767 				if (end < IP_REASS_END(mp1)) {
6768 					mp->b_wptr -= end - offset;
6769 					IP_REASS_SET_END(mp, offset);
6770 					BUMP_MIB(ill->ill_ip_mib,
6771 					    ipIfStatsReasmPartDups);
6772 					break;
6773 				}
6774 				/* Did we cover another hole? */
6775 				if ((mp1->b_cont &&
6776 				    IP_REASS_END(mp1) !=
6777 				    IP_REASS_START(mp1->b_cont) &&
6778 				    end >= IP_REASS_START(mp1->b_cont)) ||
6779 				    (!ipf->ipf_last_frag_seen && !more)) {
6780 					ipf->ipf_hole_cnt--;
6781 				}
6782 				/* Clip out mp1. */
6783 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6784 					/*
6785 					 * After clipping out mp1, this guy
6786 					 * is now hanging off the end.
6787 					 */
6788 					ipf->ipf_tail_mp = mp;
6789 				}
6790 				IP_REASS_SET_START(mp1, 0);
6791 				IP_REASS_SET_END(mp1, 0);
6792 				/* Subtract byte count */
6793 				ipf->ipf_count -= mp1->b_datap->db_lim -
6794 				    mp1->b_datap->db_base;
6795 				freeb(mp1);
6796 				BUMP_MIB(ill->ill_ip_mib,
6797 				    ipIfStatsReasmPartDups);
6798 				mp1 = mp->b_cont;
6799 				if (!mp1)
6800 					break;
6801 				offset = IP_REASS_START(mp1);
6802 			}
6803 			ipf->ipf_mp->b_cont = mp;
6804 			continue;
6805 		}
6806 		/*
6807 		 * The new piece starts somewhere between the start of the head
6808 		 * and before the end of the tail.
6809 		 */
6810 		for (; mp1; mp1 = mp1->b_cont) {
6811 			offset = IP_REASS_END(mp1);
6812 			if (start < offset) {
6813 				if (end <= offset) {
6814 					/* Nothing new. */
6815 					IP_REASS_SET_START(mp, 0);
6816 					IP_REASS_SET_END(mp, 0);
6817 					/* Subtract byte count */
6818 					ipf->ipf_count -= mp->b_datap->db_lim -
6819 					    mp->b_datap->db_base;
6820 					if (incr_dups) {
6821 						ipf->ipf_num_dups++;
6822 						incr_dups = B_FALSE;
6823 					}
6824 					freeb(mp);
6825 					BUMP_MIB(ill->ill_ip_mib,
6826 					    ipIfStatsReasmDuplicates);
6827 					break;
6828 				}
6829 				/*
6830 				 * Trim redundant stuff off beginning of new
6831 				 * piece.
6832 				 */
6833 				IP_REASS_SET_START(mp, offset);
6834 				mp->b_rptr += offset - start;
6835 				BUMP_MIB(ill->ill_ip_mib,
6836 				    ipIfStatsReasmPartDups);
6837 				start = offset;
6838 				if (!mp1->b_cont) {
6839 					/*
6840 					 * After trimming, this guy is now
6841 					 * hanging off the end.
6842 					 */
6843 					mp1->b_cont = mp;
6844 					ipf->ipf_tail_mp = mp;
6845 					if (!more) {
6846 						ipf->ipf_hole_cnt--;
6847 					}
6848 					break;
6849 				}
6850 			}
6851 			if (start >= IP_REASS_START(mp1->b_cont))
6852 				continue;
6853 			/* Fill a hole */
6854 			if (start > offset)
6855 				ipf->ipf_hole_cnt++;
6856 			mp->b_cont = mp1->b_cont;
6857 			mp1->b_cont = mp;
6858 			mp1 = mp->b_cont;
6859 			offset = IP_REASS_START(mp1);
6860 			if (end >= offset) {
6861 				ipf->ipf_hole_cnt--;
6862 				/* Check for overlap. */
6863 				while (end > offset) {
6864 					if (end < IP_REASS_END(mp1)) {
6865 						mp->b_wptr -= end - offset;
6866 						IP_REASS_SET_END(mp, offset);
6867 						/*
6868 						 * TODO we might bump
6869 						 * this up twice if there is
6870 						 * overlap at both ends.
6871 						 */
6872 						BUMP_MIB(ill->ill_ip_mib,
6873 						    ipIfStatsReasmPartDups);
6874 						break;
6875 					}
6876 					/* Did we cover another hole? */
6877 					if ((mp1->b_cont &&
6878 					    IP_REASS_END(mp1)
6879 					    != IP_REASS_START(mp1->b_cont) &&
6880 					    end >=
6881 					    IP_REASS_START(mp1->b_cont)) ||
6882 					    (!ipf->ipf_last_frag_seen &&
6883 					    !more)) {
6884 						ipf->ipf_hole_cnt--;
6885 					}
6886 					/* Clip out mp1. */
6887 					if ((mp->b_cont = mp1->b_cont) ==
6888 					    NULL) {
6889 						/*
6890 						 * After clipping out mp1,
6891 						 * this guy is now hanging
6892 						 * off the end.
6893 						 */
6894 						ipf->ipf_tail_mp = mp;
6895 					}
6896 					IP_REASS_SET_START(mp1, 0);
6897 					IP_REASS_SET_END(mp1, 0);
6898 					/* Subtract byte count */
6899 					ipf->ipf_count -=
6900 					    mp1->b_datap->db_lim -
6901 					    mp1->b_datap->db_base;
6902 					freeb(mp1);
6903 					BUMP_MIB(ill->ill_ip_mib,
6904 					    ipIfStatsReasmPartDups);
6905 					mp1 = mp->b_cont;
6906 					if (!mp1)
6907 						break;
6908 					offset = IP_REASS_START(mp1);
6909 				}
6910 			}
6911 			break;
6912 		}
6913 	} while (start = end, mp = next_mp);
6914 
6915 	/* Fragment just processed could be the last one. Remember this fact */
6916 	if (!more)
6917 		ipf->ipf_last_frag_seen = B_TRUE;
6918 
6919 	/* Still got holes? */
6920 	if (ipf->ipf_hole_cnt)
6921 		return (IP_REASS_PARTIAL);
6922 	/* Clean up overloaded fields to avoid upstream disasters. */
6923 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6924 		IP_REASS_SET_START(mp1, 0);
6925 		IP_REASS_SET_END(mp1, 0);
6926 	}
6927 	return (IP_REASS_COMPLETE);
6928 }
6929 
6930 /*
6931  * Fragmentation reassembly.  Each ILL has a hash table for
6932  * queuing packets undergoing reassembly for all IPIFs
6933  * associated with the ILL.  The hash is based on the packet
6934  * IP ident field.  The ILL frag hash table was allocated
6935  * as a timer block at the time the ILL was created.  Whenever
6936  * there is anything on the reassembly queue, the timer will
6937  * be running.  Returns the reassembled packet if reassembly completes.
6938  */
6939 mblk_t *
6940 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
6941 {
6942 	uint32_t	frag_offset_flags;
6943 	mblk_t		*t_mp;
6944 	ipaddr_t	dst;
6945 	uint8_t		proto = ipha->ipha_protocol;
6946 	uint32_t	sum_val;
6947 	uint16_t	sum_flags;
6948 	ipf_t		*ipf;
6949 	ipf_t		**ipfp;
6950 	ipfb_t		*ipfb;
6951 	uint16_t	ident;
6952 	uint32_t	offset;
6953 	ipaddr_t	src;
6954 	uint_t		hdr_length;
6955 	uint32_t	end;
6956 	mblk_t		*mp1;
6957 	mblk_t		*tail_mp;
6958 	size_t		count;
6959 	size_t		msg_len;
6960 	uint8_t		ecn_info = 0;
6961 	uint32_t	packet_size;
6962 	boolean_t	pruned = B_FALSE;
6963 	ill_t		*ill = ira->ira_ill;
6964 	ip_stack_t	*ipst = ill->ill_ipst;
6965 
6966 	/*
6967 	 * Drop the fragmented as early as possible, if
6968 	 * we don't have resource(s) to re-assemble.
6969 	 */
6970 	if (ipst->ips_ip_reass_queue_bytes == 0) {
6971 		freemsg(mp);
6972 		return (NULL);
6973 	}
6974 
6975 	/* Check for fragmentation offset; return if there's none */
6976 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
6977 	    (IPH_MF | IPH_OFFSET)) == 0)
6978 		return (mp);
6979 
6980 	/*
6981 	 * We utilize hardware computed checksum info only for UDP since
6982 	 * IP fragmentation is a normal occurrence for the protocol.  In
6983 	 * addition, checksum offload support for IP fragments carrying
6984 	 * UDP payload is commonly implemented across network adapters.
6985 	 */
6986 	ASSERT(ira->ira_rill != NULL);
6987 	if (proto == IPPROTO_UDP && dohwcksum &&
6988 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
6989 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
6990 		mblk_t *mp1 = mp->b_cont;
6991 		int32_t len;
6992 
6993 		/* Record checksum information from the packet */
6994 		sum_val = (uint32_t)DB_CKSUM16(mp);
6995 		sum_flags = DB_CKSUMFLAGS(mp);
6996 
6997 		/* IP payload offset from beginning of mblk */
6998 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
6999 
7000 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7001 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7002 		    offset >= DB_CKSUMSTART(mp) &&
7003 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7004 			uint32_t adj;
7005 			/*
7006 			 * Partial checksum has been calculated by hardware
7007 			 * and attached to the packet; in addition, any
7008 			 * prepended extraneous data is even byte aligned.
7009 			 * If any such data exists, we adjust the checksum;
7010 			 * this would also handle any postpended data.
7011 			 */
7012 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7013 			    mp, mp1, len, adj);
7014 
7015 			/* One's complement subtract extraneous checksum */
7016 			if (adj >= sum_val)
7017 				sum_val = ~(adj - sum_val) & 0xFFFF;
7018 			else
7019 				sum_val -= adj;
7020 		}
7021 	} else {
7022 		sum_val = 0;
7023 		sum_flags = 0;
7024 	}
7025 
7026 	/* Clear hardware checksumming flag */
7027 	DB_CKSUMFLAGS(mp) = 0;
7028 
7029 	ident = ipha->ipha_ident;
7030 	offset = (frag_offset_flags << 3) & 0xFFFF;
7031 	src = ipha->ipha_src;
7032 	dst = ipha->ipha_dst;
7033 	hdr_length = IPH_HDR_LENGTH(ipha);
7034 	end = ntohs(ipha->ipha_length) - hdr_length;
7035 
7036 	/* If end == 0 then we have a packet with no data, so just free it */
7037 	if (end == 0) {
7038 		freemsg(mp);
7039 		return (NULL);
7040 	}
7041 
7042 	/* Record the ECN field info. */
7043 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7044 	if (offset != 0) {
7045 		/*
7046 		 * If this isn't the first piece, strip the header, and
7047 		 * add the offset to the end value.
7048 		 */
7049 		mp->b_rptr += hdr_length;
7050 		end += offset;
7051 	}
7052 
7053 	/* Handle vnic loopback of fragments */
7054 	if (mp->b_datap->db_ref > 2)
7055 		msg_len = 0;
7056 	else
7057 		msg_len = MBLKSIZE(mp);
7058 
7059 	tail_mp = mp;
7060 	while (tail_mp->b_cont != NULL) {
7061 		tail_mp = tail_mp->b_cont;
7062 		if (tail_mp->b_datap->db_ref <= 2)
7063 			msg_len += MBLKSIZE(tail_mp);
7064 	}
7065 
7066 	/* If the reassembly list for this ILL will get too big, prune it */
7067 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7068 	    ipst->ips_ip_reass_queue_bytes) {
7069 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7070 		    uint_t, ill->ill_frag_count,
7071 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7072 		ill_frag_prune(ill,
7073 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7074 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7075 		pruned = B_TRUE;
7076 	}
7077 
7078 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7079 	mutex_enter(&ipfb->ipfb_lock);
7080 
7081 	ipfp = &ipfb->ipfb_ipf;
7082 	/* Try to find an existing fragment queue for this packet. */
7083 	for (;;) {
7084 		ipf = ipfp[0];
7085 		if (ipf != NULL) {
7086 			/*
7087 			 * It has to match on ident and src/dst address.
7088 			 */
7089 			if (ipf->ipf_ident == ident &&
7090 			    ipf->ipf_src == src &&
7091 			    ipf->ipf_dst == dst &&
7092 			    ipf->ipf_protocol == proto) {
7093 				/*
7094 				 * If we have received too many
7095 				 * duplicate fragments for this packet
7096 				 * free it.
7097 				 */
7098 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7099 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7100 					freemsg(mp);
7101 					mutex_exit(&ipfb->ipfb_lock);
7102 					return (NULL);
7103 				}
7104 				/* Found it. */
7105 				break;
7106 			}
7107 			ipfp = &ipf->ipf_hash_next;
7108 			continue;
7109 		}
7110 
7111 		/*
7112 		 * If we pruned the list, do we want to store this new
7113 		 * fragment?. We apply an optimization here based on the
7114 		 * fact that most fragments will be received in order.
7115 		 * So if the offset of this incoming fragment is zero,
7116 		 * it is the first fragment of a new packet. We will
7117 		 * keep it.  Otherwise drop the fragment, as we have
7118 		 * probably pruned the packet already (since the
7119 		 * packet cannot be found).
7120 		 */
7121 		if (pruned && offset != 0) {
7122 			mutex_exit(&ipfb->ipfb_lock);
7123 			freemsg(mp);
7124 			return (NULL);
7125 		}
7126 
7127 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7128 			/*
7129 			 * Too many fragmented packets in this hash
7130 			 * bucket. Free the oldest.
7131 			 */
7132 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7133 		}
7134 
7135 		/* New guy.  Allocate a frag message. */
7136 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7137 		if (mp1 == NULL) {
7138 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7139 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7140 			freemsg(mp);
7141 reass_done:
7142 			mutex_exit(&ipfb->ipfb_lock);
7143 			return (NULL);
7144 		}
7145 
7146 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7147 		mp1->b_cont = mp;
7148 
7149 		/* Initialize the fragment header. */
7150 		ipf = (ipf_t *)mp1->b_rptr;
7151 		ipf->ipf_mp = mp1;
7152 		ipf->ipf_ptphn = ipfp;
7153 		ipfp[0] = ipf;
7154 		ipf->ipf_hash_next = NULL;
7155 		ipf->ipf_ident = ident;
7156 		ipf->ipf_protocol = proto;
7157 		ipf->ipf_src = src;
7158 		ipf->ipf_dst = dst;
7159 		ipf->ipf_nf_hdr_len = 0;
7160 		/* Record reassembly start time. */
7161 		ipf->ipf_timestamp = gethrestime_sec();
7162 		/* Record ipf generation and account for frag header */
7163 		ipf->ipf_gen = ill->ill_ipf_gen++;
7164 		ipf->ipf_count = MBLKSIZE(mp1);
7165 		ipf->ipf_last_frag_seen = B_FALSE;
7166 		ipf->ipf_ecn = ecn_info;
7167 		ipf->ipf_num_dups = 0;
7168 		ipfb->ipfb_frag_pkts++;
7169 		ipf->ipf_checksum = 0;
7170 		ipf->ipf_checksum_flags = 0;
7171 
7172 		/* Store checksum value in fragment header */
7173 		if (sum_flags != 0) {
7174 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7175 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7176 			ipf->ipf_checksum = sum_val;
7177 			ipf->ipf_checksum_flags = sum_flags;
7178 		}
7179 
7180 		/*
7181 		 * We handle reassembly two ways.  In the easy case,
7182 		 * where all the fragments show up in order, we do
7183 		 * minimal bookkeeping, and just clip new pieces on
7184 		 * the end.  If we ever see a hole, then we go off
7185 		 * to ip_reassemble which has to mark the pieces and
7186 		 * keep track of the number of holes, etc.  Obviously,
7187 		 * the point of having both mechanisms is so we can
7188 		 * handle the easy case as efficiently as possible.
7189 		 */
7190 		if (offset == 0) {
7191 			/* Easy case, in-order reassembly so far. */
7192 			ipf->ipf_count += msg_len;
7193 			ipf->ipf_tail_mp = tail_mp;
7194 			/*
7195 			 * Keep track of next expected offset in
7196 			 * ipf_end.
7197 			 */
7198 			ipf->ipf_end = end;
7199 			ipf->ipf_nf_hdr_len = hdr_length;
7200 		} else {
7201 			/* Hard case, hole at the beginning. */
7202 			ipf->ipf_tail_mp = NULL;
7203 			/*
7204 			 * ipf_end == 0 means that we have given up
7205 			 * on easy reassembly.
7206 			 */
7207 			ipf->ipf_end = 0;
7208 
7209 			/* Forget checksum offload from now on */
7210 			ipf->ipf_checksum_flags = 0;
7211 
7212 			/*
7213 			 * ipf_hole_cnt is set by ip_reassemble.
7214 			 * ipf_count is updated by ip_reassemble.
7215 			 * No need to check for return value here
7216 			 * as we don't expect reassembly to complete
7217 			 * or fail for the first fragment itself.
7218 			 */
7219 			(void) ip_reassemble(mp, ipf,
7220 			    (frag_offset_flags & IPH_OFFSET) << 3,
7221 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7222 		}
7223 		/* Update per ipfb and ill byte counts */
7224 		ipfb->ipfb_count += ipf->ipf_count;
7225 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7226 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7227 		/* If the frag timer wasn't already going, start it. */
7228 		mutex_enter(&ill->ill_lock);
7229 		ill_frag_timer_start(ill);
7230 		mutex_exit(&ill->ill_lock);
7231 		goto reass_done;
7232 	}
7233 
7234 	/*
7235 	 * If the packet's flag has changed (it could be coming up
7236 	 * from an interface different than the previous, therefore
7237 	 * possibly different checksum capability), then forget about
7238 	 * any stored checksum states.  Otherwise add the value to
7239 	 * the existing one stored in the fragment header.
7240 	 */
7241 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7242 		sum_val += ipf->ipf_checksum;
7243 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7244 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7245 		ipf->ipf_checksum = sum_val;
7246 	} else if (ipf->ipf_checksum_flags != 0) {
7247 		/* Forget checksum offload from now on */
7248 		ipf->ipf_checksum_flags = 0;
7249 	}
7250 
7251 	/*
7252 	 * We have a new piece of a datagram which is already being
7253 	 * reassembled.  Update the ECN info if all IP fragments
7254 	 * are ECN capable.  If there is one which is not, clear
7255 	 * all the info.  If there is at least one which has CE
7256 	 * code point, IP needs to report that up to transport.
7257 	 */
7258 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7259 		if (ecn_info == IPH_ECN_CE)
7260 			ipf->ipf_ecn = IPH_ECN_CE;
7261 	} else {
7262 		ipf->ipf_ecn = IPH_ECN_NECT;
7263 	}
7264 	if (offset && ipf->ipf_end == offset) {
7265 		/* The new fragment fits at the end */
7266 		ipf->ipf_tail_mp->b_cont = mp;
7267 		/* Update the byte count */
7268 		ipf->ipf_count += msg_len;
7269 		/* Update per ipfb and ill byte counts */
7270 		ipfb->ipfb_count += msg_len;
7271 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7272 		atomic_add_32(&ill->ill_frag_count, msg_len);
7273 		if (frag_offset_flags & IPH_MF) {
7274 			/* More to come. */
7275 			ipf->ipf_end = end;
7276 			ipf->ipf_tail_mp = tail_mp;
7277 			goto reass_done;
7278 		}
7279 	} else {
7280 		/* Go do the hard cases. */
7281 		int ret;
7282 
7283 		if (offset == 0)
7284 			ipf->ipf_nf_hdr_len = hdr_length;
7285 
7286 		/* Save current byte count */
7287 		count = ipf->ipf_count;
7288 		ret = ip_reassemble(mp, ipf,
7289 		    (frag_offset_flags & IPH_OFFSET) << 3,
7290 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7291 		/* Count of bytes added and subtracted (freeb()ed) */
7292 		count = ipf->ipf_count - count;
7293 		if (count) {
7294 			/* Update per ipfb and ill byte counts */
7295 			ipfb->ipfb_count += count;
7296 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7297 			atomic_add_32(&ill->ill_frag_count, count);
7298 		}
7299 		if (ret == IP_REASS_PARTIAL) {
7300 			goto reass_done;
7301 		} else if (ret == IP_REASS_FAILED) {
7302 			/* Reassembly failed. Free up all resources */
7303 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7304 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7305 				IP_REASS_SET_START(t_mp, 0);
7306 				IP_REASS_SET_END(t_mp, 0);
7307 			}
7308 			freemsg(mp);
7309 			goto reass_done;
7310 		}
7311 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7312 	}
7313 	/*
7314 	 * We have completed reassembly.  Unhook the frag header from
7315 	 * the reassembly list.
7316 	 *
7317 	 * Before we free the frag header, record the ECN info
7318 	 * to report back to the transport.
7319 	 */
7320 	ecn_info = ipf->ipf_ecn;
7321 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7322 	ipfp = ipf->ipf_ptphn;
7323 
7324 	/* We need to supply these to caller */
7325 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7326 		sum_val = ipf->ipf_checksum;
7327 	else
7328 		sum_val = 0;
7329 
7330 	mp1 = ipf->ipf_mp;
7331 	count = ipf->ipf_count;
7332 	ipf = ipf->ipf_hash_next;
7333 	if (ipf != NULL)
7334 		ipf->ipf_ptphn = ipfp;
7335 	ipfp[0] = ipf;
7336 	atomic_add_32(&ill->ill_frag_count, -count);
7337 	ASSERT(ipfb->ipfb_count >= count);
7338 	ipfb->ipfb_count -= count;
7339 	ipfb->ipfb_frag_pkts--;
7340 	mutex_exit(&ipfb->ipfb_lock);
7341 	/* Ditch the frag header. */
7342 	mp = mp1->b_cont;
7343 
7344 	freeb(mp1);
7345 
7346 	/* Restore original IP length in header. */
7347 	packet_size = (uint32_t)msgdsize(mp);
7348 	if (packet_size > IP_MAXPACKET) {
7349 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7350 		ip_drop_input("Reassembled packet too large", mp, ill);
7351 		freemsg(mp);
7352 		return (NULL);
7353 	}
7354 
7355 	if (DB_REF(mp) > 1) {
7356 		mblk_t *mp2 = copymsg(mp);
7357 
7358 		if (mp2 == NULL) {
7359 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7360 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7361 			freemsg(mp);
7362 			return (NULL);
7363 		}
7364 		freemsg(mp);
7365 		mp = mp2;
7366 	}
7367 	ipha = (ipha_t *)mp->b_rptr;
7368 
7369 	ipha->ipha_length = htons((uint16_t)packet_size);
7370 	/* We're now complete, zip the frag state */
7371 	ipha->ipha_fragment_offset_and_flags = 0;
7372 	/* Record the ECN info. */
7373 	ipha->ipha_type_of_service &= 0xFC;
7374 	ipha->ipha_type_of_service |= ecn_info;
7375 
7376 	/* Update the receive attributes */
7377 	ira->ira_pktlen = packet_size;
7378 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7379 
7380 	/* Reassembly is successful; set checksum information in packet */
7381 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7382 	DB_CKSUMFLAGS(mp) = sum_flags;
7383 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7384 
7385 	return (mp);
7386 }
7387 
7388 /*
7389  * Pullup function that should be used for IP input in order to
7390  * ensure we do not loose the L2 source address; we need the l2 source
7391  * address for IP_RECVSLLA and for ndp_input.
7392  *
7393  * We return either NULL or b_rptr.
7394  */
7395 void *
7396 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7397 {
7398 	ill_t		*ill = ira->ira_ill;
7399 
7400 	if (ip_rput_pullups++ == 0) {
7401 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7402 		    "ip_pullup: %s forced us to "
7403 		    " pullup pkt, hdr len %ld, hdr addr %p",
7404 		    ill->ill_name, len, (void *)mp->b_rptr);
7405 	}
7406 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7407 		ip_setl2src(mp, ira, ira->ira_rill);
7408 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7409 	if (!pullupmsg(mp, len))
7410 		return (NULL);
7411 	else
7412 		return (mp->b_rptr);
7413 }
7414 
7415 /*
7416  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7417  * When called from the ULP ira_rill will be NULL hence the caller has to
7418  * pass in the ill.
7419  */
7420 /* ARGSUSED */
7421 void
7422 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7423 {
7424 	const uchar_t *addr;
7425 	int alen;
7426 
7427 	if (ira->ira_flags & IRAF_L2SRC_SET)
7428 		return;
7429 
7430 	ASSERT(ill != NULL);
7431 	alen = ill->ill_phys_addr_length;
7432 	ASSERT(alen <= sizeof (ira->ira_l2src));
7433 	if (ira->ira_mhip != NULL &&
7434 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7435 		bcopy(addr, ira->ira_l2src, alen);
7436 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7437 	    (addr = ill->ill_phys_addr) != NULL) {
7438 		bcopy(addr, ira->ira_l2src, alen);
7439 	} else {
7440 		bzero(ira->ira_l2src, alen);
7441 	}
7442 	ira->ira_flags |= IRAF_L2SRC_SET;
7443 }
7444 
7445 /*
7446  * check ip header length and align it.
7447  */
7448 mblk_t *
7449 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7450 {
7451 	ill_t	*ill = ira->ira_ill;
7452 	ssize_t len;
7453 
7454 	len = MBLKL(mp);
7455 
7456 	if (!OK_32PTR(mp->b_rptr))
7457 		IP_STAT(ill->ill_ipst, ip_notaligned);
7458 	else
7459 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7460 
7461 	/* Guard against bogus device drivers */
7462 	if (len < 0) {
7463 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7464 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7465 		freemsg(mp);
7466 		return (NULL);
7467 	}
7468 
7469 	if (len == 0) {
7470 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7471 		mblk_t *mp1 = mp->b_cont;
7472 
7473 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7474 			ip_setl2src(mp, ira, ira->ira_rill);
7475 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7476 
7477 		freeb(mp);
7478 		mp = mp1;
7479 		if (mp == NULL)
7480 			return (NULL);
7481 
7482 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7483 			return (mp);
7484 	}
7485 	if (ip_pullup(mp, min_size, ira) == NULL) {
7486 		if (msgdsize(mp) < min_size) {
7487 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7488 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7489 		} else {
7490 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7491 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7492 		}
7493 		freemsg(mp);
7494 		return (NULL);
7495 	}
7496 	return (mp);
7497 }
7498 
7499 /*
7500  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7501  */
7502 mblk_t *
7503 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7504     uint_t min_size, ip_recv_attr_t *ira)
7505 {
7506 	ill_t	*ill = ira->ira_ill;
7507 
7508 	/*
7509 	 * Make sure we have data length consistent
7510 	 * with the IP header.
7511 	 */
7512 	if (mp->b_cont == NULL) {
7513 		/* pkt_len is based on ipha_len, not the mblk length */
7514 		if (pkt_len < min_size) {
7515 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7516 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7517 			freemsg(mp);
7518 			return (NULL);
7519 		}
7520 		if (len < 0) {
7521 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7522 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7523 			freemsg(mp);
7524 			return (NULL);
7525 		}
7526 		/* Drop any pad */
7527 		mp->b_wptr = rptr + pkt_len;
7528 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7529 		ASSERT(pkt_len >= min_size);
7530 		if (pkt_len < min_size) {
7531 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7532 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7533 			freemsg(mp);
7534 			return (NULL);
7535 		}
7536 		if (len < 0) {
7537 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7538 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7539 			freemsg(mp);
7540 			return (NULL);
7541 		}
7542 		/* Drop any pad */
7543 		(void) adjmsg(mp, -len);
7544 		/*
7545 		 * adjmsg may have freed an mblk from the chain, hence
7546 		 * invalidate any hw checksum here. This will force IP to
7547 		 * calculate the checksum in sw, but only for this packet.
7548 		 */
7549 		DB_CKSUMFLAGS(mp) = 0;
7550 		IP_STAT(ill->ill_ipst, ip_multimblk);
7551 	}
7552 	return (mp);
7553 }
7554 
7555 /*
7556  * Check that the IPv4 opt_len is consistent with the packet and pullup
7557  * the options.
7558  */
7559 mblk_t *
7560 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7561     ip_recv_attr_t *ira)
7562 {
7563 	ill_t	*ill = ira->ira_ill;
7564 	ssize_t len;
7565 
7566 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7567 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7568 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7569 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7570 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7571 		freemsg(mp);
7572 		return (NULL);
7573 	}
7574 
7575 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7576 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7577 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7578 		freemsg(mp);
7579 		return (NULL);
7580 	}
7581 	/*
7582 	 * Recompute complete header length and make sure we
7583 	 * have access to all of it.
7584 	 */
7585 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7586 	if (len > (mp->b_wptr - mp->b_rptr)) {
7587 		if (len > pkt_len) {
7588 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7589 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7590 			freemsg(mp);
7591 			return (NULL);
7592 		}
7593 		if (ip_pullup(mp, len, ira) == NULL) {
7594 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7595 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7596 			freemsg(mp);
7597 			return (NULL);
7598 		}
7599 	}
7600 	return (mp);
7601 }
7602 
7603 /*
7604  * Returns a new ire, or the same ire, or NULL.
7605  * If a different IRE is returned, then it is held; the caller
7606  * needs to release it.
7607  * In no case is there any hold/release on the ire argument.
7608  */
7609 ire_t *
7610 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7611 {
7612 	ire_t		*new_ire;
7613 	ill_t		*ire_ill;
7614 	uint_t		ifindex;
7615 	ip_stack_t	*ipst = ill->ill_ipst;
7616 	boolean_t	strict_check = B_FALSE;
7617 
7618 	/*
7619 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7620 	 * issue (e.g. packet received on an underlying interface matched an
7621 	 * IRE_LOCAL on its associated group interface).
7622 	 */
7623 	ASSERT(ire->ire_ill != NULL);
7624 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7625 		return (ire);
7626 
7627 	/*
7628 	 * Do another ire lookup here, using the ingress ill, to see if the
7629 	 * interface is in a usesrc group.
7630 	 * As long as the ills belong to the same group, we don't consider
7631 	 * them to be arriving on the wrong interface. Thus, if the switch
7632 	 * is doing inbound load spreading, we won't drop packets when the
7633 	 * ip*_strict_dst_multihoming switch is on.
7634 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7635 	 * where the local address may not be unique. In this case we were
7636 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7637 	 * actually returned. The new lookup, which is more specific, should
7638 	 * only find the IRE_LOCAL associated with the ingress ill if one
7639 	 * exists.
7640 	 */
7641 	if (ire->ire_ipversion == IPV4_VERSION) {
7642 		if (ipst->ips_ip_strict_dst_multihoming)
7643 			strict_check = B_TRUE;
7644 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7645 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7646 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7647 	} else {
7648 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7649 		if (ipst->ips_ipv6_strict_dst_multihoming)
7650 			strict_check = B_TRUE;
7651 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7652 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7653 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7654 	}
7655 	/*
7656 	 * If the same ire that was returned in ip_input() is found then this
7657 	 * is an indication that usesrc groups are in use. The packet
7658 	 * arrived on a different ill in the group than the one associated with
7659 	 * the destination address.  If a different ire was found then the same
7660 	 * IP address must be hosted on multiple ills. This is possible with
7661 	 * unnumbered point2point interfaces. We switch to use this new ire in
7662 	 * order to have accurate interface statistics.
7663 	 */
7664 	if (new_ire != NULL) {
7665 		/* Note: held in one case but not the other? Caller handles */
7666 		if (new_ire != ire)
7667 			return (new_ire);
7668 		/* Unchanged */
7669 		ire_refrele(new_ire);
7670 		return (ire);
7671 	}
7672 
7673 	/*
7674 	 * Chase pointers once and store locally.
7675 	 */
7676 	ASSERT(ire->ire_ill != NULL);
7677 	ire_ill = ire->ire_ill;
7678 	ifindex = ill->ill_usesrc_ifindex;
7679 
7680 	/*
7681 	 * Check if it's a legal address on the 'usesrc' interface.
7682 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7683 	 * can just check phyint_ifindex.
7684 	 */
7685 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7686 		return (ire);
7687 	}
7688 
7689 	/*
7690 	 * If the ip*_strict_dst_multihoming switch is on then we can
7691 	 * only accept this packet if the interface is marked as routing.
7692 	 */
7693 	if (!(strict_check))
7694 		return (ire);
7695 
7696 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7697 		return (ire);
7698 	}
7699 	return (NULL);
7700 }
7701 
7702 /*
7703  * This function is used to construct a mac_header_info_s from a
7704  * DL_UNITDATA_IND message.
7705  * The address fields in the mhi structure points into the message,
7706  * thus the caller can't use those fields after freeing the message.
7707  *
7708  * We determine whether the packet received is a non-unicast packet
7709  * and in doing so, determine whether or not it is broadcast vs multicast.
7710  * For it to be a broadcast packet, we must have the appropriate mblk_t
7711  * hanging off the ill_t.  If this is either not present or doesn't match
7712  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7713  * to be multicast.  Thus NICs that have no broadcast address (or no
7714  * capability for one, such as point to point links) cannot return as
7715  * the packet being broadcast.
7716  */
7717 void
7718 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7719 {
7720 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7721 	mblk_t *bmp;
7722 	uint_t extra_offset;
7723 
7724 	bzero(mhip, sizeof (struct mac_header_info_s));
7725 
7726 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7727 
7728 	if (ill->ill_sap_length < 0)
7729 		extra_offset = 0;
7730 	else
7731 		extra_offset = ill->ill_sap_length;
7732 
7733 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7734 	    extra_offset;
7735 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7736 	    extra_offset;
7737 
7738 	if (!ind->dl_group_address)
7739 		return;
7740 
7741 	/* Multicast or broadcast */
7742 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7743 
7744 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7745 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7746 	    (bmp = ill->ill_bcast_mp) != NULL) {
7747 		dl_unitdata_req_t *dlur;
7748 		uint8_t *bphys_addr;
7749 
7750 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7751 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7752 		    extra_offset;
7753 
7754 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7755 		    ind->dl_dest_addr_length) == 0)
7756 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7757 	}
7758 }
7759 
7760 /*
7761  * This function is used to construct a mac_header_info_s from a
7762  * M_DATA fastpath message from a DLPI driver.
7763  * The address fields in the mhi structure points into the message,
7764  * thus the caller can't use those fields after freeing the message.
7765  *
7766  * We determine whether the packet received is a non-unicast packet
7767  * and in doing so, determine whether or not it is broadcast vs multicast.
7768  * For it to be a broadcast packet, we must have the appropriate mblk_t
7769  * hanging off the ill_t.  If this is either not present or doesn't match
7770  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7771  * to be multicast.  Thus NICs that have no broadcast address (or no
7772  * capability for one, such as point to point links) cannot return as
7773  * the packet being broadcast.
7774  */
7775 void
7776 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7777 {
7778 	mblk_t *bmp;
7779 	struct ether_header *pether;
7780 
7781 	bzero(mhip, sizeof (struct mac_header_info_s));
7782 
7783 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7784 
7785 	pether = (struct ether_header *)((char *)mp->b_rptr
7786 	    - sizeof (struct ether_header));
7787 
7788 	/*
7789 	 * Make sure the interface is an ethernet type, since we don't
7790 	 * know the header format for anything but Ethernet. Also make
7791 	 * sure we are pointing correctly above db_base.
7792 	 */
7793 	if (ill->ill_type != IFT_ETHER)
7794 		return;
7795 
7796 retry:
7797 	if ((uchar_t *)pether < mp->b_datap->db_base)
7798 		return;
7799 
7800 	/* Is there a VLAN tag? */
7801 	if (ill->ill_isv6) {
7802 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7803 			pether = (struct ether_header *)((char *)pether - 4);
7804 			goto retry;
7805 		}
7806 	} else {
7807 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7808 			pether = (struct ether_header *)((char *)pether - 4);
7809 			goto retry;
7810 		}
7811 	}
7812 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7813 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7814 
7815 	if (!(mhip->mhi_daddr[0] & 0x01))
7816 		return;
7817 
7818 	/* Multicast or broadcast */
7819 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7820 
7821 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7822 		dl_unitdata_req_t *dlur;
7823 		uint8_t *bphys_addr;
7824 		uint_t	addrlen;
7825 
7826 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7827 		addrlen = dlur->dl_dest_addr_length;
7828 		if (ill->ill_sap_length < 0) {
7829 			bphys_addr = (uchar_t *)dlur +
7830 			    dlur->dl_dest_addr_offset;
7831 			addrlen += ill->ill_sap_length;
7832 		} else {
7833 			bphys_addr = (uchar_t *)dlur +
7834 			    dlur->dl_dest_addr_offset +
7835 			    ill->ill_sap_length;
7836 			addrlen -= ill->ill_sap_length;
7837 		}
7838 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7839 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7840 	}
7841 }
7842 
7843 /*
7844  * Handle anything but M_DATA messages
7845  * We see the DL_UNITDATA_IND which are part
7846  * of the data path, and also the other messages from the driver.
7847  */
7848 void
7849 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7850 {
7851 	mblk_t		*first_mp;
7852 	struct iocblk   *iocp;
7853 	struct mac_header_info_s mhi;
7854 
7855 	switch (DB_TYPE(mp)) {
7856 	case M_PROTO:
7857 	case M_PCPROTO: {
7858 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7859 		    DL_UNITDATA_IND) {
7860 			/* Go handle anything other than data elsewhere. */
7861 			ip_rput_dlpi(ill, mp);
7862 			return;
7863 		}
7864 
7865 		first_mp = mp;
7866 		mp = first_mp->b_cont;
7867 		first_mp->b_cont = NULL;
7868 
7869 		if (mp == NULL) {
7870 			freeb(first_mp);
7871 			return;
7872 		}
7873 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7874 		if (ill->ill_isv6)
7875 			ip_input_v6(ill, NULL, mp, &mhi);
7876 		else
7877 			ip_input(ill, NULL, mp, &mhi);
7878 
7879 		/* Ditch the DLPI header. */
7880 		freeb(first_mp);
7881 		return;
7882 	}
7883 	case M_IOCACK:
7884 		iocp = (struct iocblk *)mp->b_rptr;
7885 		switch (iocp->ioc_cmd) {
7886 		case DL_IOC_HDR_INFO:
7887 			ill_fastpath_ack(ill, mp);
7888 			return;
7889 		default:
7890 			putnext(ill->ill_rq, mp);
7891 			return;
7892 		}
7893 		/* FALLTHRU */
7894 	case M_ERROR:
7895 	case M_HANGUP:
7896 		mutex_enter(&ill->ill_lock);
7897 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7898 			mutex_exit(&ill->ill_lock);
7899 			freemsg(mp);
7900 			return;
7901 		}
7902 		ill_refhold_locked(ill);
7903 		mutex_exit(&ill->ill_lock);
7904 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7905 		    B_FALSE);
7906 		return;
7907 	case M_CTL:
7908 		putnext(ill->ill_rq, mp);
7909 		return;
7910 	case M_IOCNAK:
7911 		ip1dbg(("got iocnak "));
7912 		iocp = (struct iocblk *)mp->b_rptr;
7913 		switch (iocp->ioc_cmd) {
7914 		case DL_IOC_HDR_INFO:
7915 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7916 			return;
7917 		default:
7918 			break;
7919 		}
7920 		/* FALLTHRU */
7921 	default:
7922 		putnext(ill->ill_rq, mp);
7923 		return;
7924 	}
7925 }
7926 
7927 /* Read side put procedure.  Packets coming from the wire arrive here. */
7928 void
7929 ip_rput(queue_t *q, mblk_t *mp)
7930 {
7931 	ill_t	*ill;
7932 	union DL_primitives *dl;
7933 
7934 	ill = (ill_t *)q->q_ptr;
7935 
7936 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
7937 		/*
7938 		 * If things are opening or closing, only accept high-priority
7939 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
7940 		 * created; on close, things hanging off the ill may have been
7941 		 * freed already.)
7942 		 */
7943 		dl = (union DL_primitives *)mp->b_rptr;
7944 		if (DB_TYPE(mp) != M_PCPROTO ||
7945 		    dl->dl_primitive == DL_UNITDATA_IND) {
7946 			inet_freemsg(mp);
7947 			return;
7948 		}
7949 	}
7950 	if (DB_TYPE(mp) == M_DATA) {
7951 		struct mac_header_info_s mhi;
7952 
7953 		ip_mdata_to_mhi(ill, mp, &mhi);
7954 		ip_input(ill, NULL, mp, &mhi);
7955 	} else {
7956 		ip_rput_notdata(ill, mp);
7957 	}
7958 }
7959 
7960 /*
7961  * Move the information to a copy.
7962  */
7963 mblk_t *
7964 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
7965 {
7966 	mblk_t		*mp1;
7967 	ill_t		*ill = ira->ira_ill;
7968 	ip_stack_t	*ipst = ill->ill_ipst;
7969 
7970 	IP_STAT(ipst, ip_db_ref);
7971 
7972 	/* Make sure we have ira_l2src before we loose the original mblk */
7973 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7974 		ip_setl2src(mp, ira, ira->ira_rill);
7975 
7976 	mp1 = copymsg(mp);
7977 	if (mp1 == NULL) {
7978 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7979 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
7980 		freemsg(mp);
7981 		return (NULL);
7982 	}
7983 	/* preserve the hardware checksum flags and data, if present */
7984 	if (DB_CKSUMFLAGS(mp) != 0) {
7985 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
7986 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
7987 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
7988 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
7989 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
7990 	}
7991 	freemsg(mp);
7992 	return (mp1);
7993 }
7994 
7995 static void
7996 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
7997     t_uscalar_t err)
7998 {
7999 	if (dl_err == DL_SYSERR) {
8000 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8001 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8002 		    ill->ill_name, dl_primstr(prim), err);
8003 		return;
8004 	}
8005 
8006 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8007 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8008 	    dl_errstr(dl_err));
8009 }
8010 
8011 /*
8012  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8013  * than DL_UNITDATA_IND messages. If we need to process this message
8014  * exclusively, we call qwriter_ip, in which case we also need to call
8015  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8016  */
8017 void
8018 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8019 {
8020 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8021 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8022 	queue_t		*q = ill->ill_rq;
8023 	t_uscalar_t	prim = dloa->dl_primitive;
8024 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8025 
8026 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8027 	    char *, dl_primstr(prim), ill_t *, ill);
8028 	ip1dbg(("ip_rput_dlpi"));
8029 
8030 	/*
8031 	 * If we received an ACK but didn't send a request for it, then it
8032 	 * can't be part of any pending operation; discard up-front.
8033 	 */
8034 	switch (prim) {
8035 	case DL_ERROR_ACK:
8036 		reqprim = dlea->dl_error_primitive;
8037 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8038 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8039 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8040 		    dlea->dl_unix_errno));
8041 		break;
8042 	case DL_OK_ACK:
8043 		reqprim = dloa->dl_correct_primitive;
8044 		break;
8045 	case DL_INFO_ACK:
8046 		reqprim = DL_INFO_REQ;
8047 		break;
8048 	case DL_BIND_ACK:
8049 		reqprim = DL_BIND_REQ;
8050 		break;
8051 	case DL_PHYS_ADDR_ACK:
8052 		reqprim = DL_PHYS_ADDR_REQ;
8053 		break;
8054 	case DL_NOTIFY_ACK:
8055 		reqprim = DL_NOTIFY_REQ;
8056 		break;
8057 	case DL_CAPABILITY_ACK:
8058 		reqprim = DL_CAPABILITY_REQ;
8059 		break;
8060 	}
8061 
8062 	if (prim != DL_NOTIFY_IND) {
8063 		if (reqprim == DL_PRIM_INVAL ||
8064 		    !ill_dlpi_pending(ill, reqprim)) {
8065 			/* Not a DLPI message we support or expected */
8066 			freemsg(mp);
8067 			return;
8068 		}
8069 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8070 		    dl_primstr(reqprim)));
8071 	}
8072 
8073 	switch (reqprim) {
8074 	case DL_UNBIND_REQ:
8075 		/*
8076 		 * NOTE: we mark the unbind as complete even if we got a
8077 		 * DL_ERROR_ACK, since there's not much else we can do.
8078 		 */
8079 		mutex_enter(&ill->ill_lock);
8080 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8081 		cv_signal(&ill->ill_cv);
8082 		mutex_exit(&ill->ill_lock);
8083 		break;
8084 
8085 	case DL_ENABMULTI_REQ:
8086 		if (prim == DL_OK_ACK) {
8087 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8088 				ill->ill_dlpi_multicast_state = IDS_OK;
8089 		}
8090 		break;
8091 	}
8092 
8093 	/*
8094 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8095 	 * need to become writer to continue to process it.  Because an
8096 	 * exclusive operation doesn't complete until replies to all queued
8097 	 * DLPI messages have been received, we know we're in the middle of an
8098 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8099 	 *
8100 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8101 	 * Since this is on the ill stream we unconditionally bump up the
8102 	 * refcount without doing ILL_CAN_LOOKUP().
8103 	 */
8104 	ill_refhold(ill);
8105 	if (prim == DL_NOTIFY_IND)
8106 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8107 	else
8108 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8109 }
8110 
8111 /*
8112  * Handling of DLPI messages that require exclusive access to the ipsq.
8113  *
8114  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8115  * happen here. (along with mi_copy_done)
8116  */
8117 /* ARGSUSED */
8118 static void
8119 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8120 {
8121 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8122 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8123 	int		err = 0;
8124 	ill_t		*ill = (ill_t *)q->q_ptr;
8125 	ipif_t		*ipif = NULL;
8126 	mblk_t		*mp1 = NULL;
8127 	conn_t		*connp = NULL;
8128 	t_uscalar_t	paddrreq;
8129 	mblk_t		*mp_hw;
8130 	boolean_t	success;
8131 	boolean_t	ioctl_aborted = B_FALSE;
8132 	boolean_t	log = B_TRUE;
8133 
8134 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8135 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8136 
8137 	ip1dbg(("ip_rput_dlpi_writer .."));
8138 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8139 	ASSERT(IAM_WRITER_ILL(ill));
8140 
8141 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8142 	/*
8143 	 * The current ioctl could have been aborted by the user and a new
8144 	 * ioctl to bring up another ill could have started. We could still
8145 	 * get a response from the driver later.
8146 	 */
8147 	if (ipif != NULL && ipif->ipif_ill != ill)
8148 		ioctl_aborted = B_TRUE;
8149 
8150 	switch (dloa->dl_primitive) {
8151 	case DL_ERROR_ACK:
8152 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8153 		    dl_primstr(dlea->dl_error_primitive)));
8154 
8155 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8156 		    char *, dl_primstr(dlea->dl_error_primitive),
8157 		    ill_t *, ill);
8158 
8159 		switch (dlea->dl_error_primitive) {
8160 		case DL_DISABMULTI_REQ:
8161 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8162 			break;
8163 		case DL_PROMISCON_REQ:
8164 		case DL_PROMISCOFF_REQ:
8165 		case DL_UNBIND_REQ:
8166 		case DL_ATTACH_REQ:
8167 		case DL_INFO_REQ:
8168 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8169 			break;
8170 		case DL_NOTIFY_REQ:
8171 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8172 			log = B_FALSE;
8173 			break;
8174 		case DL_PHYS_ADDR_REQ:
8175 			/*
8176 			 * For IPv6 only, there are two additional
8177 			 * phys_addr_req's sent to the driver to get the
8178 			 * IPv6 token and lla. This allows IP to acquire
8179 			 * the hardware address format for a given interface
8180 			 * without having built in knowledge of the hardware
8181 			 * address. ill_phys_addr_pend keeps track of the last
8182 			 * DL_PAR sent so we know which response we are
8183 			 * dealing with. ill_dlpi_done will update
8184 			 * ill_phys_addr_pend when it sends the next req.
8185 			 * We don't complete the IOCTL until all three DL_PARs
8186 			 * have been attempted, so set *_len to 0 and break.
8187 			 */
8188 			paddrreq = ill->ill_phys_addr_pend;
8189 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8190 			if (paddrreq == DL_IPV6_TOKEN) {
8191 				ill->ill_token_length = 0;
8192 				log = B_FALSE;
8193 				break;
8194 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8195 				ill->ill_nd_lla_len = 0;
8196 				log = B_FALSE;
8197 				break;
8198 			}
8199 			/*
8200 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8201 			 * We presumably have an IOCTL hanging out waiting
8202 			 * for completion. Find it and complete the IOCTL
8203 			 * with the error noted.
8204 			 * However, ill_dl_phys was called on an ill queue
8205 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8206 			 * set. But the ioctl is known to be pending on ill_wq.
8207 			 */
8208 			if (!ill->ill_ifname_pending)
8209 				break;
8210 			ill->ill_ifname_pending = 0;
8211 			if (!ioctl_aborted)
8212 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8213 			if (mp1 != NULL) {
8214 				/*
8215 				 * This operation (SIOCSLIFNAME) must have
8216 				 * happened on the ill. Assert there is no conn
8217 				 */
8218 				ASSERT(connp == NULL);
8219 				q = ill->ill_wq;
8220 			}
8221 			break;
8222 		case DL_BIND_REQ:
8223 			ill_dlpi_done(ill, DL_BIND_REQ);
8224 			if (ill->ill_ifname_pending)
8225 				break;
8226 			mutex_enter(&ill->ill_lock);
8227 			ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8228 			mutex_exit(&ill->ill_lock);
8229 			/*
8230 			 * Something went wrong with the bind.  We presumably
8231 			 * have an IOCTL hanging out waiting for completion.
8232 			 * Find it, take down the interface that was coming
8233 			 * up, and complete the IOCTL with the error noted.
8234 			 */
8235 			if (!ioctl_aborted)
8236 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8237 			if (mp1 != NULL) {
8238 				/*
8239 				 * This might be a result of a DL_NOTE_REPLUMB
8240 				 * notification. In that case, connp is NULL.
8241 				 */
8242 				if (connp != NULL)
8243 					q = CONNP_TO_WQ(connp);
8244 
8245 				(void) ipif_down(ipif, NULL, NULL);
8246 				/* error is set below the switch */
8247 			}
8248 			break;
8249 		case DL_ENABMULTI_REQ:
8250 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8251 
8252 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8253 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8254 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8255 
8256 				printf("ip: joining multicasts failed (%d)"
8257 				    " on %s - will use link layer "
8258 				    "broadcasts for multicast\n",
8259 				    dlea->dl_errno, ill->ill_name);
8260 
8261 				/*
8262 				 * Set up for multi_bcast; We are the
8263 				 * writer, so ok to access ill->ill_ipif
8264 				 * without any lock.
8265 				 */
8266 				mutex_enter(&ill->ill_phyint->phyint_lock);
8267 				ill->ill_phyint->phyint_flags |=
8268 				    PHYI_MULTI_BCAST;
8269 				mutex_exit(&ill->ill_phyint->phyint_lock);
8270 
8271 			}
8272 			freemsg(mp);	/* Don't want to pass this up */
8273 			return;
8274 		case DL_CAPABILITY_REQ:
8275 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8276 			    "DL_CAPABILITY REQ\n"));
8277 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8278 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8279 			ill_capability_done(ill);
8280 			freemsg(mp);
8281 			return;
8282 		}
8283 		/*
8284 		 * Note the error for IOCTL completion (mp1 is set when
8285 		 * ready to complete ioctl). If ill_ifname_pending_err is
8286 		 * set, an error occured during plumbing (ill_ifname_pending),
8287 		 * so we want to report that error.
8288 		 *
8289 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8290 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8291 		 * expected to get errack'd if the driver doesn't support
8292 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8293 		 * if these error conditions are encountered.
8294 		 */
8295 		if (mp1 != NULL) {
8296 			if (ill->ill_ifname_pending_err != 0)  {
8297 				err = ill->ill_ifname_pending_err;
8298 				ill->ill_ifname_pending_err = 0;
8299 			} else {
8300 				err = dlea->dl_unix_errno ?
8301 				    dlea->dl_unix_errno : ENXIO;
8302 			}
8303 		/*
8304 		 * If we're plumbing an interface and an error hasn't already
8305 		 * been saved, set ill_ifname_pending_err to the error passed
8306 		 * up. Ignore the error if log is B_FALSE (see comment above).
8307 		 */
8308 		} else if (log && ill->ill_ifname_pending &&
8309 		    ill->ill_ifname_pending_err == 0) {
8310 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8311 			    dlea->dl_unix_errno : ENXIO;
8312 		}
8313 
8314 		if (log)
8315 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8316 			    dlea->dl_errno, dlea->dl_unix_errno);
8317 		break;
8318 	case DL_CAPABILITY_ACK:
8319 		ill_capability_ack(ill, mp);
8320 		/*
8321 		 * The message has been handed off to ill_capability_ack
8322 		 * and must not be freed below
8323 		 */
8324 		mp = NULL;
8325 		break;
8326 
8327 	case DL_INFO_ACK:
8328 		/* Call a routine to handle this one. */
8329 		ill_dlpi_done(ill, DL_INFO_REQ);
8330 		ip_ll_subnet_defaults(ill, mp);
8331 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8332 		return;
8333 	case DL_BIND_ACK:
8334 		/*
8335 		 * We should have an IOCTL waiting on this unless
8336 		 * sent by ill_dl_phys, in which case just return
8337 		 */
8338 		ill_dlpi_done(ill, DL_BIND_REQ);
8339 
8340 		if (ill->ill_ifname_pending) {
8341 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8342 			    ill_t *, ill, mblk_t *, mp);
8343 			break;
8344 		}
8345 		mutex_enter(&ill->ill_lock);
8346 		ill->ill_dl_up = 1;
8347 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8348 		mutex_exit(&ill->ill_lock);
8349 
8350 		if (!ioctl_aborted)
8351 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8352 		if (mp1 == NULL) {
8353 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8354 			break;
8355 		}
8356 		/*
8357 		 * mp1 was added by ill_dl_up(). if that is a result of
8358 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8359 		 */
8360 		if (connp != NULL)
8361 			q = CONNP_TO_WQ(connp);
8362 		/*
8363 		 * We are exclusive. So nothing can change even after
8364 		 * we get the pending mp.
8365 		 */
8366 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8367 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8368 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8369 
8370 		/*
8371 		 * Now bring up the resolver; when that is complete, we'll
8372 		 * create IREs.  Note that we intentionally mirror what
8373 		 * ipif_up() would have done, because we got here by way of
8374 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8375 		 */
8376 		if (ill->ill_isv6) {
8377 			/*
8378 			 * v6 interfaces.
8379 			 * Unlike ARP which has to do another bind
8380 			 * and attach, once we get here we are
8381 			 * done with NDP
8382 			 */
8383 			(void) ipif_resolver_up(ipif, Res_act_initial);
8384 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8385 				err = ipif_up_done_v6(ipif);
8386 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8387 			/*
8388 			 * ARP and other v4 external resolvers.
8389 			 * Leave the pending mblk intact so that
8390 			 * the ioctl completes in ip_rput().
8391 			 */
8392 			if (connp != NULL)
8393 				mutex_enter(&connp->conn_lock);
8394 			mutex_enter(&ill->ill_lock);
8395 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8396 			mutex_exit(&ill->ill_lock);
8397 			if (connp != NULL)
8398 				mutex_exit(&connp->conn_lock);
8399 			if (success) {
8400 				err = ipif_resolver_up(ipif, Res_act_initial);
8401 				if (err == EINPROGRESS) {
8402 					freemsg(mp);
8403 					return;
8404 				}
8405 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8406 			} else {
8407 				/* The conn has started closing */
8408 				err = EINTR;
8409 			}
8410 		} else {
8411 			/*
8412 			 * This one is complete. Reply to pending ioctl.
8413 			 */
8414 			(void) ipif_resolver_up(ipif, Res_act_initial);
8415 			err = ipif_up_done(ipif);
8416 		}
8417 
8418 		if ((err == 0) && (ill->ill_up_ipifs)) {
8419 			err = ill_up_ipifs(ill, q, mp1);
8420 			if (err == EINPROGRESS) {
8421 				freemsg(mp);
8422 				return;
8423 			}
8424 		}
8425 
8426 		/*
8427 		 * If we have a moved ipif to bring up, and everything has
8428 		 * succeeded to this point, bring it up on the IPMP ill.
8429 		 * Otherwise, leave it down -- the admin can try to bring it
8430 		 * up by hand if need be.
8431 		 */
8432 		if (ill->ill_move_ipif != NULL) {
8433 			if (err != 0) {
8434 				ill->ill_move_ipif = NULL;
8435 			} else {
8436 				ipif = ill->ill_move_ipif;
8437 				ill->ill_move_ipif = NULL;
8438 				err = ipif_up(ipif, q, mp1);
8439 				if (err == EINPROGRESS) {
8440 					freemsg(mp);
8441 					return;
8442 				}
8443 			}
8444 		}
8445 		break;
8446 
8447 	case DL_NOTIFY_IND: {
8448 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8449 		uint_t orig_mtu;
8450 
8451 		switch (notify->dl_notification) {
8452 		case DL_NOTE_PHYS_ADDR:
8453 			err = ill_set_phys_addr(ill, mp);
8454 			break;
8455 
8456 		case DL_NOTE_REPLUMB:
8457 			/*
8458 			 * Directly return after calling ill_replumb().
8459 			 * Note that we should not free mp as it is reused
8460 			 * in the ill_replumb() function.
8461 			 */
8462 			err = ill_replumb(ill, mp);
8463 			return;
8464 
8465 		case DL_NOTE_FASTPATH_FLUSH:
8466 			nce_flush(ill, B_FALSE);
8467 			break;
8468 
8469 		case DL_NOTE_SDU_SIZE:
8470 			/*
8471 			 * The dce and fragmentation code can cope with
8472 			 * this changing while packets are being sent.
8473 			 * When packets are sent ip_output will discover
8474 			 * a change.
8475 			 *
8476 			 * Change the MTU size of the interface.
8477 			 */
8478 			mutex_enter(&ill->ill_lock);
8479 			ill->ill_current_frag = (uint_t)notify->dl_data;
8480 			if (ill->ill_current_frag > ill->ill_max_frag)
8481 				ill->ill_max_frag = ill->ill_current_frag;
8482 
8483 			orig_mtu = ill->ill_mtu;
8484 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8485 				ill->ill_mtu = ill->ill_current_frag;
8486 
8487 				/*
8488 				 * If ill_user_mtu was set (via
8489 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8490 				 */
8491 				if (ill->ill_user_mtu != 0 &&
8492 				    ill->ill_user_mtu < ill->ill_mtu)
8493 					ill->ill_mtu = ill->ill_user_mtu;
8494 
8495 				if (ill->ill_isv6) {
8496 					if (ill->ill_mtu < IPV6_MIN_MTU)
8497 						ill->ill_mtu = IPV6_MIN_MTU;
8498 				} else {
8499 					if (ill->ill_mtu < IP_MIN_MTU)
8500 						ill->ill_mtu = IP_MIN_MTU;
8501 				}
8502 			}
8503 			mutex_exit(&ill->ill_lock);
8504 			/*
8505 			 * Make sure all dce_generation checks find out
8506 			 * that ill_mtu has changed.
8507 			 */
8508 			if (orig_mtu != ill->ill_mtu) {
8509 				dce_increment_all_generations(ill->ill_isv6,
8510 				    ill->ill_ipst);
8511 			}
8512 
8513 			/*
8514 			 * Refresh IPMP meta-interface MTU if necessary.
8515 			 */
8516 			if (IS_UNDER_IPMP(ill))
8517 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8518 			break;
8519 
8520 		case DL_NOTE_LINK_UP:
8521 		case DL_NOTE_LINK_DOWN: {
8522 			/*
8523 			 * We are writer. ill / phyint / ipsq assocs stable.
8524 			 * The RUNNING flag reflects the state of the link.
8525 			 */
8526 			phyint_t *phyint = ill->ill_phyint;
8527 			uint64_t new_phyint_flags;
8528 			boolean_t changed = B_FALSE;
8529 			boolean_t went_up;
8530 
8531 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8532 			mutex_enter(&phyint->phyint_lock);
8533 
8534 			new_phyint_flags = went_up ?
8535 			    phyint->phyint_flags | PHYI_RUNNING :
8536 			    phyint->phyint_flags & ~PHYI_RUNNING;
8537 
8538 			if (IS_IPMP(ill)) {
8539 				new_phyint_flags = went_up ?
8540 				    new_phyint_flags & ~PHYI_FAILED :
8541 				    new_phyint_flags | PHYI_FAILED;
8542 			}
8543 
8544 			if (new_phyint_flags != phyint->phyint_flags) {
8545 				phyint->phyint_flags = new_phyint_flags;
8546 				changed = B_TRUE;
8547 			}
8548 			mutex_exit(&phyint->phyint_lock);
8549 			/*
8550 			 * ill_restart_dad handles the DAD restart and routing
8551 			 * socket notification logic.
8552 			 */
8553 			if (changed) {
8554 				ill_restart_dad(phyint->phyint_illv4, went_up);
8555 				ill_restart_dad(phyint->phyint_illv6, went_up);
8556 			}
8557 			break;
8558 		}
8559 		case DL_NOTE_PROMISC_ON_PHYS: {
8560 			phyint_t *phyint = ill->ill_phyint;
8561 
8562 			mutex_enter(&phyint->phyint_lock);
8563 			phyint->phyint_flags |= PHYI_PROMISC;
8564 			mutex_exit(&phyint->phyint_lock);
8565 			break;
8566 		}
8567 		case DL_NOTE_PROMISC_OFF_PHYS: {
8568 			phyint_t *phyint = ill->ill_phyint;
8569 
8570 			mutex_enter(&phyint->phyint_lock);
8571 			phyint->phyint_flags &= ~PHYI_PROMISC;
8572 			mutex_exit(&phyint->phyint_lock);
8573 			break;
8574 		}
8575 		case DL_NOTE_CAPAB_RENEG:
8576 			/*
8577 			 * Something changed on the driver side.
8578 			 * It wants us to renegotiate the capabilities
8579 			 * on this ill. One possible cause is the aggregation
8580 			 * interface under us where a port got added or
8581 			 * went away.
8582 			 *
8583 			 * If the capability negotiation is already done
8584 			 * or is in progress, reset the capabilities and
8585 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8586 			 * so that when the ack comes back, we can start
8587 			 * the renegotiation process.
8588 			 *
8589 			 * Note that if ill_capab_reneg is already B_TRUE
8590 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8591 			 * the capability resetting request has been sent
8592 			 * and the renegotiation has not been started yet;
8593 			 * nothing needs to be done in this case.
8594 			 */
8595 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8596 			ill_capability_reset(ill, B_TRUE);
8597 			ipsq_current_finish(ipsq);
8598 			break;
8599 
8600 		case DL_NOTE_ALLOWED_IPS:
8601 			ill_set_allowed_ips(ill, mp);
8602 			break;
8603 		default:
8604 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8605 			    "type 0x%x for DL_NOTIFY_IND\n",
8606 			    notify->dl_notification));
8607 			break;
8608 		}
8609 
8610 		/*
8611 		 * As this is an asynchronous operation, we
8612 		 * should not call ill_dlpi_done
8613 		 */
8614 		break;
8615 	}
8616 	case DL_NOTIFY_ACK: {
8617 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8618 
8619 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8620 			ill->ill_note_link = 1;
8621 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8622 		break;
8623 	}
8624 	case DL_PHYS_ADDR_ACK: {
8625 		/*
8626 		 * As part of plumbing the interface via SIOCSLIFNAME,
8627 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8628 		 * whose answers we receive here.  As each answer is received,
8629 		 * we call ill_dlpi_done() to dispatch the next request as
8630 		 * we're processing the current one.  Once all answers have
8631 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8632 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8633 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8634 		 * available, but we know the ioctl is pending on ill_wq.)
8635 		 */
8636 		uint_t	paddrlen, paddroff;
8637 		uint8_t	*addr;
8638 
8639 		paddrreq = ill->ill_phys_addr_pend;
8640 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8641 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8642 		addr = mp->b_rptr + paddroff;
8643 
8644 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8645 		if (paddrreq == DL_IPV6_TOKEN) {
8646 			/*
8647 			 * bcopy to low-order bits of ill_token
8648 			 *
8649 			 * XXX Temporary hack - currently, all known tokens
8650 			 * are 64 bits, so I'll cheat for the moment.
8651 			 */
8652 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8653 			ill->ill_token_length = paddrlen;
8654 			break;
8655 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8656 			ASSERT(ill->ill_nd_lla_mp == NULL);
8657 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8658 			mp = NULL;
8659 			break;
8660 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8661 			ASSERT(ill->ill_dest_addr_mp == NULL);
8662 			ill->ill_dest_addr_mp = mp;
8663 			ill->ill_dest_addr = addr;
8664 			mp = NULL;
8665 			if (ill->ill_isv6) {
8666 				ill_setdesttoken(ill);
8667 				ipif_setdestlinklocal(ill->ill_ipif);
8668 			}
8669 			break;
8670 		}
8671 
8672 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8673 		ASSERT(ill->ill_phys_addr_mp == NULL);
8674 		if (!ill->ill_ifname_pending)
8675 			break;
8676 		ill->ill_ifname_pending = 0;
8677 		if (!ioctl_aborted)
8678 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8679 		if (mp1 != NULL) {
8680 			ASSERT(connp == NULL);
8681 			q = ill->ill_wq;
8682 		}
8683 		/*
8684 		 * If any error acks received during the plumbing sequence,
8685 		 * ill_ifname_pending_err will be set. Break out and send up
8686 		 * the error to the pending ioctl.
8687 		 */
8688 		if (ill->ill_ifname_pending_err != 0) {
8689 			err = ill->ill_ifname_pending_err;
8690 			ill->ill_ifname_pending_err = 0;
8691 			break;
8692 		}
8693 
8694 		ill->ill_phys_addr_mp = mp;
8695 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8696 		mp = NULL;
8697 
8698 		/*
8699 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8700 		 * provider doesn't support physical addresses.  We check both
8701 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8702 		 * not have physical addresses, but historically adversises a
8703 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8704 		 * its DL_PHYS_ADDR_ACK.
8705 		 */
8706 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8707 			ill->ill_phys_addr = NULL;
8708 		} else if (paddrlen != ill->ill_phys_addr_length) {
8709 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8710 			    paddrlen, ill->ill_phys_addr_length));
8711 			err = EINVAL;
8712 			break;
8713 		}
8714 
8715 		if (ill->ill_nd_lla_mp == NULL) {
8716 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8717 				err = ENOMEM;
8718 				break;
8719 			}
8720 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8721 		}
8722 
8723 		if (ill->ill_isv6) {
8724 			ill_setdefaulttoken(ill);
8725 			ipif_setlinklocal(ill->ill_ipif);
8726 		}
8727 		break;
8728 	}
8729 	case DL_OK_ACK:
8730 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8731 		    dl_primstr((int)dloa->dl_correct_primitive),
8732 		    dloa->dl_correct_primitive));
8733 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8734 		    char *, dl_primstr(dloa->dl_correct_primitive),
8735 		    ill_t *, ill);
8736 
8737 		switch (dloa->dl_correct_primitive) {
8738 		case DL_ENABMULTI_REQ:
8739 		case DL_DISABMULTI_REQ:
8740 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8741 			break;
8742 		case DL_PROMISCON_REQ:
8743 		case DL_PROMISCOFF_REQ:
8744 		case DL_UNBIND_REQ:
8745 		case DL_ATTACH_REQ:
8746 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8747 			break;
8748 		}
8749 		break;
8750 	default:
8751 		break;
8752 	}
8753 
8754 	freemsg(mp);
8755 	if (mp1 == NULL)
8756 		return;
8757 
8758 	/*
8759 	 * The operation must complete without EINPROGRESS since
8760 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8761 	 * the operation will be stuck forever inside the IPSQ.
8762 	 */
8763 	ASSERT(err != EINPROGRESS);
8764 
8765 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8766 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8767 	    ipif_t *, NULL);
8768 
8769 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8770 	case 0:
8771 		ipsq_current_finish(ipsq);
8772 		break;
8773 
8774 	case SIOCSLIFNAME:
8775 	case IF_UNITSEL: {
8776 		ill_t *ill_other = ILL_OTHER(ill);
8777 
8778 		/*
8779 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8780 		 * ill has a peer which is in an IPMP group, then place ill
8781 		 * into the same group.  One catch: although ifconfig plumbs
8782 		 * the appropriate IPMP meta-interface prior to plumbing this
8783 		 * ill, it is possible for multiple ifconfig applications to
8784 		 * race (or for another application to adjust plumbing), in
8785 		 * which case the IPMP meta-interface we need will be missing.
8786 		 * If so, kick the phyint out of the group.
8787 		 */
8788 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8789 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8790 			ipmp_illgrp_t	*illg;
8791 
8792 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8793 			if (illg == NULL)
8794 				ipmp_phyint_leave_grp(ill->ill_phyint);
8795 			else
8796 				ipmp_ill_join_illgrp(ill, illg);
8797 		}
8798 
8799 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8800 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8801 		else
8802 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8803 		break;
8804 	}
8805 	case SIOCLIFADDIF:
8806 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8807 		break;
8808 
8809 	default:
8810 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8811 		break;
8812 	}
8813 }
8814 
8815 /*
8816  * ip_rput_other is called by ip_rput to handle messages modifying the global
8817  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8818  */
8819 /* ARGSUSED */
8820 void
8821 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8822 {
8823 	ill_t		*ill = q->q_ptr;
8824 	struct iocblk	*iocp;
8825 
8826 	ip1dbg(("ip_rput_other "));
8827 	if (ipsq != NULL) {
8828 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8829 		ASSERT(ipsq->ipsq_xop ==
8830 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8831 	}
8832 
8833 	switch (mp->b_datap->db_type) {
8834 	case M_ERROR:
8835 	case M_HANGUP:
8836 		/*
8837 		 * The device has a problem.  We force the ILL down.  It can
8838 		 * be brought up again manually using SIOCSIFFLAGS (via
8839 		 * ifconfig or equivalent).
8840 		 */
8841 		ASSERT(ipsq != NULL);
8842 		if (mp->b_rptr < mp->b_wptr)
8843 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8844 		if (ill->ill_error == 0)
8845 			ill->ill_error = ENXIO;
8846 		if (!ill_down_start(q, mp))
8847 			return;
8848 		ipif_all_down_tail(ipsq, q, mp, NULL);
8849 		break;
8850 	case M_IOCNAK: {
8851 		iocp = (struct iocblk *)mp->b_rptr;
8852 
8853 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8854 		/*
8855 		 * If this was the first attempt, turn off the fastpath
8856 		 * probing.
8857 		 */
8858 		mutex_enter(&ill->ill_lock);
8859 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8860 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8861 			mutex_exit(&ill->ill_lock);
8862 			/*
8863 			 * don't flush the nce_t entries: we use them
8864 			 * as an index to the ncec itself.
8865 			 */
8866 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8867 			    ill->ill_name));
8868 		} else {
8869 			mutex_exit(&ill->ill_lock);
8870 		}
8871 		freemsg(mp);
8872 		break;
8873 	}
8874 	default:
8875 		ASSERT(0);
8876 		break;
8877 	}
8878 }
8879 
8880 /*
8881  * Update any source route, record route or timestamp options
8882  * When it fails it has consumed the message and BUMPed the MIB.
8883  */
8884 boolean_t
8885 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8886     ip_recv_attr_t *ira)
8887 {
8888 	ipoptp_t	opts;
8889 	uchar_t		*opt;
8890 	uint8_t		optval;
8891 	uint8_t		optlen;
8892 	ipaddr_t	dst;
8893 	ipaddr_t	ifaddr;
8894 	uint32_t	ts;
8895 	timestruc_t	now;
8896 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
8897 
8898 	ip2dbg(("ip_forward_options\n"));
8899 	dst = ipha->ipha_dst;
8900 	for (optval = ipoptp_first(&opts, ipha);
8901 	    optval != IPOPT_EOL;
8902 	    optval = ipoptp_next(&opts)) {
8903 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
8904 		opt = opts.ipoptp_cur;
8905 		optlen = opts.ipoptp_len;
8906 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
8907 		    optval, opts.ipoptp_len));
8908 		switch (optval) {
8909 			uint32_t off;
8910 		case IPOPT_SSRR:
8911 		case IPOPT_LSRR:
8912 			/* Check if adminstratively disabled */
8913 			if (!ipst->ips_ip_forward_src_routed) {
8914 				BUMP_MIB(dst_ill->ill_ip_mib,
8915 				    ipIfStatsForwProhibits);
8916 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
8917 				    mp, dst_ill);
8918 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
8919 				    ira);
8920 				return (B_FALSE);
8921 			}
8922 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8923 				/*
8924 				 * Must be partial since ip_input_options
8925 				 * checked for strict.
8926 				 */
8927 				break;
8928 			}
8929 			off = opt[IPOPT_OFFSET];
8930 			off--;
8931 		redo_srr:
8932 			if (optlen < IP_ADDR_LEN ||
8933 			    off > optlen - IP_ADDR_LEN) {
8934 				/* End of source route */
8935 				ip1dbg((
8936 				    "ip_forward_options: end of SR\n"));
8937 				break;
8938 			}
8939 			/* Pick a reasonable address on the outbound if */
8940 			ASSERT(dst_ill != NULL);
8941 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8942 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8943 			    NULL) != 0) {
8944 				/* No source! Shouldn't happen */
8945 				ifaddr = INADDR_ANY;
8946 			}
8947 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8948 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8949 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
8950 			    ntohl(dst)));
8951 
8952 			/*
8953 			 * Check if our address is present more than
8954 			 * once as consecutive hops in source route.
8955 			 */
8956 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
8957 				off += IP_ADDR_LEN;
8958 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8959 				goto redo_srr;
8960 			}
8961 			ipha->ipha_dst = dst;
8962 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8963 			break;
8964 		case IPOPT_RR:
8965 			off = opt[IPOPT_OFFSET];
8966 			off--;
8967 			if (optlen < IP_ADDR_LEN ||
8968 			    off > optlen - IP_ADDR_LEN) {
8969 				/* No more room - ignore */
8970 				ip1dbg((
8971 				    "ip_forward_options: end of RR\n"));
8972 				break;
8973 			}
8974 			/* Pick a reasonable address on the outbound if */
8975 			ASSERT(dst_ill != NULL);
8976 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8977 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8978 			    NULL) != 0) {
8979 				/* No source! Shouldn't happen */
8980 				ifaddr = INADDR_ANY;
8981 			}
8982 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8983 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8984 			break;
8985 		case IPOPT_TS:
8986 			/* Insert timestamp if there is room */
8987 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
8988 			case IPOPT_TS_TSONLY:
8989 				off = IPOPT_TS_TIMELEN;
8990 				break;
8991 			case IPOPT_TS_PRESPEC:
8992 			case IPOPT_TS_PRESPEC_RFC791:
8993 				/* Verify that the address matched */
8994 				off = opt[IPOPT_OFFSET] - 1;
8995 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8996 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8997 					/* Not for us */
8998 					break;
8999 				}
9000 				/* FALLTHRU */
9001 			case IPOPT_TS_TSANDADDR:
9002 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9003 				break;
9004 			default:
9005 				/*
9006 				 * ip_*put_options should have already
9007 				 * dropped this packet.
9008 				 */
9009 				cmn_err(CE_PANIC, "ip_forward_options: "
9010 				    "unknown IT - bug in ip_input_options?\n");
9011 				return (B_TRUE);	/* Keep "lint" happy */
9012 			}
9013 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9014 				/* Increase overflow counter */
9015 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9016 				opt[IPOPT_POS_OV_FLG] =
9017 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9018 				    (off << 4));
9019 				break;
9020 			}
9021 			off = opt[IPOPT_OFFSET] - 1;
9022 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9023 			case IPOPT_TS_PRESPEC:
9024 			case IPOPT_TS_PRESPEC_RFC791:
9025 			case IPOPT_TS_TSANDADDR:
9026 				/* Pick a reasonable addr on the outbound if */
9027 				ASSERT(dst_ill != NULL);
9028 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9029 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9030 				    NULL, NULL) != 0) {
9031 					/* No source! Shouldn't happen */
9032 					ifaddr = INADDR_ANY;
9033 				}
9034 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9035 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9036 				/* FALLTHRU */
9037 			case IPOPT_TS_TSONLY:
9038 				off = opt[IPOPT_OFFSET] - 1;
9039 				/* Compute # of milliseconds since midnight */
9040 				gethrestime(&now);
9041 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9042 				    now.tv_nsec / (NANOSEC / MILLISEC);
9043 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9044 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9045 				break;
9046 			}
9047 			break;
9048 		}
9049 	}
9050 	return (B_TRUE);
9051 }
9052 
9053 /*
9054  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9055  * returns 'true' if there are still fragments left on the queue, in
9056  * which case we restart the timer.
9057  */
9058 void
9059 ill_frag_timer(void *arg)
9060 {
9061 	ill_t	*ill = (ill_t *)arg;
9062 	boolean_t frag_pending;
9063 	ip_stack_t *ipst = ill->ill_ipst;
9064 	time_t	timeout;
9065 
9066 	mutex_enter(&ill->ill_lock);
9067 	ASSERT(!ill->ill_fragtimer_executing);
9068 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9069 		ill->ill_frag_timer_id = 0;
9070 		mutex_exit(&ill->ill_lock);
9071 		return;
9072 	}
9073 	ill->ill_fragtimer_executing = 1;
9074 	mutex_exit(&ill->ill_lock);
9075 
9076 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9077 	    ipst->ips_ip_reassembly_timeout);
9078 
9079 	frag_pending = ill_frag_timeout(ill, timeout);
9080 
9081 	/*
9082 	 * Restart the timer, if we have fragments pending or if someone
9083 	 * wanted us to be scheduled again.
9084 	 */
9085 	mutex_enter(&ill->ill_lock);
9086 	ill->ill_fragtimer_executing = 0;
9087 	ill->ill_frag_timer_id = 0;
9088 	if (frag_pending || ill->ill_fragtimer_needrestart)
9089 		ill_frag_timer_start(ill);
9090 	mutex_exit(&ill->ill_lock);
9091 }
9092 
9093 void
9094 ill_frag_timer_start(ill_t *ill)
9095 {
9096 	ip_stack_t *ipst = ill->ill_ipst;
9097 	clock_t	timeo_ms;
9098 
9099 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9100 
9101 	/* If the ill is closing or opening don't proceed */
9102 	if (ill->ill_state_flags & ILL_CONDEMNED)
9103 		return;
9104 
9105 	if (ill->ill_fragtimer_executing) {
9106 		/*
9107 		 * ill_frag_timer is currently executing. Just record the
9108 		 * the fact that we want the timer to be restarted.
9109 		 * ill_frag_timer will post a timeout before it returns,
9110 		 * ensuring it will be called again.
9111 		 */
9112 		ill->ill_fragtimer_needrestart = 1;
9113 		return;
9114 	}
9115 
9116 	if (ill->ill_frag_timer_id == 0) {
9117 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9118 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9119 
9120 		/*
9121 		 * The timer is neither running nor is the timeout handler
9122 		 * executing. Post a timeout so that ill_frag_timer will be
9123 		 * called
9124 		 */
9125 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9126 		    MSEC_TO_TICK(timeo_ms >> 1));
9127 		ill->ill_fragtimer_needrestart = 0;
9128 	}
9129 }
9130 
9131 /*
9132  * Update any source route, record route or timestamp options.
9133  * Check that we are at end of strict source route.
9134  * The options have already been checked for sanity in ip_input_options().
9135  */
9136 boolean_t
9137 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9138 {
9139 	ipoptp_t	opts;
9140 	uchar_t		*opt;
9141 	uint8_t		optval;
9142 	uint8_t		optlen;
9143 	ipaddr_t	dst;
9144 	ipaddr_t	ifaddr;
9145 	uint32_t	ts;
9146 	timestruc_t	now;
9147 	ill_t		*ill = ira->ira_ill;
9148 	ip_stack_t	*ipst = ill->ill_ipst;
9149 
9150 	ip2dbg(("ip_input_local_options\n"));
9151 
9152 	for (optval = ipoptp_first(&opts, ipha);
9153 	    optval != IPOPT_EOL;
9154 	    optval = ipoptp_next(&opts)) {
9155 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9156 		opt = opts.ipoptp_cur;
9157 		optlen = opts.ipoptp_len;
9158 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9159 		    optval, optlen));
9160 		switch (optval) {
9161 			uint32_t off;
9162 		case IPOPT_SSRR:
9163 		case IPOPT_LSRR:
9164 			off = opt[IPOPT_OFFSET];
9165 			off--;
9166 			if (optlen < IP_ADDR_LEN ||
9167 			    off > optlen - IP_ADDR_LEN) {
9168 				/* End of source route */
9169 				ip1dbg(("ip_input_local_options: end of SR\n"));
9170 				break;
9171 			}
9172 			/*
9173 			 * This will only happen if two consecutive entries
9174 			 * in the source route contains our address or if
9175 			 * it is a packet with a loose source route which
9176 			 * reaches us before consuming the whole source route
9177 			 */
9178 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9179 			if (optval == IPOPT_SSRR) {
9180 				goto bad_src_route;
9181 			}
9182 			/*
9183 			 * Hack: instead of dropping the packet truncate the
9184 			 * source route to what has been used by filling the
9185 			 * rest with IPOPT_NOP.
9186 			 */
9187 			opt[IPOPT_OLEN] = (uint8_t)off;
9188 			while (off < optlen) {
9189 				opt[off++] = IPOPT_NOP;
9190 			}
9191 			break;
9192 		case IPOPT_RR:
9193 			off = opt[IPOPT_OFFSET];
9194 			off--;
9195 			if (optlen < IP_ADDR_LEN ||
9196 			    off > optlen - IP_ADDR_LEN) {
9197 				/* No more room - ignore */
9198 				ip1dbg((
9199 				    "ip_input_local_options: end of RR\n"));
9200 				break;
9201 			}
9202 			/* Pick a reasonable address on the outbound if */
9203 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9204 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9205 			    NULL) != 0) {
9206 				/* No source! Shouldn't happen */
9207 				ifaddr = INADDR_ANY;
9208 			}
9209 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9210 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9211 			break;
9212 		case IPOPT_TS:
9213 			/* Insert timestamp if there is romm */
9214 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9215 			case IPOPT_TS_TSONLY:
9216 				off = IPOPT_TS_TIMELEN;
9217 				break;
9218 			case IPOPT_TS_PRESPEC:
9219 			case IPOPT_TS_PRESPEC_RFC791:
9220 				/* Verify that the address matched */
9221 				off = opt[IPOPT_OFFSET] - 1;
9222 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9223 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9224 					/* Not for us */
9225 					break;
9226 				}
9227 				/* FALLTHRU */
9228 			case IPOPT_TS_TSANDADDR:
9229 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9230 				break;
9231 			default:
9232 				/*
9233 				 * ip_*put_options should have already
9234 				 * dropped this packet.
9235 				 */
9236 				cmn_err(CE_PANIC, "ip_input_local_options: "
9237 				    "unknown IT - bug in ip_input_options?\n");
9238 				return (B_TRUE);	/* Keep "lint" happy */
9239 			}
9240 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9241 				/* Increase overflow counter */
9242 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9243 				opt[IPOPT_POS_OV_FLG] =
9244 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9245 				    (off << 4));
9246 				break;
9247 			}
9248 			off = opt[IPOPT_OFFSET] - 1;
9249 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9250 			case IPOPT_TS_PRESPEC:
9251 			case IPOPT_TS_PRESPEC_RFC791:
9252 			case IPOPT_TS_TSANDADDR:
9253 				/* Pick a reasonable addr on the outbound if */
9254 				if (ip_select_source_v4(ill, INADDR_ANY,
9255 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9256 				    &ifaddr, NULL, NULL) != 0) {
9257 					/* No source! Shouldn't happen */
9258 					ifaddr = INADDR_ANY;
9259 				}
9260 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9261 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9262 				/* FALLTHRU */
9263 			case IPOPT_TS_TSONLY:
9264 				off = opt[IPOPT_OFFSET] - 1;
9265 				/* Compute # of milliseconds since midnight */
9266 				gethrestime(&now);
9267 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9268 				    now.tv_nsec / (NANOSEC / MILLISEC);
9269 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9270 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9271 				break;
9272 			}
9273 			break;
9274 		}
9275 	}
9276 	return (B_TRUE);
9277 
9278 bad_src_route:
9279 	/* make sure we clear any indication of a hardware checksum */
9280 	DB_CKSUMFLAGS(mp) = 0;
9281 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9282 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9283 	return (B_FALSE);
9284 
9285 }
9286 
9287 /*
9288  * Process IP options in an inbound packet.  Always returns the nexthop.
9289  * Normally this is the passed in nexthop, but if there is an option
9290  * that effects the nexthop (such as a source route) that will be returned.
9291  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9292  * and mp freed.
9293  */
9294 ipaddr_t
9295 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9296     ip_recv_attr_t *ira, int *errorp)
9297 {
9298 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9299 	ipoptp_t	opts;
9300 	uchar_t		*opt;
9301 	uint8_t		optval;
9302 	uint8_t		optlen;
9303 	intptr_t	code = 0;
9304 	ire_t		*ire;
9305 
9306 	ip2dbg(("ip_input_options\n"));
9307 	*errorp = 0;
9308 	for (optval = ipoptp_first(&opts, ipha);
9309 	    optval != IPOPT_EOL;
9310 	    optval = ipoptp_next(&opts)) {
9311 		opt = opts.ipoptp_cur;
9312 		optlen = opts.ipoptp_len;
9313 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9314 		    optval, optlen));
9315 		/*
9316 		 * Note: we need to verify the checksum before we
9317 		 * modify anything thus this routine only extracts the next
9318 		 * hop dst from any source route.
9319 		 */
9320 		switch (optval) {
9321 			uint32_t off;
9322 		case IPOPT_SSRR:
9323 		case IPOPT_LSRR:
9324 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9325 				if (optval == IPOPT_SSRR) {
9326 					ip1dbg(("ip_input_options: not next"
9327 					    " strict source route 0x%x\n",
9328 					    ntohl(dst)));
9329 					code = (char *)&ipha->ipha_dst -
9330 					    (char *)ipha;
9331 					goto param_prob; /* RouterReq's */
9332 				}
9333 				ip2dbg(("ip_input_options: "
9334 				    "not next source route 0x%x\n",
9335 				    ntohl(dst)));
9336 				break;
9337 			}
9338 
9339 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9340 				ip1dbg((
9341 				    "ip_input_options: bad option offset\n"));
9342 				code = (char *)&opt[IPOPT_OLEN] -
9343 				    (char *)ipha;
9344 				goto param_prob;
9345 			}
9346 			off = opt[IPOPT_OFFSET];
9347 			off--;
9348 		redo_srr:
9349 			if (optlen < IP_ADDR_LEN ||
9350 			    off > optlen - IP_ADDR_LEN) {
9351 				/* End of source route */
9352 				ip1dbg(("ip_input_options: end of SR\n"));
9353 				break;
9354 			}
9355 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9356 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9357 			    ntohl(dst)));
9358 
9359 			/*
9360 			 * Check if our address is present more than
9361 			 * once as consecutive hops in source route.
9362 			 * XXX verify per-interface ip_forwarding
9363 			 * for source route?
9364 			 */
9365 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9366 				off += IP_ADDR_LEN;
9367 				goto redo_srr;
9368 			}
9369 
9370 			if (dst == htonl(INADDR_LOOPBACK)) {
9371 				ip1dbg(("ip_input_options: loopback addr in "
9372 				    "source route!\n"));
9373 				goto bad_src_route;
9374 			}
9375 			/*
9376 			 * For strict: verify that dst is directly
9377 			 * reachable.
9378 			 */
9379 			if (optval == IPOPT_SSRR) {
9380 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9381 				    IRE_IF_ALL, NULL, ALL_ZONES,
9382 				    ira->ira_tsl,
9383 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9384 				    NULL);
9385 				if (ire == NULL) {
9386 					ip1dbg(("ip_input_options: SSRR not "
9387 					    "directly reachable: 0x%x\n",
9388 					    ntohl(dst)));
9389 					goto bad_src_route;
9390 				}
9391 				ire_refrele(ire);
9392 			}
9393 			/*
9394 			 * Defer update of the offset and the record route
9395 			 * until the packet is forwarded.
9396 			 */
9397 			break;
9398 		case IPOPT_RR:
9399 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9400 				ip1dbg((
9401 				    "ip_input_options: bad option offset\n"));
9402 				code = (char *)&opt[IPOPT_OLEN] -
9403 				    (char *)ipha;
9404 				goto param_prob;
9405 			}
9406 			break;
9407 		case IPOPT_TS:
9408 			/*
9409 			 * Verify that length >= 5 and that there is either
9410 			 * room for another timestamp or that the overflow
9411 			 * counter is not maxed out.
9412 			 */
9413 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9414 			if (optlen < IPOPT_MINLEN_IT) {
9415 				goto param_prob;
9416 			}
9417 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9418 				ip1dbg((
9419 				    "ip_input_options: bad option offset\n"));
9420 				code = (char *)&opt[IPOPT_OFFSET] -
9421 				    (char *)ipha;
9422 				goto param_prob;
9423 			}
9424 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9425 			case IPOPT_TS_TSONLY:
9426 				off = IPOPT_TS_TIMELEN;
9427 				break;
9428 			case IPOPT_TS_TSANDADDR:
9429 			case IPOPT_TS_PRESPEC:
9430 			case IPOPT_TS_PRESPEC_RFC791:
9431 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9432 				break;
9433 			default:
9434 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9435 				    (char *)ipha;
9436 				goto param_prob;
9437 			}
9438 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9439 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9440 				/*
9441 				 * No room and the overflow counter is 15
9442 				 * already.
9443 				 */
9444 				goto param_prob;
9445 			}
9446 			break;
9447 		}
9448 	}
9449 
9450 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9451 		return (dst);
9452 	}
9453 
9454 	ip1dbg(("ip_input_options: error processing IP options."));
9455 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9456 
9457 param_prob:
9458 	/* make sure we clear any indication of a hardware checksum */
9459 	DB_CKSUMFLAGS(mp) = 0;
9460 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9461 	icmp_param_problem(mp, (uint8_t)code, ira);
9462 	*errorp = -1;
9463 	return (dst);
9464 
9465 bad_src_route:
9466 	/* make sure we clear any indication of a hardware checksum */
9467 	DB_CKSUMFLAGS(mp) = 0;
9468 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9469 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9470 	*errorp = -1;
9471 	return (dst);
9472 }
9473 
9474 /*
9475  * IP & ICMP info in >=14 msg's ...
9476  *  - ip fixed part (mib2_ip_t)
9477  *  - icmp fixed part (mib2_icmp_t)
9478  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9479  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9480  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9481  *  - ipRouteAttributeTable (ip 102)	labeled routes
9482  *  - ip multicast membership (ip_member_t)
9483  *  - ip multicast source filtering (ip_grpsrc_t)
9484  *  - igmp fixed part (struct igmpstat)
9485  *  - multicast routing stats (struct mrtstat)
9486  *  - multicast routing vifs (array of struct vifctl)
9487  *  - multicast routing routes (array of struct mfcctl)
9488  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9489  *					One per ill plus one generic
9490  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9491  *					One per ill plus one generic
9492  *  - ipv6RouteEntry			all IPv6 IREs
9493  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9494  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9495  *  - ipv6AddrEntry			all IPv6 ipifs
9496  *  - ipv6 multicast membership (ipv6_member_t)
9497  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9498  *
9499  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9500  * already filled in by the caller.
9501  * If legacy_req is true then MIB structures needs to be truncated to their
9502  * legacy sizes before being returned.
9503  * Return value of 0 indicates that no messages were sent and caller
9504  * should free mpctl.
9505  */
9506 int
9507 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level, boolean_t legacy_req)
9508 {
9509 	ip_stack_t *ipst;
9510 	sctp_stack_t *sctps;
9511 
9512 	if (q->q_next != NULL) {
9513 		ipst = ILLQ_TO_IPST(q);
9514 	} else {
9515 		ipst = CONNQ_TO_IPST(q);
9516 	}
9517 	ASSERT(ipst != NULL);
9518 	sctps = ipst->ips_netstack->netstack_sctp;
9519 
9520 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9521 		return (0);
9522 	}
9523 
9524 	/*
9525 	 * For the purposes of the (broken) packet shell use
9526 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9527 	 * to make TCP and UDP appear first in the list of mib items.
9528 	 * TBD: We could expand this and use it in netstat so that
9529 	 * the kernel doesn't have to produce large tables (connections,
9530 	 * routes, etc) when netstat only wants the statistics or a particular
9531 	 * table.
9532 	 */
9533 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9534 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9535 			return (1);
9536 		}
9537 	}
9538 
9539 	if (level != MIB2_TCP) {
9540 		if ((mpctl = udp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9541 			return (1);
9542 		}
9543 	}
9544 
9545 	if (level != MIB2_UDP) {
9546 		if ((mpctl = tcp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9547 			return (1);
9548 		}
9549 	}
9550 
9551 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9552 	    ipst, legacy_req)) == NULL) {
9553 		return (1);
9554 	}
9555 
9556 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst,
9557 	    legacy_req)) == NULL) {
9558 		return (1);
9559 	}
9560 
9561 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9562 		return (1);
9563 	}
9564 
9565 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9566 		return (1);
9567 	}
9568 
9569 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9570 		return (1);
9571 	}
9572 
9573 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9574 		return (1);
9575 	}
9576 
9577 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst,
9578 	    legacy_req)) == NULL) {
9579 		return (1);
9580 	}
9581 
9582 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst,
9583 	    legacy_req)) == NULL) {
9584 		return (1);
9585 	}
9586 
9587 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9588 		return (1);
9589 	}
9590 
9591 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9592 		return (1);
9593 	}
9594 
9595 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9596 		return (1);
9597 	}
9598 
9599 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9600 		return (1);
9601 	}
9602 
9603 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9604 		return (1);
9605 	}
9606 
9607 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9608 		return (1);
9609 	}
9610 
9611 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9612 	if (mpctl == NULL)
9613 		return (1);
9614 
9615 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9616 	if (mpctl == NULL)
9617 		return (1);
9618 
9619 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9620 		return (1);
9621 	}
9622 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9623 		return (1);
9624 	}
9625 	freemsg(mpctl);
9626 	return (1);
9627 }
9628 
9629 /* Get global (legacy) IPv4 statistics */
9630 static mblk_t *
9631 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9632     ip_stack_t *ipst, boolean_t legacy_req)
9633 {
9634 	mib2_ip_t		old_ip_mib;
9635 	struct opthdr		*optp;
9636 	mblk_t			*mp2ctl;
9637 	mib2_ipAddrEntry_t	mae;
9638 
9639 	/*
9640 	 * make a copy of the original message
9641 	 */
9642 	mp2ctl = copymsg(mpctl);
9643 
9644 	/* fixed length IP structure... */
9645 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9646 	optp->level = MIB2_IP;
9647 	optp->name = 0;
9648 	SET_MIB(old_ip_mib.ipForwarding,
9649 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9650 	SET_MIB(old_ip_mib.ipDefaultTTL,
9651 	    (uint32_t)ipst->ips_ip_def_ttl);
9652 	SET_MIB(old_ip_mib.ipReasmTimeout,
9653 	    ipst->ips_ip_reassembly_timeout);
9654 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9655 	    (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9656 	    sizeof (mib2_ipAddrEntry_t));
9657 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9658 	    sizeof (mib2_ipRouteEntry_t));
9659 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9660 	    sizeof (mib2_ipNetToMediaEntry_t));
9661 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9662 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9663 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9664 	    sizeof (mib2_ipAttributeEntry_t));
9665 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9666 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9667 
9668 	/*
9669 	 * Grab the statistics from the new IP MIB
9670 	 */
9671 	SET_MIB(old_ip_mib.ipInReceives,
9672 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9673 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9674 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9675 	SET_MIB(old_ip_mib.ipForwDatagrams,
9676 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9677 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9678 	    ipmib->ipIfStatsInUnknownProtos);
9679 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9680 	SET_MIB(old_ip_mib.ipInDelivers,
9681 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9682 	SET_MIB(old_ip_mib.ipOutRequests,
9683 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9684 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9685 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9686 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9687 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9688 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9689 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9690 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9691 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9692 
9693 	/* ipRoutingDiscards is not being used */
9694 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9695 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9696 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9697 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9698 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9699 	    ipmib->ipIfStatsReasmDuplicates);
9700 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9701 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9702 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9703 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9704 	SET_MIB(old_ip_mib.rawipInOverflows,
9705 	    ipmib->rawipIfStatsInOverflows);
9706 
9707 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9708 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9709 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9710 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9711 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9712 	    ipmib->ipIfStatsOutSwitchIPVersion);
9713 
9714 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9715 	    (int)sizeof (old_ip_mib))) {
9716 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9717 		    (uint_t)sizeof (old_ip_mib)));
9718 	}
9719 
9720 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9721 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9722 	    (int)optp->level, (int)optp->name, (int)optp->len));
9723 	qreply(q, mpctl);
9724 	return (mp2ctl);
9725 }
9726 
9727 /* Per interface IPv4 statistics */
9728 static mblk_t *
9729 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9730     boolean_t legacy_req)
9731 {
9732 	struct opthdr		*optp;
9733 	mblk_t			*mp2ctl;
9734 	ill_t			*ill;
9735 	ill_walk_context_t	ctx;
9736 	mblk_t			*mp_tail = NULL;
9737 	mib2_ipIfStatsEntry_t	global_ip_mib;
9738 	mib2_ipAddrEntry_t	mae;
9739 
9740 	/*
9741 	 * Make a copy of the original message
9742 	 */
9743 	mp2ctl = copymsg(mpctl);
9744 
9745 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9746 	optp->level = MIB2_IP;
9747 	optp->name = MIB2_IP_TRAFFIC_STATS;
9748 	/* Include "unknown interface" ip_mib */
9749 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9750 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9751 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9752 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9753 	    (ipst->ips_ip_forwarding ? 1 : 2));
9754 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9755 	    (uint32_t)ipst->ips_ip_def_ttl);
9756 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9757 	    sizeof (mib2_ipIfStatsEntry_t));
9758 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9759 	    sizeof (mib2_ipAddrEntry_t));
9760 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9761 	    sizeof (mib2_ipRouteEntry_t));
9762 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9763 	    sizeof (mib2_ipNetToMediaEntry_t));
9764 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9765 	    sizeof (ip_member_t));
9766 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9767 	    sizeof (ip_grpsrc_t));
9768 
9769 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9770 
9771 	if (legacy_req) {
9772 		SET_MIB(global_ip_mib.ipIfStatsAddrEntrySize,
9773 		    LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t));
9774 	}
9775 
9776 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9777 	    (char *)&global_ip_mib, (int)sizeof (global_ip_mib))) {
9778 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9779 		    "failed to allocate %u bytes\n",
9780 		    (uint_t)sizeof (global_ip_mib)));
9781 	}
9782 
9783 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9784 	ill = ILL_START_WALK_V4(&ctx, ipst);
9785 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9786 		ill->ill_ip_mib->ipIfStatsIfIndex =
9787 		    ill->ill_phyint->phyint_ifindex;
9788 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9789 		    (ipst->ips_ip_forwarding ? 1 : 2));
9790 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9791 		    (uint32_t)ipst->ips_ip_def_ttl);
9792 
9793 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9794 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9795 		    (char *)ill->ill_ip_mib,
9796 		    (int)sizeof (*ill->ill_ip_mib))) {
9797 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9798 			    "failed to allocate %u bytes\n",
9799 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9800 		}
9801 	}
9802 	rw_exit(&ipst->ips_ill_g_lock);
9803 
9804 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9805 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9806 	    "level %d, name %d, len %d\n",
9807 	    (int)optp->level, (int)optp->name, (int)optp->len));
9808 	qreply(q, mpctl);
9809 
9810 	if (mp2ctl == NULL)
9811 		return (NULL);
9812 
9813 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst,
9814 	    legacy_req));
9815 }
9816 
9817 /* Global IPv4 ICMP statistics */
9818 static mblk_t *
9819 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9820 {
9821 	struct opthdr		*optp;
9822 	mblk_t			*mp2ctl;
9823 
9824 	/*
9825 	 * Make a copy of the original message
9826 	 */
9827 	mp2ctl = copymsg(mpctl);
9828 
9829 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9830 	optp->level = MIB2_ICMP;
9831 	optp->name = 0;
9832 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9833 	    (int)sizeof (ipst->ips_icmp_mib))) {
9834 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9835 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9836 	}
9837 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9838 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9839 	    (int)optp->level, (int)optp->name, (int)optp->len));
9840 	qreply(q, mpctl);
9841 	return (mp2ctl);
9842 }
9843 
9844 /* Global IPv4 IGMP statistics */
9845 static mblk_t *
9846 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9847 {
9848 	struct opthdr		*optp;
9849 	mblk_t			*mp2ctl;
9850 
9851 	/*
9852 	 * make a copy of the original message
9853 	 */
9854 	mp2ctl = copymsg(mpctl);
9855 
9856 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9857 	optp->level = EXPER_IGMP;
9858 	optp->name = 0;
9859 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9860 	    (int)sizeof (ipst->ips_igmpstat))) {
9861 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9862 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9863 	}
9864 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9865 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9866 	    (int)optp->level, (int)optp->name, (int)optp->len));
9867 	qreply(q, mpctl);
9868 	return (mp2ctl);
9869 }
9870 
9871 /* Global IPv4 Multicast Routing statistics */
9872 static mblk_t *
9873 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9874 {
9875 	struct opthdr		*optp;
9876 	mblk_t			*mp2ctl;
9877 
9878 	/*
9879 	 * make a copy of the original message
9880 	 */
9881 	mp2ctl = copymsg(mpctl);
9882 
9883 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9884 	optp->level = EXPER_DVMRP;
9885 	optp->name = 0;
9886 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9887 		ip0dbg(("ip_mroute_stats: failed\n"));
9888 	}
9889 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9890 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9891 	    (int)optp->level, (int)optp->name, (int)optp->len));
9892 	qreply(q, mpctl);
9893 	return (mp2ctl);
9894 }
9895 
9896 /* IPv4 address information */
9897 static mblk_t *
9898 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9899     boolean_t legacy_req)
9900 {
9901 	struct opthdr		*optp;
9902 	mblk_t			*mp2ctl;
9903 	mblk_t			*mp_tail = NULL;
9904 	ill_t			*ill;
9905 	ipif_t			*ipif;
9906 	uint_t			bitval;
9907 	mib2_ipAddrEntry_t	mae;
9908 	size_t			mae_size;
9909 	zoneid_t		zoneid;
9910 	ill_walk_context_t	ctx;
9911 
9912 	/*
9913 	 * make a copy of the original message
9914 	 */
9915 	mp2ctl = copymsg(mpctl);
9916 
9917 	mae_size = (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9918 	    sizeof (mib2_ipAddrEntry_t);
9919 
9920 	/* ipAddrEntryTable */
9921 
9922 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9923 	optp->level = MIB2_IP;
9924 	optp->name = MIB2_IP_ADDR;
9925 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9926 
9927 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9928 	ill = ILL_START_WALK_V4(&ctx, ipst);
9929 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9930 		for (ipif = ill->ill_ipif; ipif != NULL;
9931 		    ipif = ipif->ipif_next) {
9932 			if (ipif->ipif_zoneid != zoneid &&
9933 			    ipif->ipif_zoneid != ALL_ZONES)
9934 				continue;
9935 			/* Sum of count from dead IRE_LO* and our current */
9936 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9937 			if (ipif->ipif_ire_local != NULL) {
9938 				mae.ipAdEntInfo.ae_ibcnt +=
9939 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9940 			}
9941 			mae.ipAdEntInfo.ae_obcnt = 0;
9942 			mae.ipAdEntInfo.ae_focnt = 0;
9943 
9944 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
9945 			    OCTET_LENGTH);
9946 			mae.ipAdEntIfIndex.o_length =
9947 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
9948 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
9949 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
9950 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
9951 			mae.ipAdEntInfo.ae_subnet_len =
9952 			    ip_mask_to_plen(ipif->ipif_net_mask);
9953 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
9954 			for (bitval = 1;
9955 			    bitval &&
9956 			    !(bitval & ipif->ipif_brd_addr);
9957 			    bitval <<= 1)
9958 				noop;
9959 			mae.ipAdEntBcastAddr = bitval;
9960 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
9961 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
9962 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
9963 			mae.ipAdEntInfo.ae_broadcast_addr =
9964 			    ipif->ipif_brd_addr;
9965 			mae.ipAdEntInfo.ae_pp_dst_addr =
9966 			    ipif->ipif_pp_dst_addr;
9967 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
9968 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
9969 			mae.ipAdEntRetransmitTime =
9970 			    ill->ill_reachable_retrans_time;
9971 
9972 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9973 			    (char *)&mae, (int)mae_size)) {
9974 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
9975 				    "allocate %u bytes\n", (uint_t)mae_size));
9976 			}
9977 		}
9978 	}
9979 	rw_exit(&ipst->ips_ill_g_lock);
9980 
9981 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9982 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
9983 	    (int)optp->level, (int)optp->name, (int)optp->len));
9984 	qreply(q, mpctl);
9985 	return (mp2ctl);
9986 }
9987 
9988 /* IPv6 address information */
9989 static mblk_t *
9990 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9991     boolean_t legacy_req)
9992 {
9993 	struct opthdr		*optp;
9994 	mblk_t			*mp2ctl;
9995 	mblk_t			*mp_tail = NULL;
9996 	ill_t			*ill;
9997 	ipif_t			*ipif;
9998 	mib2_ipv6AddrEntry_t	mae6;
9999 	size_t			mae6_size;
10000 	zoneid_t		zoneid;
10001 	ill_walk_context_t	ctx;
10002 
10003 	/*
10004 	 * make a copy of the original message
10005 	 */
10006 	mp2ctl = copymsg(mpctl);
10007 
10008 	mae6_size = (legacy_req) ?
10009 	    LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t) :
10010 	    sizeof (mib2_ipv6AddrEntry_t);
10011 
10012 	/* ipv6AddrEntryTable */
10013 
10014 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10015 	optp->level = MIB2_IP6;
10016 	optp->name = MIB2_IP6_ADDR;
10017 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10018 
10019 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10020 	ill = ILL_START_WALK_V6(&ctx, ipst);
10021 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10022 		for (ipif = ill->ill_ipif; ipif != NULL;
10023 		    ipif = ipif->ipif_next) {
10024 			if (ipif->ipif_zoneid != zoneid &&
10025 			    ipif->ipif_zoneid != ALL_ZONES)
10026 				continue;
10027 			/* Sum of count from dead IRE_LO* and our current */
10028 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10029 			if (ipif->ipif_ire_local != NULL) {
10030 				mae6.ipv6AddrInfo.ae_ibcnt +=
10031 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10032 			}
10033 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10034 			mae6.ipv6AddrInfo.ae_focnt = 0;
10035 
10036 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10037 			    OCTET_LENGTH);
10038 			mae6.ipv6AddrIfIndex.o_length =
10039 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10040 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10041 			mae6.ipv6AddrPfxLength =
10042 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10043 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10044 			mae6.ipv6AddrInfo.ae_subnet_len =
10045 			    mae6.ipv6AddrPfxLength;
10046 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10047 
10048 			/* Type: stateless(1), stateful(2), unknown(3) */
10049 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10050 				mae6.ipv6AddrType = 1;
10051 			else
10052 				mae6.ipv6AddrType = 2;
10053 			/* Anycast: true(1), false(2) */
10054 			if (ipif->ipif_flags & IPIF_ANYCAST)
10055 				mae6.ipv6AddrAnycastFlag = 1;
10056 			else
10057 				mae6.ipv6AddrAnycastFlag = 2;
10058 
10059 			/*
10060 			 * Address status: preferred(1), deprecated(2),
10061 			 * invalid(3), inaccessible(4), unknown(5)
10062 			 */
10063 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10064 				mae6.ipv6AddrStatus = 3;
10065 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10066 				mae6.ipv6AddrStatus = 2;
10067 			else
10068 				mae6.ipv6AddrStatus = 1;
10069 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10070 			mae6.ipv6AddrInfo.ae_metric  =
10071 			    ipif->ipif_ill->ill_metric;
10072 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10073 			    ipif->ipif_v6pp_dst_addr;
10074 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10075 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10076 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10077 			mae6.ipv6AddrIdentifier = ill->ill_token;
10078 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10079 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10080 			mae6.ipv6AddrRetransmitTime =
10081 			    ill->ill_reachable_retrans_time;
10082 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10083 			    (char *)&mae6, (int)mae6_size)) {
10084 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10085 				    "allocate %u bytes\n",
10086 				    (uint_t)mae6_size));
10087 			}
10088 		}
10089 	}
10090 	rw_exit(&ipst->ips_ill_g_lock);
10091 
10092 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10093 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10094 	    (int)optp->level, (int)optp->name, (int)optp->len));
10095 	qreply(q, mpctl);
10096 	return (mp2ctl);
10097 }
10098 
10099 /* IPv4 multicast group membership. */
10100 static mblk_t *
10101 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10102 {
10103 	struct opthdr		*optp;
10104 	mblk_t			*mp2ctl;
10105 	ill_t			*ill;
10106 	ipif_t			*ipif;
10107 	ilm_t			*ilm;
10108 	ip_member_t		ipm;
10109 	mblk_t			*mp_tail = NULL;
10110 	ill_walk_context_t	ctx;
10111 	zoneid_t		zoneid;
10112 
10113 	/*
10114 	 * make a copy of the original message
10115 	 */
10116 	mp2ctl = copymsg(mpctl);
10117 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10118 
10119 	/* ipGroupMember table */
10120 	optp = (struct opthdr *)&mpctl->b_rptr[
10121 	    sizeof (struct T_optmgmt_ack)];
10122 	optp->level = MIB2_IP;
10123 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10124 
10125 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10126 	ill = ILL_START_WALK_V4(&ctx, ipst);
10127 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10128 		/* Make sure the ill isn't going away. */
10129 		if (!ill_check_and_refhold(ill))
10130 			continue;
10131 		rw_exit(&ipst->ips_ill_g_lock);
10132 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10133 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10134 			if (ilm->ilm_zoneid != zoneid &&
10135 			    ilm->ilm_zoneid != ALL_ZONES)
10136 				continue;
10137 
10138 			/* Is there an ipif for ilm_ifaddr? */
10139 			for (ipif = ill->ill_ipif; ipif != NULL;
10140 			    ipif = ipif->ipif_next) {
10141 				if (!IPIF_IS_CONDEMNED(ipif) &&
10142 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10143 				    ilm->ilm_ifaddr != INADDR_ANY)
10144 					break;
10145 			}
10146 			if (ipif != NULL) {
10147 				ipif_get_name(ipif,
10148 				    ipm.ipGroupMemberIfIndex.o_bytes,
10149 				    OCTET_LENGTH);
10150 			} else {
10151 				ill_get_name(ill,
10152 				    ipm.ipGroupMemberIfIndex.o_bytes,
10153 				    OCTET_LENGTH);
10154 			}
10155 			ipm.ipGroupMemberIfIndex.o_length =
10156 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10157 
10158 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10159 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10160 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10161 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10162 			    (char *)&ipm, (int)sizeof (ipm))) {
10163 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10164 				    "failed to allocate %u bytes\n",
10165 				    (uint_t)sizeof (ipm)));
10166 			}
10167 		}
10168 		rw_exit(&ill->ill_mcast_lock);
10169 		ill_refrele(ill);
10170 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10171 	}
10172 	rw_exit(&ipst->ips_ill_g_lock);
10173 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10174 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10175 	    (int)optp->level, (int)optp->name, (int)optp->len));
10176 	qreply(q, mpctl);
10177 	return (mp2ctl);
10178 }
10179 
10180 /* IPv6 multicast group membership. */
10181 static mblk_t *
10182 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10183 {
10184 	struct opthdr		*optp;
10185 	mblk_t			*mp2ctl;
10186 	ill_t			*ill;
10187 	ilm_t			*ilm;
10188 	ipv6_member_t		ipm6;
10189 	mblk_t			*mp_tail = NULL;
10190 	ill_walk_context_t	ctx;
10191 	zoneid_t		zoneid;
10192 
10193 	/*
10194 	 * make a copy of the original message
10195 	 */
10196 	mp2ctl = copymsg(mpctl);
10197 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10198 
10199 	/* ip6GroupMember table */
10200 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10201 	optp->level = MIB2_IP6;
10202 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10203 
10204 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10205 	ill = ILL_START_WALK_V6(&ctx, ipst);
10206 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10207 		/* Make sure the ill isn't going away. */
10208 		if (!ill_check_and_refhold(ill))
10209 			continue;
10210 		rw_exit(&ipst->ips_ill_g_lock);
10211 		/*
10212 		 * Normally we don't have any members on under IPMP interfaces.
10213 		 * We report them as a debugging aid.
10214 		 */
10215 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10216 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10217 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10218 			if (ilm->ilm_zoneid != zoneid &&
10219 			    ilm->ilm_zoneid != ALL_ZONES)
10220 				continue;	/* not this zone */
10221 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10222 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10223 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10224 			if (!snmp_append_data2(mpctl->b_cont,
10225 			    &mp_tail,
10226 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10227 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10228 				    "failed to allocate %u bytes\n",
10229 				    (uint_t)sizeof (ipm6)));
10230 			}
10231 		}
10232 		rw_exit(&ill->ill_mcast_lock);
10233 		ill_refrele(ill);
10234 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10235 	}
10236 	rw_exit(&ipst->ips_ill_g_lock);
10237 
10238 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10239 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10240 	    (int)optp->level, (int)optp->name, (int)optp->len));
10241 	qreply(q, mpctl);
10242 	return (mp2ctl);
10243 }
10244 
10245 /* IP multicast filtered sources */
10246 static mblk_t *
10247 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10248 {
10249 	struct opthdr		*optp;
10250 	mblk_t			*mp2ctl;
10251 	ill_t			*ill;
10252 	ipif_t			*ipif;
10253 	ilm_t			*ilm;
10254 	ip_grpsrc_t		ips;
10255 	mblk_t			*mp_tail = NULL;
10256 	ill_walk_context_t	ctx;
10257 	zoneid_t		zoneid;
10258 	int			i;
10259 	slist_t			*sl;
10260 
10261 	/*
10262 	 * make a copy of the original message
10263 	 */
10264 	mp2ctl = copymsg(mpctl);
10265 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10266 
10267 	/* ipGroupSource table */
10268 	optp = (struct opthdr *)&mpctl->b_rptr[
10269 	    sizeof (struct T_optmgmt_ack)];
10270 	optp->level = MIB2_IP;
10271 	optp->name = EXPER_IP_GROUP_SOURCES;
10272 
10273 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10274 	ill = ILL_START_WALK_V4(&ctx, ipst);
10275 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10276 		/* Make sure the ill isn't going away. */
10277 		if (!ill_check_and_refhold(ill))
10278 			continue;
10279 		rw_exit(&ipst->ips_ill_g_lock);
10280 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10281 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10282 			sl = ilm->ilm_filter;
10283 			if (ilm->ilm_zoneid != zoneid &&
10284 			    ilm->ilm_zoneid != ALL_ZONES)
10285 				continue;
10286 			if (SLIST_IS_EMPTY(sl))
10287 				continue;
10288 
10289 			/* Is there an ipif for ilm_ifaddr? */
10290 			for (ipif = ill->ill_ipif; ipif != NULL;
10291 			    ipif = ipif->ipif_next) {
10292 				if (!IPIF_IS_CONDEMNED(ipif) &&
10293 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10294 				    ilm->ilm_ifaddr != INADDR_ANY)
10295 					break;
10296 			}
10297 			if (ipif != NULL) {
10298 				ipif_get_name(ipif,
10299 				    ips.ipGroupSourceIfIndex.o_bytes,
10300 				    OCTET_LENGTH);
10301 			} else {
10302 				ill_get_name(ill,
10303 				    ips.ipGroupSourceIfIndex.o_bytes,
10304 				    OCTET_LENGTH);
10305 			}
10306 			ips.ipGroupSourceIfIndex.o_length =
10307 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10308 
10309 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10310 			for (i = 0; i < sl->sl_numsrc; i++) {
10311 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10312 					continue;
10313 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10314 				    ips.ipGroupSourceAddress);
10315 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10316 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10317 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10318 					    " failed to allocate %u bytes\n",
10319 					    (uint_t)sizeof (ips)));
10320 				}
10321 			}
10322 		}
10323 		rw_exit(&ill->ill_mcast_lock);
10324 		ill_refrele(ill);
10325 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10326 	}
10327 	rw_exit(&ipst->ips_ill_g_lock);
10328 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10329 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10330 	    (int)optp->level, (int)optp->name, (int)optp->len));
10331 	qreply(q, mpctl);
10332 	return (mp2ctl);
10333 }
10334 
10335 /* IPv6 multicast filtered sources. */
10336 static mblk_t *
10337 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10338 {
10339 	struct opthdr		*optp;
10340 	mblk_t			*mp2ctl;
10341 	ill_t			*ill;
10342 	ilm_t			*ilm;
10343 	ipv6_grpsrc_t		ips6;
10344 	mblk_t			*mp_tail = NULL;
10345 	ill_walk_context_t	ctx;
10346 	zoneid_t		zoneid;
10347 	int			i;
10348 	slist_t			*sl;
10349 
10350 	/*
10351 	 * make a copy of the original message
10352 	 */
10353 	mp2ctl = copymsg(mpctl);
10354 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10355 
10356 	/* ip6GroupMember table */
10357 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10358 	optp->level = MIB2_IP6;
10359 	optp->name = EXPER_IP6_GROUP_SOURCES;
10360 
10361 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10362 	ill = ILL_START_WALK_V6(&ctx, ipst);
10363 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10364 		/* Make sure the ill isn't going away. */
10365 		if (!ill_check_and_refhold(ill))
10366 			continue;
10367 		rw_exit(&ipst->ips_ill_g_lock);
10368 		/*
10369 		 * Normally we don't have any members on under IPMP interfaces.
10370 		 * We report them as a debugging aid.
10371 		 */
10372 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10373 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10374 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10375 			sl = ilm->ilm_filter;
10376 			if (ilm->ilm_zoneid != zoneid &&
10377 			    ilm->ilm_zoneid != ALL_ZONES)
10378 				continue;
10379 			if (SLIST_IS_EMPTY(sl))
10380 				continue;
10381 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10382 			for (i = 0; i < sl->sl_numsrc; i++) {
10383 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10384 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10385 				    (char *)&ips6, (int)sizeof (ips6))) {
10386 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10387 					    "group_src: failed to allocate "
10388 					    "%u bytes\n",
10389 					    (uint_t)sizeof (ips6)));
10390 				}
10391 			}
10392 		}
10393 		rw_exit(&ill->ill_mcast_lock);
10394 		ill_refrele(ill);
10395 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10396 	}
10397 	rw_exit(&ipst->ips_ill_g_lock);
10398 
10399 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10400 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10401 	    (int)optp->level, (int)optp->name, (int)optp->len));
10402 	qreply(q, mpctl);
10403 	return (mp2ctl);
10404 }
10405 
10406 /* Multicast routing virtual interface table. */
10407 static mblk_t *
10408 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10409 {
10410 	struct opthdr		*optp;
10411 	mblk_t			*mp2ctl;
10412 
10413 	/*
10414 	 * make a copy of the original message
10415 	 */
10416 	mp2ctl = copymsg(mpctl);
10417 
10418 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10419 	optp->level = EXPER_DVMRP;
10420 	optp->name = EXPER_DVMRP_VIF;
10421 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10422 		ip0dbg(("ip_mroute_vif: failed\n"));
10423 	}
10424 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10425 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10426 	    (int)optp->level, (int)optp->name, (int)optp->len));
10427 	qreply(q, mpctl);
10428 	return (mp2ctl);
10429 }
10430 
10431 /* Multicast routing table. */
10432 static mblk_t *
10433 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10434 {
10435 	struct opthdr		*optp;
10436 	mblk_t			*mp2ctl;
10437 
10438 	/*
10439 	 * make a copy of the original message
10440 	 */
10441 	mp2ctl = copymsg(mpctl);
10442 
10443 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10444 	optp->level = EXPER_DVMRP;
10445 	optp->name = EXPER_DVMRP_MRT;
10446 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10447 		ip0dbg(("ip_mroute_mrt: failed\n"));
10448 	}
10449 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10450 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10451 	    (int)optp->level, (int)optp->name, (int)optp->len));
10452 	qreply(q, mpctl);
10453 	return (mp2ctl);
10454 }
10455 
10456 /*
10457  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10458  * in one IRE walk.
10459  */
10460 static mblk_t *
10461 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10462     ip_stack_t *ipst)
10463 {
10464 	struct opthdr	*optp;
10465 	mblk_t		*mp2ctl;	/* Returned */
10466 	mblk_t		*mp3ctl;	/* nettomedia */
10467 	mblk_t		*mp4ctl;	/* routeattrs */
10468 	iproutedata_t	ird;
10469 	zoneid_t	zoneid;
10470 
10471 	/*
10472 	 * make copies of the original message
10473 	 *	- mp2ctl is returned unchanged to the caller for his use
10474 	 *	- mpctl is sent upstream as ipRouteEntryTable
10475 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10476 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10477 	 */
10478 	mp2ctl = copymsg(mpctl);
10479 	mp3ctl = copymsg(mpctl);
10480 	mp4ctl = copymsg(mpctl);
10481 	if (mp3ctl == NULL || mp4ctl == NULL) {
10482 		freemsg(mp4ctl);
10483 		freemsg(mp3ctl);
10484 		freemsg(mp2ctl);
10485 		freemsg(mpctl);
10486 		return (NULL);
10487 	}
10488 
10489 	bzero(&ird, sizeof (ird));
10490 
10491 	ird.ird_route.lp_head = mpctl->b_cont;
10492 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10493 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10494 	/*
10495 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10496 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10497 	 * intended a temporary solution until a proper MIB API is provided
10498 	 * that provides complete filtering/caller-opt-in.
10499 	 */
10500 	if (level == EXPER_IP_AND_ALL_IRES)
10501 		ird.ird_flags |= IRD_REPORT_ALL;
10502 
10503 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10504 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10505 
10506 	/* ipRouteEntryTable in mpctl */
10507 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10508 	optp->level = MIB2_IP;
10509 	optp->name = MIB2_IP_ROUTE;
10510 	optp->len = msgdsize(ird.ird_route.lp_head);
10511 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10512 	    (int)optp->level, (int)optp->name, (int)optp->len));
10513 	qreply(q, mpctl);
10514 
10515 	/* ipNetToMediaEntryTable in mp3ctl */
10516 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10517 
10518 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10519 	optp->level = MIB2_IP;
10520 	optp->name = MIB2_IP_MEDIA;
10521 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10522 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10523 	    (int)optp->level, (int)optp->name, (int)optp->len));
10524 	qreply(q, mp3ctl);
10525 
10526 	/* ipRouteAttributeTable in mp4ctl */
10527 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10528 	optp->level = MIB2_IP;
10529 	optp->name = EXPER_IP_RTATTR;
10530 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10531 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10532 	    (int)optp->level, (int)optp->name, (int)optp->len));
10533 	if (optp->len == 0)
10534 		freemsg(mp4ctl);
10535 	else
10536 		qreply(q, mp4ctl);
10537 
10538 	return (mp2ctl);
10539 }
10540 
10541 /*
10542  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10543  * ipv6NetToMediaEntryTable in an NDP walk.
10544  */
10545 static mblk_t *
10546 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10547     ip_stack_t *ipst)
10548 {
10549 	struct opthdr	*optp;
10550 	mblk_t		*mp2ctl;	/* Returned */
10551 	mblk_t		*mp3ctl;	/* nettomedia */
10552 	mblk_t		*mp4ctl;	/* routeattrs */
10553 	iproutedata_t	ird;
10554 	zoneid_t	zoneid;
10555 
10556 	/*
10557 	 * make copies of the original message
10558 	 *	- mp2ctl is returned unchanged to the caller for his use
10559 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10560 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10561 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10562 	 */
10563 	mp2ctl = copymsg(mpctl);
10564 	mp3ctl = copymsg(mpctl);
10565 	mp4ctl = copymsg(mpctl);
10566 	if (mp3ctl == NULL || mp4ctl == NULL) {
10567 		freemsg(mp4ctl);
10568 		freemsg(mp3ctl);
10569 		freemsg(mp2ctl);
10570 		freemsg(mpctl);
10571 		return (NULL);
10572 	}
10573 
10574 	bzero(&ird, sizeof (ird));
10575 
10576 	ird.ird_route.lp_head = mpctl->b_cont;
10577 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10578 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10579 	/*
10580 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10581 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10582 	 * intended a temporary solution until a proper MIB API is provided
10583 	 * that provides complete filtering/caller-opt-in.
10584 	 */
10585 	if (level == EXPER_IP_AND_ALL_IRES)
10586 		ird.ird_flags |= IRD_REPORT_ALL;
10587 
10588 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10589 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10590 
10591 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10592 	optp->level = MIB2_IP6;
10593 	optp->name = MIB2_IP6_ROUTE;
10594 	optp->len = msgdsize(ird.ird_route.lp_head);
10595 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10596 	    (int)optp->level, (int)optp->name, (int)optp->len));
10597 	qreply(q, mpctl);
10598 
10599 	/* ipv6NetToMediaEntryTable in mp3ctl */
10600 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10601 
10602 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10603 	optp->level = MIB2_IP6;
10604 	optp->name = MIB2_IP6_MEDIA;
10605 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10606 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10607 	    (int)optp->level, (int)optp->name, (int)optp->len));
10608 	qreply(q, mp3ctl);
10609 
10610 	/* ipv6RouteAttributeTable in mp4ctl */
10611 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10612 	optp->level = MIB2_IP6;
10613 	optp->name = EXPER_IP_RTATTR;
10614 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10615 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10616 	    (int)optp->level, (int)optp->name, (int)optp->len));
10617 	if (optp->len == 0)
10618 		freemsg(mp4ctl);
10619 	else
10620 		qreply(q, mp4ctl);
10621 
10622 	return (mp2ctl);
10623 }
10624 
10625 /*
10626  * IPv6 mib: One per ill
10627  */
10628 static mblk_t *
10629 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10630     boolean_t legacy_req)
10631 {
10632 	struct opthdr		*optp;
10633 	mblk_t			*mp2ctl;
10634 	ill_t			*ill;
10635 	ill_walk_context_t	ctx;
10636 	mblk_t			*mp_tail = NULL;
10637 	mib2_ipv6AddrEntry_t	mae6;
10638 	mib2_ipIfStatsEntry_t	*ise;
10639 	size_t			ise_size, iae_size;
10640 
10641 	/*
10642 	 * Make a copy of the original message
10643 	 */
10644 	mp2ctl = copymsg(mpctl);
10645 
10646 	/* fixed length IPv6 structure ... */
10647 
10648 	if (legacy_req) {
10649 		ise_size = LEGACY_MIB_SIZE(&ipst->ips_ip6_mib,
10650 		    mib2_ipIfStatsEntry_t);
10651 		iae_size = LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t);
10652 	} else {
10653 		ise_size = sizeof (mib2_ipIfStatsEntry_t);
10654 		iae_size = sizeof (mib2_ipv6AddrEntry_t);
10655 	}
10656 
10657 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10658 	optp->level = MIB2_IP6;
10659 	optp->name = 0;
10660 	/* Include "unknown interface" ip6_mib */
10661 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10662 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10663 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10664 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10665 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10666 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10667 	    ipst->ips_ipv6_def_hops);
10668 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10669 	    sizeof (mib2_ipIfStatsEntry_t));
10670 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10671 	    sizeof (mib2_ipv6AddrEntry_t));
10672 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10673 	    sizeof (mib2_ipv6RouteEntry_t));
10674 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10675 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10676 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10677 	    sizeof (ipv6_member_t));
10678 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10679 	    sizeof (ipv6_grpsrc_t));
10680 
10681 	/*
10682 	 * Synchronize 64- and 32-bit counters
10683 	 */
10684 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10685 	    ipIfStatsHCInReceives);
10686 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10687 	    ipIfStatsHCInDelivers);
10688 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10689 	    ipIfStatsHCOutRequests);
10690 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10691 	    ipIfStatsHCOutForwDatagrams);
10692 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10693 	    ipIfStatsHCOutMcastPkts);
10694 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10695 	    ipIfStatsHCInMcastPkts);
10696 
10697 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10698 	    (char *)&ipst->ips_ip6_mib, (int)ise_size)) {
10699 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10700 		    (uint_t)ise_size));
10701 	} else if (legacy_req) {
10702 		/* Adjust the EntrySize fields for legacy requests. */
10703 		ise =
10704 		    (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr - (int)ise_size);
10705 		SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10706 		SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10707 	}
10708 
10709 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10710 	ill = ILL_START_WALK_V6(&ctx, ipst);
10711 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10712 		ill->ill_ip_mib->ipIfStatsIfIndex =
10713 		    ill->ill_phyint->phyint_ifindex;
10714 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10715 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10716 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10717 		    ill->ill_max_hops);
10718 
10719 		/*
10720 		 * Synchronize 64- and 32-bit counters
10721 		 */
10722 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10723 		    ipIfStatsHCInReceives);
10724 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10725 		    ipIfStatsHCInDelivers);
10726 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10727 		    ipIfStatsHCOutRequests);
10728 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10729 		    ipIfStatsHCOutForwDatagrams);
10730 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10731 		    ipIfStatsHCOutMcastPkts);
10732 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10733 		    ipIfStatsHCInMcastPkts);
10734 
10735 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10736 		    (char *)ill->ill_ip_mib, (int)ise_size)) {
10737 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10738 			"%u bytes\n", (uint_t)ise_size));
10739 		} else if (legacy_req) {
10740 			/* Adjust the EntrySize fields for legacy requests. */
10741 			ise = (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr -
10742 			    (int)ise_size);
10743 			SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10744 			SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10745 		}
10746 	}
10747 	rw_exit(&ipst->ips_ill_g_lock);
10748 
10749 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10750 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10751 	    (int)optp->level, (int)optp->name, (int)optp->len));
10752 	qreply(q, mpctl);
10753 	return (mp2ctl);
10754 }
10755 
10756 /*
10757  * ICMPv6 mib: One per ill
10758  */
10759 static mblk_t *
10760 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10761 {
10762 	struct opthdr		*optp;
10763 	mblk_t			*mp2ctl;
10764 	ill_t			*ill;
10765 	ill_walk_context_t	ctx;
10766 	mblk_t			*mp_tail = NULL;
10767 	/*
10768 	 * Make a copy of the original message
10769 	 */
10770 	mp2ctl = copymsg(mpctl);
10771 
10772 	/* fixed length ICMPv6 structure ... */
10773 
10774 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10775 	optp->level = MIB2_ICMP6;
10776 	optp->name = 0;
10777 	/* Include "unknown interface" icmp6_mib */
10778 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10779 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10780 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10781 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10782 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10783 	    (char *)&ipst->ips_icmp6_mib,
10784 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10785 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10786 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10787 	}
10788 
10789 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10790 	ill = ILL_START_WALK_V6(&ctx, ipst);
10791 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10792 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10793 		    ill->ill_phyint->phyint_ifindex;
10794 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10795 		    (char *)ill->ill_icmp6_mib,
10796 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10797 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10798 			    "%u bytes\n",
10799 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10800 		}
10801 	}
10802 	rw_exit(&ipst->ips_ill_g_lock);
10803 
10804 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10805 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10806 	    (int)optp->level, (int)optp->name, (int)optp->len));
10807 	qreply(q, mpctl);
10808 	return (mp2ctl);
10809 }
10810 
10811 /*
10812  * ire_walk routine to create both ipRouteEntryTable and
10813  * ipRouteAttributeTable in one IRE walk
10814  */
10815 static void
10816 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10817 {
10818 	ill_t				*ill;
10819 	mib2_ipRouteEntry_t		*re;
10820 	mib2_ipAttributeEntry_t		iaes;
10821 	tsol_ire_gw_secattr_t		*attrp;
10822 	tsol_gc_t			*gc = NULL;
10823 	tsol_gcgrp_t			*gcgrp = NULL;
10824 	ip_stack_t			*ipst = ire->ire_ipst;
10825 
10826 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10827 
10828 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10829 		if (ire->ire_testhidden)
10830 			return;
10831 		if (ire->ire_type & IRE_IF_CLONE)
10832 			return;
10833 	}
10834 
10835 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10836 		return;
10837 
10838 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10839 		mutex_enter(&attrp->igsa_lock);
10840 		if ((gc = attrp->igsa_gc) != NULL) {
10841 			gcgrp = gc->gc_grp;
10842 			ASSERT(gcgrp != NULL);
10843 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10844 		}
10845 		mutex_exit(&attrp->igsa_lock);
10846 	}
10847 	/*
10848 	 * Return all IRE types for route table... let caller pick and choose
10849 	 */
10850 	re->ipRouteDest = ire->ire_addr;
10851 	ill = ire->ire_ill;
10852 	re->ipRouteIfIndex.o_length = 0;
10853 	if (ill != NULL) {
10854 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10855 		re->ipRouteIfIndex.o_length =
10856 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10857 	}
10858 	re->ipRouteMetric1 = -1;
10859 	re->ipRouteMetric2 = -1;
10860 	re->ipRouteMetric3 = -1;
10861 	re->ipRouteMetric4 = -1;
10862 
10863 	re->ipRouteNextHop = ire->ire_gateway_addr;
10864 	/* indirect(4), direct(3), or invalid(2) */
10865 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10866 		re->ipRouteType = 2;
10867 	else if (ire->ire_type & IRE_ONLINK)
10868 		re->ipRouteType = 3;
10869 	else
10870 		re->ipRouteType = 4;
10871 
10872 	re->ipRouteProto = -1;
10873 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10874 	re->ipRouteMask = ire->ire_mask;
10875 	re->ipRouteMetric5 = -1;
10876 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10877 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10878 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10879 
10880 	re->ipRouteInfo.re_frag_flag	= 0;
10881 	re->ipRouteInfo.re_rtt		= 0;
10882 	re->ipRouteInfo.re_src_addr	= 0;
10883 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
10884 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10885 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10886 	re->ipRouteInfo.re_flags	= ire->ire_flags;
10887 
10888 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10889 	if (ire->ire_type & IRE_INTERFACE) {
10890 		ire_t *child;
10891 
10892 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10893 		child = ire->ire_dep_children;
10894 		while (child != NULL) {
10895 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10896 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10897 			child = child->ire_dep_sib_next;
10898 		}
10899 		rw_exit(&ipst->ips_ire_dep_lock);
10900 	}
10901 
10902 	if (ire->ire_flags & RTF_DYNAMIC) {
10903 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10904 	} else {
10905 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
10906 	}
10907 
10908 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10909 	    (char *)re, (int)sizeof (*re))) {
10910 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
10911 		    (uint_t)sizeof (*re)));
10912 	}
10913 
10914 	if (gc != NULL) {
10915 		iaes.iae_routeidx = ird->ird_idx;
10916 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10917 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10918 
10919 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10920 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10921 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
10922 			    "bytes\n", (uint_t)sizeof (iaes)));
10923 		}
10924 	}
10925 
10926 	/* bump route index for next pass */
10927 	ird->ird_idx++;
10928 
10929 	kmem_free(re, sizeof (*re));
10930 	if (gcgrp != NULL)
10931 		rw_exit(&gcgrp->gcgrp_rwlock);
10932 }
10933 
10934 /*
10935  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
10936  */
10937 static void
10938 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
10939 {
10940 	ill_t				*ill;
10941 	mib2_ipv6RouteEntry_t		*re;
10942 	mib2_ipAttributeEntry_t		iaes;
10943 	tsol_ire_gw_secattr_t		*attrp;
10944 	tsol_gc_t			*gc = NULL;
10945 	tsol_gcgrp_t			*gcgrp = NULL;
10946 	ip_stack_t			*ipst = ire->ire_ipst;
10947 
10948 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
10949 
10950 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10951 		if (ire->ire_testhidden)
10952 			return;
10953 		if (ire->ire_type & IRE_IF_CLONE)
10954 			return;
10955 	}
10956 
10957 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10958 		return;
10959 
10960 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10961 		mutex_enter(&attrp->igsa_lock);
10962 		if ((gc = attrp->igsa_gc) != NULL) {
10963 			gcgrp = gc->gc_grp;
10964 			ASSERT(gcgrp != NULL);
10965 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10966 		}
10967 		mutex_exit(&attrp->igsa_lock);
10968 	}
10969 	/*
10970 	 * Return all IRE types for route table... let caller pick and choose
10971 	 */
10972 	re->ipv6RouteDest = ire->ire_addr_v6;
10973 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
10974 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
10975 	re->ipv6RouteIfIndex.o_length = 0;
10976 	ill = ire->ire_ill;
10977 	if (ill != NULL) {
10978 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
10979 		re->ipv6RouteIfIndex.o_length =
10980 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
10981 	}
10982 
10983 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
10984 
10985 	mutex_enter(&ire->ire_lock);
10986 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
10987 	mutex_exit(&ire->ire_lock);
10988 
10989 	/* remote(4), local(3), or discard(2) */
10990 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10991 		re->ipv6RouteType = 2;
10992 	else if (ire->ire_type & IRE_ONLINK)
10993 		re->ipv6RouteType = 3;
10994 	else
10995 		re->ipv6RouteType = 4;
10996 
10997 	re->ipv6RouteProtocol	= -1;
10998 	re->ipv6RoutePolicy	= 0;
10999 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
11000 	re->ipv6RouteNextHopRDI	= 0;
11001 	re->ipv6RouteWeight	= 0;
11002 	re->ipv6RouteMetric	= 0;
11003 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11004 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11005 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11006 
11007 	re->ipv6RouteInfo.re_frag_flag	= 0;
11008 	re->ipv6RouteInfo.re_rtt	= 0;
11009 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
11010 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11011 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11012 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
11013 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
11014 
11015 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11016 	if (ire->ire_type & IRE_INTERFACE) {
11017 		ire_t *child;
11018 
11019 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11020 		child = ire->ire_dep_children;
11021 		while (child != NULL) {
11022 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11023 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11024 			child = child->ire_dep_sib_next;
11025 		}
11026 		rw_exit(&ipst->ips_ire_dep_lock);
11027 	}
11028 	if (ire->ire_flags & RTF_DYNAMIC) {
11029 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11030 	} else {
11031 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
11032 	}
11033 
11034 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11035 	    (char *)re, (int)sizeof (*re))) {
11036 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11037 		    (uint_t)sizeof (*re)));
11038 	}
11039 
11040 	if (gc != NULL) {
11041 		iaes.iae_routeidx = ird->ird_idx;
11042 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11043 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11044 
11045 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11046 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11047 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11048 			    "bytes\n", (uint_t)sizeof (iaes)));
11049 		}
11050 	}
11051 
11052 	/* bump route index for next pass */
11053 	ird->ird_idx++;
11054 
11055 	kmem_free(re, sizeof (*re));
11056 	if (gcgrp != NULL)
11057 		rw_exit(&gcgrp->gcgrp_rwlock);
11058 }
11059 
11060 /*
11061  * ncec_walk routine to create ipv6NetToMediaEntryTable
11062  */
11063 static int
11064 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11065 {
11066 	ill_t				*ill;
11067 	mib2_ipv6NetToMediaEntry_t	ntme;
11068 
11069 	ill = ncec->ncec_ill;
11070 	/* skip arpce entries, and loopback ncec entries */
11071 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11072 		return (0);
11073 	/*
11074 	 * Neighbor cache entry attached to IRE with on-link
11075 	 * destination.
11076 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11077 	 */
11078 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11079 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11080 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11081 	if (ncec->ncec_lladdr != NULL) {
11082 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11083 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11084 	}
11085 	/*
11086 	 * Note: Returns ND_* states. Should be:
11087 	 * reachable(1), stale(2), delay(3), probe(4),
11088 	 * invalid(5), unknown(6)
11089 	 */
11090 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11091 	ntme.ipv6NetToMediaLastUpdated = 0;
11092 
11093 	/* other(1), dynamic(2), static(3), local(4) */
11094 	if (NCE_MYADDR(ncec)) {
11095 		ntme.ipv6NetToMediaType = 4;
11096 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11097 		ntme.ipv6NetToMediaType = 1; /* proxy */
11098 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11099 		ntme.ipv6NetToMediaType = 3;
11100 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11101 		ntme.ipv6NetToMediaType = 1;
11102 	} else {
11103 		ntme.ipv6NetToMediaType = 2;
11104 	}
11105 
11106 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11107 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11108 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11109 		    (uint_t)sizeof (ntme)));
11110 	}
11111 	return (0);
11112 }
11113 
11114 int
11115 nce2ace(ncec_t *ncec)
11116 {
11117 	int flags = 0;
11118 
11119 	if (NCE_ISREACHABLE(ncec))
11120 		flags |= ACE_F_RESOLVED;
11121 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11122 		flags |= ACE_F_AUTHORITY;
11123 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11124 		flags |= ACE_F_PUBLISH;
11125 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11126 		flags |= ACE_F_PERMANENT;
11127 	if (NCE_MYADDR(ncec))
11128 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11129 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11130 		flags |= ACE_F_UNVERIFIED;
11131 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11132 		flags |= ACE_F_AUTHORITY;
11133 	if (ncec->ncec_flags & NCE_F_DELAYED)
11134 		flags |= ACE_F_DELAYED;
11135 	return (flags);
11136 }
11137 
11138 /*
11139  * ncec_walk routine to create ipNetToMediaEntryTable
11140  */
11141 static int
11142 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11143 {
11144 	ill_t				*ill;
11145 	mib2_ipNetToMediaEntry_t	ntme;
11146 	const char			*name = "unknown";
11147 	ipaddr_t			ncec_addr;
11148 
11149 	ill = ncec->ncec_ill;
11150 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11151 	    ill->ill_net_type == IRE_LOOPBACK)
11152 		return (0);
11153 
11154 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11155 	name = ill->ill_name;
11156 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11157 	if (NCE_MYADDR(ncec)) {
11158 		ntme.ipNetToMediaType = 4;
11159 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11160 		ntme.ipNetToMediaType = 1;
11161 	} else {
11162 		ntme.ipNetToMediaType = 3;
11163 	}
11164 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11165 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11166 	    ntme.ipNetToMediaIfIndex.o_length);
11167 
11168 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11169 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11170 
11171 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11172 	ncec_addr = INADDR_BROADCAST;
11173 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11174 	    sizeof (ncec_addr));
11175 	/*
11176 	 * map all the flags to the ACE counterpart.
11177 	 */
11178 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11179 
11180 	ntme.ipNetToMediaPhysAddress.o_length =
11181 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11182 
11183 	if (!NCE_ISREACHABLE(ncec))
11184 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11185 	else {
11186 		if (ncec->ncec_lladdr != NULL) {
11187 			bcopy(ncec->ncec_lladdr,
11188 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11189 			    ntme.ipNetToMediaPhysAddress.o_length);
11190 		}
11191 	}
11192 
11193 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11194 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11195 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11196 		    (uint_t)sizeof (ntme)));
11197 	}
11198 	return (0);
11199 }
11200 
11201 /*
11202  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11203  */
11204 /* ARGSUSED */
11205 int
11206 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11207 {
11208 	switch (level) {
11209 	case MIB2_IP:
11210 	case MIB2_ICMP:
11211 		switch (name) {
11212 		default:
11213 			break;
11214 		}
11215 		return (1);
11216 	default:
11217 		return (1);
11218 	}
11219 }
11220 
11221 /*
11222  * When there exists both a 64- and 32-bit counter of a particular type
11223  * (i.e., InReceives), only the 64-bit counters are added.
11224  */
11225 void
11226 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11227 {
11228 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11229 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11230 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11231 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11232 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11233 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11234 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11235 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11236 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11237 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11238 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11239 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11240 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11241 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11242 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11243 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11244 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11245 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11246 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11247 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11248 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11249 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11250 	    o2->ipIfStatsInWrongIPVersion);
11251 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11252 	    o2->ipIfStatsInWrongIPVersion);
11253 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11254 	    o2->ipIfStatsOutSwitchIPVersion);
11255 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11256 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11257 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11258 	    o2->ipIfStatsHCInForwDatagrams);
11259 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11260 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11261 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11262 	    o2->ipIfStatsHCOutForwDatagrams);
11263 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11264 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11265 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11266 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11267 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11268 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11269 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11270 	    o2->ipIfStatsHCOutMcastOctets);
11271 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11272 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11273 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11274 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11275 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11276 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11277 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11278 }
11279 
11280 void
11281 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11282 {
11283 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11284 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11285 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11286 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11287 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11288 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11289 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11290 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11291 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11292 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11293 	    o2->ipv6IfIcmpInRouterSolicits);
11294 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11295 	    o2->ipv6IfIcmpInRouterAdvertisements);
11296 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11297 	    o2->ipv6IfIcmpInNeighborSolicits);
11298 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11299 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11300 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11301 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11302 	    o2->ipv6IfIcmpInGroupMembQueries);
11303 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11304 	    o2->ipv6IfIcmpInGroupMembResponses);
11305 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11306 	    o2->ipv6IfIcmpInGroupMembReductions);
11307 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11308 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11309 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11310 	    o2->ipv6IfIcmpOutDestUnreachs);
11311 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11312 	    o2->ipv6IfIcmpOutAdminProhibs);
11313 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11314 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11315 	    o2->ipv6IfIcmpOutParmProblems);
11316 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11317 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11318 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11319 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11320 	    o2->ipv6IfIcmpOutRouterSolicits);
11321 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11322 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11323 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11324 	    o2->ipv6IfIcmpOutNeighborSolicits);
11325 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11326 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11327 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11328 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11329 	    o2->ipv6IfIcmpOutGroupMembQueries);
11330 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11331 	    o2->ipv6IfIcmpOutGroupMembResponses);
11332 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11333 	    o2->ipv6IfIcmpOutGroupMembReductions);
11334 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11335 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11336 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11337 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11338 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11339 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11340 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11341 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11342 	    o2->ipv6IfIcmpInGroupMembTotal);
11343 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11344 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11345 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11346 	    o2->ipv6IfIcmpInGroupMembBadReports);
11347 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11348 	    o2->ipv6IfIcmpInGroupMembOurReports);
11349 }
11350 
11351 /*
11352  * Called before the options are updated to check if this packet will
11353  * be source routed from here.
11354  * This routine assumes that the options are well formed i.e. that they
11355  * have already been checked.
11356  */
11357 boolean_t
11358 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11359 {
11360 	ipoptp_t	opts;
11361 	uchar_t		*opt;
11362 	uint8_t		optval;
11363 	uint8_t		optlen;
11364 	ipaddr_t	dst;
11365 
11366 	if (IS_SIMPLE_IPH(ipha)) {
11367 		ip2dbg(("not source routed\n"));
11368 		return (B_FALSE);
11369 	}
11370 	dst = ipha->ipha_dst;
11371 	for (optval = ipoptp_first(&opts, ipha);
11372 	    optval != IPOPT_EOL;
11373 	    optval = ipoptp_next(&opts)) {
11374 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11375 		opt = opts.ipoptp_cur;
11376 		optlen = opts.ipoptp_len;
11377 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11378 		    optval, optlen));
11379 		switch (optval) {
11380 			uint32_t off;
11381 		case IPOPT_SSRR:
11382 		case IPOPT_LSRR:
11383 			/*
11384 			 * If dst is one of our addresses and there are some
11385 			 * entries left in the source route return (true).
11386 			 */
11387 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11388 				ip2dbg(("ip_source_routed: not next"
11389 				    " source route 0x%x\n",
11390 				    ntohl(dst)));
11391 				return (B_FALSE);
11392 			}
11393 			off = opt[IPOPT_OFFSET];
11394 			off--;
11395 			if (optlen < IP_ADDR_LEN ||
11396 			    off > optlen - IP_ADDR_LEN) {
11397 				/* End of source route */
11398 				ip1dbg(("ip_source_routed: end of SR\n"));
11399 				return (B_FALSE);
11400 			}
11401 			return (B_TRUE);
11402 		}
11403 	}
11404 	ip2dbg(("not source routed\n"));
11405 	return (B_FALSE);
11406 }
11407 
11408 /*
11409  * ip_unbind is called by the transports to remove a conn from
11410  * the fanout table.
11411  */
11412 void
11413 ip_unbind(conn_t *connp)
11414 {
11415 
11416 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11417 
11418 	if (is_system_labeled() && connp->conn_anon_port) {
11419 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11420 		    connp->conn_mlp_type, connp->conn_proto,
11421 		    ntohs(connp->conn_lport), B_FALSE);
11422 		connp->conn_anon_port = 0;
11423 	}
11424 	connp->conn_mlp_type = mlptSingle;
11425 
11426 	ipcl_hash_remove(connp);
11427 }
11428 
11429 /*
11430  * Used for deciding the MSS size for the upper layer. Thus
11431  * we need to check the outbound policy values in the conn.
11432  */
11433 int
11434 conn_ipsec_length(conn_t *connp)
11435 {
11436 	ipsec_latch_t *ipl;
11437 
11438 	ipl = connp->conn_latch;
11439 	if (ipl == NULL)
11440 		return (0);
11441 
11442 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11443 		return (0);
11444 
11445 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11446 }
11447 
11448 /*
11449  * Returns an estimate of the IPsec headers size. This is used if
11450  * we don't want to call into IPsec to get the exact size.
11451  */
11452 int
11453 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11454 {
11455 	ipsec_action_t *a;
11456 
11457 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11458 		return (0);
11459 
11460 	a = ixa->ixa_ipsec_action;
11461 	if (a == NULL) {
11462 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11463 		a = ixa->ixa_ipsec_policy->ipsp_act;
11464 	}
11465 	ASSERT(a != NULL);
11466 
11467 	return (a->ipa_ovhd);
11468 }
11469 
11470 /*
11471  * If there are any source route options, return the true final
11472  * destination. Otherwise, return the destination.
11473  */
11474 ipaddr_t
11475 ip_get_dst(ipha_t *ipha)
11476 {
11477 	ipoptp_t	opts;
11478 	uchar_t		*opt;
11479 	uint8_t		optval;
11480 	uint8_t		optlen;
11481 	ipaddr_t	dst;
11482 	uint32_t off;
11483 
11484 	dst = ipha->ipha_dst;
11485 
11486 	if (IS_SIMPLE_IPH(ipha))
11487 		return (dst);
11488 
11489 	for (optval = ipoptp_first(&opts, ipha);
11490 	    optval != IPOPT_EOL;
11491 	    optval = ipoptp_next(&opts)) {
11492 		opt = opts.ipoptp_cur;
11493 		optlen = opts.ipoptp_len;
11494 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11495 		switch (optval) {
11496 		case IPOPT_SSRR:
11497 		case IPOPT_LSRR:
11498 			off = opt[IPOPT_OFFSET];
11499 			/*
11500 			 * If one of the conditions is true, it means
11501 			 * end of options and dst already has the right
11502 			 * value.
11503 			 */
11504 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11505 				off = optlen - IP_ADDR_LEN;
11506 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11507 			}
11508 			return (dst);
11509 		default:
11510 			break;
11511 		}
11512 	}
11513 
11514 	return (dst);
11515 }
11516 
11517 /*
11518  * Outbound IP fragmentation routine.
11519  * Assumes the caller has checked whether or not fragmentation should
11520  * be allowed. Here we copy the DF bit from the header to all the generated
11521  * fragments.
11522  */
11523 int
11524 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11525     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11526     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11527 {
11528 	int		i1;
11529 	int		hdr_len;
11530 	mblk_t		*hdr_mp;
11531 	ipha_t		*ipha;
11532 	int		ip_data_end;
11533 	int		len;
11534 	mblk_t		*mp = mp_orig;
11535 	int		offset;
11536 	ill_t		*ill = nce->nce_ill;
11537 	ip_stack_t	*ipst = ill->ill_ipst;
11538 	mblk_t		*carve_mp;
11539 	uint32_t	frag_flag;
11540 	uint_t		priority = mp->b_band;
11541 	int		error = 0;
11542 
11543 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11544 
11545 	if (pkt_len != msgdsize(mp)) {
11546 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11547 		    pkt_len, msgdsize(mp)));
11548 		freemsg(mp);
11549 		return (EINVAL);
11550 	}
11551 
11552 	if (max_frag == 0) {
11553 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11554 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11555 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11556 		freemsg(mp);
11557 		return (EINVAL);
11558 	}
11559 
11560 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11561 	ipha = (ipha_t *)mp->b_rptr;
11562 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11563 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11564 
11565 	/*
11566 	 * Establish the starting offset.  May not be zero if we are fragging
11567 	 * a fragment that is being forwarded.
11568 	 */
11569 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11570 
11571 	/* TODO why is this test needed? */
11572 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11573 		/* TODO: notify ulp somehow */
11574 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11575 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11576 		freemsg(mp);
11577 		return (EINVAL);
11578 	}
11579 
11580 	hdr_len = IPH_HDR_LENGTH(ipha);
11581 	ipha->ipha_hdr_checksum = 0;
11582 
11583 	/*
11584 	 * Establish the number of bytes maximum per frag, after putting
11585 	 * in the header.
11586 	 */
11587 	len = (max_frag - hdr_len) & ~7;
11588 
11589 	/* Get a copy of the header for the trailing frags */
11590 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11591 	    mp);
11592 	if (hdr_mp == NULL) {
11593 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11594 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11595 		freemsg(mp);
11596 		return (ENOBUFS);
11597 	}
11598 
11599 	/* Store the starting offset, with the MoreFrags flag. */
11600 	i1 = offset | IPH_MF | frag_flag;
11601 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11602 
11603 	/* Establish the ending byte offset, based on the starting offset. */
11604 	offset <<= 3;
11605 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11606 
11607 	/* Store the length of the first fragment in the IP header. */
11608 	i1 = len + hdr_len;
11609 	ASSERT(i1 <= IP_MAXPACKET);
11610 	ipha->ipha_length = htons((uint16_t)i1);
11611 
11612 	/*
11613 	 * Compute the IP header checksum for the first frag.  We have to
11614 	 * watch out that we stop at the end of the header.
11615 	 */
11616 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11617 
11618 	/*
11619 	 * Now carve off the first frag.  Note that this will include the
11620 	 * original IP header.
11621 	 */
11622 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11623 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11624 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11625 		freeb(hdr_mp);
11626 		freemsg(mp_orig);
11627 		return (ENOBUFS);
11628 	}
11629 
11630 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11631 
11632 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11633 	    ixa_cookie);
11634 	if (error != 0 && error != EWOULDBLOCK) {
11635 		/* No point in sending the other fragments */
11636 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11637 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11638 		freeb(hdr_mp);
11639 		freemsg(mp_orig);
11640 		return (error);
11641 	}
11642 
11643 	/* No need to redo state machine in loop */
11644 	ixaflags &= ~IXAF_REACH_CONF;
11645 
11646 	/* Advance the offset to the second frag starting point. */
11647 	offset += len;
11648 	/*
11649 	 * Update hdr_len from the copied header - there might be less options
11650 	 * in the later fragments.
11651 	 */
11652 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11653 	/* Loop until done. */
11654 	for (;;) {
11655 		uint16_t	offset_and_flags;
11656 		uint16_t	ip_len;
11657 
11658 		if (ip_data_end - offset > len) {
11659 			/*
11660 			 * Carve off the appropriate amount from the original
11661 			 * datagram.
11662 			 */
11663 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11664 				mp = NULL;
11665 				break;
11666 			}
11667 			/*
11668 			 * More frags after this one.  Get another copy
11669 			 * of the header.
11670 			 */
11671 			if (carve_mp->b_datap->db_ref == 1 &&
11672 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11673 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11674 				/* Inline IP header */
11675 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11676 				    hdr_mp->b_rptr;
11677 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11678 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11679 				mp = carve_mp;
11680 			} else {
11681 				if (!(mp = copyb(hdr_mp))) {
11682 					freemsg(carve_mp);
11683 					break;
11684 				}
11685 				/* Get priority marking, if any. */
11686 				mp->b_band = priority;
11687 				mp->b_cont = carve_mp;
11688 			}
11689 			ipha = (ipha_t *)mp->b_rptr;
11690 			offset_and_flags = IPH_MF;
11691 		} else {
11692 			/*
11693 			 * Last frag.  Consume the header. Set len to
11694 			 * the length of this last piece.
11695 			 */
11696 			len = ip_data_end - offset;
11697 
11698 			/*
11699 			 * Carve off the appropriate amount from the original
11700 			 * datagram.
11701 			 */
11702 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11703 				mp = NULL;
11704 				break;
11705 			}
11706 			if (carve_mp->b_datap->db_ref == 1 &&
11707 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11708 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11709 				/* Inline IP header */
11710 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11711 				    hdr_mp->b_rptr;
11712 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11713 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11714 				mp = carve_mp;
11715 				freeb(hdr_mp);
11716 				hdr_mp = mp;
11717 			} else {
11718 				mp = hdr_mp;
11719 				/* Get priority marking, if any. */
11720 				mp->b_band = priority;
11721 				mp->b_cont = carve_mp;
11722 			}
11723 			ipha = (ipha_t *)mp->b_rptr;
11724 			/* A frag of a frag might have IPH_MF non-zero */
11725 			offset_and_flags =
11726 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11727 			    IPH_MF;
11728 		}
11729 		offset_and_flags |= (uint16_t)(offset >> 3);
11730 		offset_and_flags |= (uint16_t)frag_flag;
11731 		/* Store the offset and flags in the IP header. */
11732 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11733 
11734 		/* Store the length in the IP header. */
11735 		ip_len = (uint16_t)(len + hdr_len);
11736 		ipha->ipha_length = htons(ip_len);
11737 
11738 		/*
11739 		 * Set the IP header checksum.	Note that mp is just
11740 		 * the header, so this is easy to pass to ip_csum.
11741 		 */
11742 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11743 
11744 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11745 
11746 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11747 		    nolzid, ixa_cookie);
11748 		/* All done if we just consumed the hdr_mp. */
11749 		if (mp == hdr_mp) {
11750 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11751 			return (error);
11752 		}
11753 		if (error != 0 && error != EWOULDBLOCK) {
11754 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11755 			    mblk_t *, hdr_mp);
11756 			/* No point in sending the other fragments */
11757 			break;
11758 		}
11759 
11760 		/* Otherwise, advance and loop. */
11761 		offset += len;
11762 	}
11763 	/* Clean up following allocation failure. */
11764 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11765 	ip_drop_output("FragFails: loop ended", NULL, ill);
11766 	if (mp != hdr_mp)
11767 		freeb(hdr_mp);
11768 	if (mp != mp_orig)
11769 		freemsg(mp_orig);
11770 	return (error);
11771 }
11772 
11773 /*
11774  * Copy the header plus those options which have the copy bit set
11775  */
11776 static mblk_t *
11777 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11778     mblk_t *src)
11779 {
11780 	mblk_t	*mp;
11781 	uchar_t	*up;
11782 
11783 	/*
11784 	 * Quick check if we need to look for options without the copy bit
11785 	 * set
11786 	 */
11787 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11788 	if (!mp)
11789 		return (mp);
11790 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11791 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11792 		bcopy(rptr, mp->b_rptr, hdr_len);
11793 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11794 		return (mp);
11795 	}
11796 	up  = mp->b_rptr;
11797 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11798 	up += IP_SIMPLE_HDR_LENGTH;
11799 	rptr += IP_SIMPLE_HDR_LENGTH;
11800 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11801 	while (hdr_len > 0) {
11802 		uint32_t optval;
11803 		uint32_t optlen;
11804 
11805 		optval = *rptr;
11806 		if (optval == IPOPT_EOL)
11807 			break;
11808 		if (optval == IPOPT_NOP)
11809 			optlen = 1;
11810 		else
11811 			optlen = rptr[1];
11812 		if (optval & IPOPT_COPY) {
11813 			bcopy(rptr, up, optlen);
11814 			up += optlen;
11815 		}
11816 		rptr += optlen;
11817 		hdr_len -= optlen;
11818 	}
11819 	/*
11820 	 * Make sure that we drop an even number of words by filling
11821 	 * with EOL to the next word boundary.
11822 	 */
11823 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11824 	    hdr_len & 0x3; hdr_len++)
11825 		*up++ = IPOPT_EOL;
11826 	mp->b_wptr = up;
11827 	/* Update header length */
11828 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11829 	return (mp);
11830 }
11831 
11832 /*
11833  * Update any source route, record route, or timestamp options when
11834  * sending a packet back to ourselves.
11835  * Check that we are at end of strict source route.
11836  * The options have been sanity checked by ip_output_options().
11837  */
11838 void
11839 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11840 {
11841 	ipoptp_t	opts;
11842 	uchar_t		*opt;
11843 	uint8_t		optval;
11844 	uint8_t		optlen;
11845 	ipaddr_t	dst;
11846 	uint32_t	ts;
11847 	timestruc_t	now;
11848 
11849 	for (optval = ipoptp_first(&opts, ipha);
11850 	    optval != IPOPT_EOL;
11851 	    optval = ipoptp_next(&opts)) {
11852 		opt = opts.ipoptp_cur;
11853 		optlen = opts.ipoptp_len;
11854 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11855 		switch (optval) {
11856 			uint32_t off;
11857 		case IPOPT_SSRR:
11858 		case IPOPT_LSRR:
11859 			off = opt[IPOPT_OFFSET];
11860 			off--;
11861 			if (optlen < IP_ADDR_LEN ||
11862 			    off > optlen - IP_ADDR_LEN) {
11863 				/* End of source route */
11864 				break;
11865 			}
11866 			/*
11867 			 * This will only happen if two consecutive entries
11868 			 * in the source route contains our address or if
11869 			 * it is a packet with a loose source route which
11870 			 * reaches us before consuming the whole source route
11871 			 */
11872 
11873 			if (optval == IPOPT_SSRR) {
11874 				return;
11875 			}
11876 			/*
11877 			 * Hack: instead of dropping the packet truncate the
11878 			 * source route to what has been used by filling the
11879 			 * rest with IPOPT_NOP.
11880 			 */
11881 			opt[IPOPT_OLEN] = (uint8_t)off;
11882 			while (off < optlen) {
11883 				opt[off++] = IPOPT_NOP;
11884 			}
11885 			break;
11886 		case IPOPT_RR:
11887 			off = opt[IPOPT_OFFSET];
11888 			off--;
11889 			if (optlen < IP_ADDR_LEN ||
11890 			    off > optlen - IP_ADDR_LEN) {
11891 				/* No more room - ignore */
11892 				ip1dbg((
11893 				    "ip_output_local_options: end of RR\n"));
11894 				break;
11895 			}
11896 			dst = htonl(INADDR_LOOPBACK);
11897 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11898 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11899 			break;
11900 		case IPOPT_TS:
11901 			/* Insert timestamp if there is romm */
11902 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11903 			case IPOPT_TS_TSONLY:
11904 				off = IPOPT_TS_TIMELEN;
11905 				break;
11906 			case IPOPT_TS_PRESPEC:
11907 			case IPOPT_TS_PRESPEC_RFC791:
11908 				/* Verify that the address matched */
11909 				off = opt[IPOPT_OFFSET] - 1;
11910 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
11911 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11912 					/* Not for us */
11913 					break;
11914 				}
11915 				/* FALLTHRU */
11916 			case IPOPT_TS_TSANDADDR:
11917 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
11918 				break;
11919 			default:
11920 				/*
11921 				 * ip_*put_options should have already
11922 				 * dropped this packet.
11923 				 */
11924 				cmn_err(CE_PANIC, "ip_output_local_options: "
11925 				    "unknown IT - bug in ip_output_options?\n");
11926 				return;	/* Keep "lint" happy */
11927 			}
11928 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
11929 				/* Increase overflow counter */
11930 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
11931 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
11932 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
11933 				    (off << 4);
11934 				break;
11935 			}
11936 			off = opt[IPOPT_OFFSET] - 1;
11937 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11938 			case IPOPT_TS_PRESPEC:
11939 			case IPOPT_TS_PRESPEC_RFC791:
11940 			case IPOPT_TS_TSANDADDR:
11941 				dst = htonl(INADDR_LOOPBACK);
11942 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11943 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11944 				/* FALLTHRU */
11945 			case IPOPT_TS_TSONLY:
11946 				off = opt[IPOPT_OFFSET] - 1;
11947 				/* Compute # of milliseconds since midnight */
11948 				gethrestime(&now);
11949 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
11950 				    now.tv_nsec / (NANOSEC / MILLISEC);
11951 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
11952 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
11953 				break;
11954 			}
11955 			break;
11956 		}
11957 	}
11958 }
11959 
11960 /*
11961  * Prepend an M_DATA fastpath header, and if none present prepend a
11962  * DL_UNITDATA_REQ. Frees the mblk on failure.
11963  *
11964  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
11965  * If there is a change to them, the nce will be deleted (condemned) and
11966  * a new nce_t will be created when packets are sent. Thus we need no locks
11967  * to access those fields.
11968  *
11969  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
11970  * we place b_band in dl_priority.dl_max.
11971  */
11972 static mblk_t *
11973 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
11974 {
11975 	uint_t	hlen;
11976 	mblk_t *mp1;
11977 	uint_t	priority;
11978 	uchar_t *rptr;
11979 
11980 	rptr = mp->b_rptr;
11981 
11982 	ASSERT(DB_TYPE(mp) == M_DATA);
11983 	priority = mp->b_band;
11984 
11985 	ASSERT(nce != NULL);
11986 	if ((mp1 = nce->nce_fp_mp) != NULL) {
11987 		hlen = MBLKL(mp1);
11988 		/*
11989 		 * Check if we have enough room to prepend fastpath
11990 		 * header
11991 		 */
11992 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
11993 			rptr -= hlen;
11994 			bcopy(mp1->b_rptr, rptr, hlen);
11995 			/*
11996 			 * Set the b_rptr to the start of the link layer
11997 			 * header
11998 			 */
11999 			mp->b_rptr = rptr;
12000 			return (mp);
12001 		}
12002 		mp1 = copyb(mp1);
12003 		if (mp1 == NULL) {
12004 			ill_t *ill = nce->nce_ill;
12005 
12006 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12007 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12008 			freemsg(mp);
12009 			return (NULL);
12010 		}
12011 		mp1->b_band = priority;
12012 		mp1->b_cont = mp;
12013 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12014 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12015 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12016 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12017 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12018 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12019 		/*
12020 		 * XXX disable ICK_VALID and compute checksum
12021 		 * here; can happen if nce_fp_mp changes and
12022 		 * it can't be copied now due to insufficient
12023 		 * space. (unlikely, fp mp can change, but it
12024 		 * does not increase in length)
12025 		 */
12026 		return (mp1);
12027 	}
12028 	mp1 = copyb(nce->nce_dlur_mp);
12029 
12030 	if (mp1 == NULL) {
12031 		ill_t *ill = nce->nce_ill;
12032 
12033 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12034 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12035 		freemsg(mp);
12036 		return (NULL);
12037 	}
12038 	mp1->b_cont = mp;
12039 	if (priority != 0) {
12040 		mp1->b_band = priority;
12041 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12042 		    priority;
12043 	}
12044 	return (mp1);
12045 #undef rptr
12046 }
12047 
12048 /*
12049  * Finish the outbound IPsec processing. This function is called from
12050  * ipsec_out_process() if the IPsec packet was processed
12051  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12052  * asynchronously.
12053  *
12054  * This is common to IPv4 and IPv6.
12055  */
12056 int
12057 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12058 {
12059 	iaflags_t	ixaflags = ixa->ixa_flags;
12060 	uint_t		pktlen;
12061 
12062 
12063 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12064 	if (ixaflags & IXAF_IS_IPV4) {
12065 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12066 
12067 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12068 		pktlen = ntohs(ipha->ipha_length);
12069 	} else {
12070 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12071 
12072 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12073 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12074 	}
12075 
12076 	/*
12077 	 * We release any hard reference on the SAs here to make
12078 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12079 	 * on the SAs.
12080 	 * If in the future we want the hard latching of the SAs in the
12081 	 * ip_xmit_attr_t then we should remove this.
12082 	 */
12083 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12084 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12085 		ixa->ixa_ipsec_esp_sa = NULL;
12086 	}
12087 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12088 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12089 		ixa->ixa_ipsec_ah_sa = NULL;
12090 	}
12091 
12092 	/* Do we need to fragment? */
12093 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12094 	    pktlen > ixa->ixa_fragsize) {
12095 		if (ixaflags & IXAF_IS_IPV4) {
12096 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12097 			/*
12098 			 * We check for the DF case in ipsec_out_process
12099 			 * hence this only handles the non-DF case.
12100 			 */
12101 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12102 			    pktlen, ixa->ixa_fragsize,
12103 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12104 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12105 			    &ixa->ixa_cookie));
12106 		} else {
12107 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12108 			if (mp == NULL) {
12109 				/* MIB and ip_drop_output already done */
12110 				return (ENOMEM);
12111 			}
12112 			pktlen += sizeof (ip6_frag_t);
12113 			if (pktlen > ixa->ixa_fragsize) {
12114 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12115 				    ixa->ixa_flags, pktlen,
12116 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12117 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12118 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12119 			}
12120 		}
12121 	}
12122 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12123 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12124 	    ixa->ixa_no_loop_zoneid, NULL));
12125 }
12126 
12127 /*
12128  * Finish the inbound IPsec processing. This function is called from
12129  * ipsec_out_process() if the IPsec packet was processed
12130  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12131  * asynchronously.
12132  *
12133  * This is common to IPv4 and IPv6.
12134  */
12135 void
12136 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12137 {
12138 	iaflags_t	iraflags = ira->ira_flags;
12139 
12140 	/* Length might have changed */
12141 	if (iraflags & IRAF_IS_IPV4) {
12142 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12143 
12144 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12145 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12146 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12147 		ira->ira_protocol = ipha->ipha_protocol;
12148 
12149 		ip_fanout_v4(mp, ipha, ira);
12150 	} else {
12151 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12152 		uint8_t		*nexthdrp;
12153 
12154 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12155 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12156 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12157 		    &nexthdrp)) {
12158 			/* Malformed packet */
12159 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12160 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12161 			freemsg(mp);
12162 			return;
12163 		}
12164 		ira->ira_protocol = *nexthdrp;
12165 		ip_fanout_v6(mp, ip6h, ira);
12166 	}
12167 }
12168 
12169 /*
12170  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12171  *
12172  * If this function returns B_TRUE, the requested SA's have been filled
12173  * into the ixa_ipsec_*_sa pointers.
12174  *
12175  * If the function returns B_FALSE, the packet has been "consumed", most
12176  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12177  *
12178  * The SA references created by the protocol-specific "select"
12179  * function will be released in ip_output_post_ipsec.
12180  */
12181 static boolean_t
12182 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12183 {
12184 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12185 	ipsec_policy_t *pp;
12186 	ipsec_action_t *ap;
12187 
12188 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12189 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12190 	    (ixa->ixa_ipsec_action != NULL));
12191 
12192 	ap = ixa->ixa_ipsec_action;
12193 	if (ap == NULL) {
12194 		pp = ixa->ixa_ipsec_policy;
12195 		ASSERT(pp != NULL);
12196 		ap = pp->ipsp_act;
12197 		ASSERT(ap != NULL);
12198 	}
12199 
12200 	/*
12201 	 * We have an action.  now, let's select SA's.
12202 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12203 	 * be cached in the conn_t.
12204 	 */
12205 	if (ap->ipa_want_esp) {
12206 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12207 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12208 			    IPPROTO_ESP);
12209 		}
12210 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12211 	}
12212 
12213 	if (ap->ipa_want_ah) {
12214 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12215 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12216 			    IPPROTO_AH);
12217 		}
12218 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12219 		/*
12220 		 * The ESP and AH processing order needs to be preserved
12221 		 * when both protocols are required (ESP should be applied
12222 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12223 		 * when both ESP and AH are required, and an AH ACQUIRE
12224 		 * is needed.
12225 		 */
12226 		if (ap->ipa_want_esp && need_ah_acquire)
12227 			need_esp_acquire = B_TRUE;
12228 	}
12229 
12230 	/*
12231 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12232 	 * Release SAs that got referenced, but will not be used until we
12233 	 * acquire _all_ of the SAs we need.
12234 	 */
12235 	if (need_ah_acquire || need_esp_acquire) {
12236 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12237 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12238 			ixa->ixa_ipsec_ah_sa = NULL;
12239 		}
12240 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12241 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12242 			ixa->ixa_ipsec_esp_sa = NULL;
12243 		}
12244 
12245 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12246 		return (B_FALSE);
12247 	}
12248 
12249 	return (B_TRUE);
12250 }
12251 
12252 /*
12253  * Handle IPsec output processing.
12254  * This function is only entered once for a given packet.
12255  * We try to do things synchronously, but if we need to have user-level
12256  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12257  * will be completed
12258  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12259  *  - when asynchronous ESP is done it will do AH
12260  *
12261  * In all cases we come back in ip_output_post_ipsec() to fragment and
12262  * send out the packet.
12263  */
12264 int
12265 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12266 {
12267 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12268 	ip_stack_t	*ipst = ixa->ixa_ipst;
12269 	ipsec_stack_t	*ipss;
12270 	ipsec_policy_t	*pp;
12271 	ipsec_action_t	*ap;
12272 
12273 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12274 
12275 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12276 	    (ixa->ixa_ipsec_action != NULL));
12277 
12278 	ipss = ipst->ips_netstack->netstack_ipsec;
12279 	if (!ipsec_loaded(ipss)) {
12280 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12281 		ip_drop_packet(mp, B_TRUE, ill,
12282 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12283 		    &ipss->ipsec_dropper);
12284 		return (ENOTSUP);
12285 	}
12286 
12287 	ap = ixa->ixa_ipsec_action;
12288 	if (ap == NULL) {
12289 		pp = ixa->ixa_ipsec_policy;
12290 		ASSERT(pp != NULL);
12291 		ap = pp->ipsp_act;
12292 		ASSERT(ap != NULL);
12293 	}
12294 
12295 	/* Handle explicit drop action and bypass. */
12296 	switch (ap->ipa_act.ipa_type) {
12297 	case IPSEC_ACT_DISCARD:
12298 	case IPSEC_ACT_REJECT:
12299 		ip_drop_packet(mp, B_FALSE, ill,
12300 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12301 		return (EHOSTUNREACH);	/* IPsec policy failure */
12302 	case IPSEC_ACT_BYPASS:
12303 		return (ip_output_post_ipsec(mp, ixa));
12304 	}
12305 
12306 	/*
12307 	 * The order of processing is first insert a IP header if needed.
12308 	 * Then insert the ESP header and then the AH header.
12309 	 */
12310 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12311 		/*
12312 		 * First get the outer IP header before sending
12313 		 * it to ESP.
12314 		 */
12315 		ipha_t *oipha, *iipha;
12316 		mblk_t *outer_mp, *inner_mp;
12317 
12318 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12319 			(void) mi_strlog(ill->ill_rq, 0,
12320 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12321 			    "ipsec_out_process: "
12322 			    "Self-Encapsulation failed: Out of memory\n");
12323 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12324 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12325 			freemsg(mp);
12326 			return (ENOBUFS);
12327 		}
12328 		inner_mp = mp;
12329 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12330 		oipha = (ipha_t *)outer_mp->b_rptr;
12331 		iipha = (ipha_t *)inner_mp->b_rptr;
12332 		*oipha = *iipha;
12333 		outer_mp->b_wptr += sizeof (ipha_t);
12334 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12335 		    sizeof (ipha_t));
12336 		oipha->ipha_protocol = IPPROTO_ENCAP;
12337 		oipha->ipha_version_and_hdr_length =
12338 		    IP_SIMPLE_HDR_VERSION;
12339 		oipha->ipha_hdr_checksum = 0;
12340 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12341 		outer_mp->b_cont = inner_mp;
12342 		mp = outer_mp;
12343 
12344 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12345 	}
12346 
12347 	/* If we need to wait for a SA then we can't return any errno */
12348 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12349 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12350 	    !ipsec_out_select_sa(mp, ixa))
12351 		return (0);
12352 
12353 	/*
12354 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12355 	 * to do the heavy lifting.
12356 	 */
12357 	if (ap->ipa_want_esp) {
12358 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12359 
12360 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12361 		if (mp == NULL) {
12362 			/*
12363 			 * Either it failed or is pending. In the former case
12364 			 * ipIfStatsInDiscards was increased.
12365 			 */
12366 			return (0);
12367 		}
12368 	}
12369 
12370 	if (ap->ipa_want_ah) {
12371 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12372 
12373 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12374 		if (mp == NULL) {
12375 			/*
12376 			 * Either it failed or is pending. In the former case
12377 			 * ipIfStatsInDiscards was increased.
12378 			 */
12379 			return (0);
12380 		}
12381 	}
12382 	/*
12383 	 * We are done with IPsec processing. Send it over
12384 	 * the wire.
12385 	 */
12386 	return (ip_output_post_ipsec(mp, ixa));
12387 }
12388 
12389 /*
12390  * ioctls that go through a down/up sequence may need to wait for the down
12391  * to complete. This involves waiting for the ire and ipif refcnts to go down
12392  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12393  */
12394 /* ARGSUSED */
12395 void
12396 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12397 {
12398 	struct iocblk *iocp;
12399 	mblk_t *mp1;
12400 	ip_ioctl_cmd_t *ipip;
12401 	int err;
12402 	sin_t	*sin;
12403 	struct lifreq *lifr;
12404 	struct ifreq *ifr;
12405 
12406 	iocp = (struct iocblk *)mp->b_rptr;
12407 	ASSERT(ipsq != NULL);
12408 	/* Existence of mp1 verified in ip_wput_nondata */
12409 	mp1 = mp->b_cont->b_cont;
12410 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12411 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12412 		/*
12413 		 * Special case where ipx_current_ipif is not set:
12414 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12415 		 * We are here as were not able to complete the operation in
12416 		 * ipif_set_values because we could not become exclusive on
12417 		 * the new ipsq.
12418 		 */
12419 		ill_t *ill = q->q_ptr;
12420 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12421 	}
12422 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12423 
12424 	if (ipip->ipi_cmd_type == IF_CMD) {
12425 		/* This a old style SIOC[GS]IF* command */
12426 		ifr = (struct ifreq *)mp1->b_rptr;
12427 		sin = (sin_t *)&ifr->ifr_addr;
12428 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12429 		/* This a new style SIOC[GS]LIF* command */
12430 		lifr = (struct lifreq *)mp1->b_rptr;
12431 		sin = (sin_t *)&lifr->lifr_addr;
12432 	} else {
12433 		sin = NULL;
12434 	}
12435 
12436 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12437 	    q, mp, ipip, mp1->b_rptr);
12438 
12439 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12440 	    int, ipip->ipi_cmd,
12441 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12442 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12443 
12444 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12445 }
12446 
12447 /*
12448  * ioctl processing
12449  *
12450  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12451  * the ioctl command in the ioctl tables, determines the copyin data size
12452  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12453  *
12454  * ioctl processing then continues when the M_IOCDATA makes its way down to
12455  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12456  * associated 'conn' is refheld till the end of the ioctl and the general
12457  * ioctl processing function ip_process_ioctl() is called to extract the
12458  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12459  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12460  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12461  * is used to extract the ioctl's arguments.
12462  *
12463  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12464  * so goes thru the serialization primitive ipsq_try_enter. Then the
12465  * appropriate function to handle the ioctl is called based on the entry in
12466  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12467  * which also refreleases the 'conn' that was refheld at the start of the
12468  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12469  *
12470  * Many exclusive ioctls go thru an internal down up sequence as part of
12471  * the operation. For example an attempt to change the IP address of an
12472  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12473  * does all the cleanup such as deleting all ires that use this address.
12474  * Then we need to wait till all references to the interface go away.
12475  */
12476 void
12477 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12478 {
12479 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12480 	ip_ioctl_cmd_t *ipip = arg;
12481 	ip_extract_func_t *extract_funcp;
12482 	cmd_info_t ci;
12483 	int err;
12484 	boolean_t entered_ipsq = B_FALSE;
12485 
12486 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12487 
12488 	if (ipip == NULL)
12489 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12490 
12491 	/*
12492 	 * SIOCLIFADDIF needs to go thru a special path since the
12493 	 * ill may not exist yet. This happens in the case of lo0
12494 	 * which is created using this ioctl.
12495 	 */
12496 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12497 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12498 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12499 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12500 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12501 		return;
12502 	}
12503 
12504 	ci.ci_ipif = NULL;
12505 	switch (ipip->ipi_cmd_type) {
12506 	case MISC_CMD:
12507 	case MSFILT_CMD:
12508 		/*
12509 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12510 		 */
12511 		if (ipip->ipi_cmd == IF_UNITSEL) {
12512 			/* ioctl comes down the ill */
12513 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12514 			ipif_refhold(ci.ci_ipif);
12515 		}
12516 		err = 0;
12517 		ci.ci_sin = NULL;
12518 		ci.ci_sin6 = NULL;
12519 		ci.ci_lifr = NULL;
12520 		extract_funcp = NULL;
12521 		break;
12522 
12523 	case IF_CMD:
12524 	case LIF_CMD:
12525 		extract_funcp = ip_extract_lifreq;
12526 		break;
12527 
12528 	case ARP_CMD:
12529 	case XARP_CMD:
12530 		extract_funcp = ip_extract_arpreq;
12531 		break;
12532 
12533 	default:
12534 		ASSERT(0);
12535 	}
12536 
12537 	if (extract_funcp != NULL) {
12538 		err = (*extract_funcp)(q, mp, ipip, &ci);
12539 		if (err != 0) {
12540 			DTRACE_PROBE4(ipif__ioctl,
12541 			    char *, "ip_process_ioctl finish err",
12542 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12543 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12544 			return;
12545 		}
12546 
12547 		/*
12548 		 * All of the extraction functions return a refheld ipif.
12549 		 */
12550 		ASSERT(ci.ci_ipif != NULL);
12551 	}
12552 
12553 	if (!(ipip->ipi_flags & IPI_WR)) {
12554 		/*
12555 		 * A return value of EINPROGRESS means the ioctl is
12556 		 * either queued and waiting for some reason or has
12557 		 * already completed.
12558 		 */
12559 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12560 		    ci.ci_lifr);
12561 		if (ci.ci_ipif != NULL) {
12562 			DTRACE_PROBE4(ipif__ioctl,
12563 			    char *, "ip_process_ioctl finish RD",
12564 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12565 			    ipif_t *, ci.ci_ipif);
12566 			ipif_refrele(ci.ci_ipif);
12567 		} else {
12568 			DTRACE_PROBE4(ipif__ioctl,
12569 			    char *, "ip_process_ioctl finish RD",
12570 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12571 		}
12572 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12573 		return;
12574 	}
12575 
12576 	ASSERT(ci.ci_ipif != NULL);
12577 
12578 	/*
12579 	 * If ipsq is non-NULL, we are already being called exclusively
12580 	 */
12581 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12582 	if (ipsq == NULL) {
12583 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12584 		    NEW_OP, B_TRUE);
12585 		if (ipsq == NULL) {
12586 			ipif_refrele(ci.ci_ipif);
12587 			return;
12588 		}
12589 		entered_ipsq = B_TRUE;
12590 	}
12591 	/*
12592 	 * Release the ipif so that ipif_down and friends that wait for
12593 	 * references to go away are not misled about the current ipif_refcnt
12594 	 * values. We are writer so we can access the ipif even after releasing
12595 	 * the ipif.
12596 	 */
12597 	ipif_refrele(ci.ci_ipif);
12598 
12599 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12600 
12601 	/*
12602 	 * A return value of EINPROGRESS means the ioctl is
12603 	 * either queued and waiting for some reason or has
12604 	 * already completed.
12605 	 */
12606 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12607 
12608 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12609 	    int, ipip->ipi_cmd,
12610 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12611 	    ipif_t *, ci.ci_ipif);
12612 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12613 
12614 	if (entered_ipsq)
12615 		ipsq_exit(ipsq);
12616 }
12617 
12618 /*
12619  * Complete the ioctl. Typically ioctls use the mi package and need to
12620  * do mi_copyout/mi_copy_done.
12621  */
12622 void
12623 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12624 {
12625 	conn_t	*connp = NULL;
12626 
12627 	if (err == EINPROGRESS)
12628 		return;
12629 
12630 	if (CONN_Q(q)) {
12631 		connp = Q_TO_CONN(q);
12632 		ASSERT(connp->conn_ref >= 2);
12633 	}
12634 
12635 	switch (mode) {
12636 	case COPYOUT:
12637 		if (err == 0)
12638 			mi_copyout(q, mp);
12639 		else
12640 			mi_copy_done(q, mp, err);
12641 		break;
12642 
12643 	case NO_COPYOUT:
12644 		mi_copy_done(q, mp, err);
12645 		break;
12646 
12647 	default:
12648 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12649 		break;
12650 	}
12651 
12652 	/*
12653 	 * The conn refhold and ioctlref placed on the conn at the start of the
12654 	 * ioctl are released here.
12655 	 */
12656 	if (connp != NULL) {
12657 		CONN_DEC_IOCTLREF(connp);
12658 		CONN_OPER_PENDING_DONE(connp);
12659 	}
12660 
12661 	if (ipsq != NULL)
12662 		ipsq_current_finish(ipsq);
12663 }
12664 
12665 /* Handles all non data messages */
12666 void
12667 ip_wput_nondata(queue_t *q, mblk_t *mp)
12668 {
12669 	mblk_t		*mp1;
12670 	struct iocblk	*iocp;
12671 	ip_ioctl_cmd_t	*ipip;
12672 	conn_t		*connp;
12673 	cred_t		*cr;
12674 	char		*proto_str;
12675 
12676 	if (CONN_Q(q))
12677 		connp = Q_TO_CONN(q);
12678 	else
12679 		connp = NULL;
12680 
12681 	switch (DB_TYPE(mp)) {
12682 	case M_IOCTL:
12683 		/*
12684 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12685 		 * will arrange to copy in associated control structures.
12686 		 */
12687 		ip_sioctl_copyin_setup(q, mp);
12688 		return;
12689 	case M_IOCDATA:
12690 		/*
12691 		 * Ensure that this is associated with one of our trans-
12692 		 * parent ioctls.  If it's not ours, discard it if we're
12693 		 * running as a driver, or pass it on if we're a module.
12694 		 */
12695 		iocp = (struct iocblk *)mp->b_rptr;
12696 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12697 		if (ipip == NULL) {
12698 			if (q->q_next == NULL) {
12699 				goto nak;
12700 			} else {
12701 				putnext(q, mp);
12702 			}
12703 			return;
12704 		}
12705 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12706 			/*
12707 			 * The ioctl is one we recognise, but is not consumed
12708 			 * by IP as a module and we are a module, so we drop
12709 			 */
12710 			goto nak;
12711 		}
12712 
12713 		/* IOCTL continuation following copyin or copyout. */
12714 		if (mi_copy_state(q, mp, NULL) == -1) {
12715 			/*
12716 			 * The copy operation failed.  mi_copy_state already
12717 			 * cleaned up, so we're out of here.
12718 			 */
12719 			return;
12720 		}
12721 		/*
12722 		 * If we just completed a copy in, we become writer and
12723 		 * continue processing in ip_sioctl_copyin_done.  If it
12724 		 * was a copy out, we call mi_copyout again.  If there is
12725 		 * nothing more to copy out, it will complete the IOCTL.
12726 		 */
12727 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12728 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12729 				mi_copy_done(q, mp, EPROTO);
12730 				return;
12731 			}
12732 			/*
12733 			 * Check for cases that need more copying.  A return
12734 			 * value of 0 means a second copyin has been started,
12735 			 * so we return; a return value of 1 means no more
12736 			 * copying is needed, so we continue.
12737 			 */
12738 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12739 			    MI_COPY_COUNT(mp) == 1) {
12740 				if (ip_copyin_msfilter(q, mp) == 0)
12741 					return;
12742 			}
12743 			/*
12744 			 * Refhold the conn, till the ioctl completes. This is
12745 			 * needed in case the ioctl ends up in the pending mp
12746 			 * list. Every mp in the ipx_pending_mp list must have
12747 			 * a refhold on the conn to resume processing. The
12748 			 * refhold is released when the ioctl completes
12749 			 * (whether normally or abnormally). An ioctlref is also
12750 			 * placed on the conn to prevent TCP from removing the
12751 			 * queue needed to send the ioctl reply back.
12752 			 * In all cases ip_ioctl_finish is called to finish
12753 			 * the ioctl and release the refholds.
12754 			 */
12755 			if (connp != NULL) {
12756 				/* This is not a reentry */
12757 				CONN_INC_REF(connp);
12758 				CONN_INC_IOCTLREF(connp);
12759 			} else {
12760 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12761 					mi_copy_done(q, mp, EINVAL);
12762 					return;
12763 				}
12764 			}
12765 
12766 			ip_process_ioctl(NULL, q, mp, ipip);
12767 
12768 		} else {
12769 			mi_copyout(q, mp);
12770 		}
12771 		return;
12772 
12773 	case M_IOCNAK:
12774 		/*
12775 		 * The only way we could get here is if a resolver didn't like
12776 		 * an IOCTL we sent it.	 This shouldn't happen.
12777 		 */
12778 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12779 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12780 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12781 		freemsg(mp);
12782 		return;
12783 	case M_IOCACK:
12784 		/* /dev/ip shouldn't see this */
12785 		goto nak;
12786 	case M_FLUSH:
12787 		if (*mp->b_rptr & FLUSHW)
12788 			flushq(q, FLUSHALL);
12789 		if (q->q_next) {
12790 			putnext(q, mp);
12791 			return;
12792 		}
12793 		if (*mp->b_rptr & FLUSHR) {
12794 			*mp->b_rptr &= ~FLUSHW;
12795 			qreply(q, mp);
12796 			return;
12797 		}
12798 		freemsg(mp);
12799 		return;
12800 	case M_CTL:
12801 		break;
12802 	case M_PROTO:
12803 	case M_PCPROTO:
12804 		/*
12805 		 * The only PROTO messages we expect are SNMP-related.
12806 		 */
12807 		switch (((union T_primitives *)mp->b_rptr)->type) {
12808 		case T_SVR4_OPTMGMT_REQ:
12809 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12810 			    "flags %x\n",
12811 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12812 
12813 			if (connp == NULL) {
12814 				proto_str = "T_SVR4_OPTMGMT_REQ";
12815 				goto protonak;
12816 			}
12817 
12818 			/*
12819 			 * All Solaris components should pass a db_credp
12820 			 * for this TPI message, hence we ASSERT.
12821 			 * But in case there is some other M_PROTO that looks
12822 			 * like a TPI message sent by some other kernel
12823 			 * component, we check and return an error.
12824 			 */
12825 			cr = msg_getcred(mp, NULL);
12826 			ASSERT(cr != NULL);
12827 			if (cr == NULL) {
12828 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12829 				if (mp != NULL)
12830 					qreply(q, mp);
12831 				return;
12832 			}
12833 
12834 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12835 				proto_str = "Bad SNMPCOM request?";
12836 				goto protonak;
12837 			}
12838 			return;
12839 		default:
12840 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12841 			    (int)*(uint_t *)mp->b_rptr));
12842 			freemsg(mp);
12843 			return;
12844 		}
12845 	default:
12846 		break;
12847 	}
12848 	if (q->q_next) {
12849 		putnext(q, mp);
12850 	} else
12851 		freemsg(mp);
12852 	return;
12853 
12854 nak:
12855 	iocp->ioc_error = EINVAL;
12856 	mp->b_datap->db_type = M_IOCNAK;
12857 	iocp->ioc_count = 0;
12858 	qreply(q, mp);
12859 	return;
12860 
12861 protonak:
12862 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12863 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12864 		qreply(q, mp);
12865 }
12866 
12867 /*
12868  * Process IP options in an outbound packet.  Verify that the nexthop in a
12869  * strict source route is onlink.
12870  * Returns non-zero if something fails in which case an ICMP error has been
12871  * sent and mp freed.
12872  *
12873  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12874  */
12875 int
12876 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12877 {
12878 	ipoptp_t	opts;
12879 	uchar_t		*opt;
12880 	uint8_t		optval;
12881 	uint8_t		optlen;
12882 	ipaddr_t	dst;
12883 	intptr_t	code = 0;
12884 	ire_t		*ire;
12885 	ip_stack_t	*ipst = ixa->ixa_ipst;
12886 	ip_recv_attr_t	iras;
12887 
12888 	ip2dbg(("ip_output_options\n"));
12889 
12890 	dst = ipha->ipha_dst;
12891 	for (optval = ipoptp_first(&opts, ipha);
12892 	    optval != IPOPT_EOL;
12893 	    optval = ipoptp_next(&opts)) {
12894 		opt = opts.ipoptp_cur;
12895 		optlen = opts.ipoptp_len;
12896 		ip2dbg(("ip_output_options: opt %d, len %d\n",
12897 		    optval, optlen));
12898 		switch (optval) {
12899 			uint32_t off;
12900 		case IPOPT_SSRR:
12901 		case IPOPT_LSRR:
12902 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12903 				ip1dbg((
12904 				    "ip_output_options: bad option offset\n"));
12905 				code = (char *)&opt[IPOPT_OLEN] -
12906 				    (char *)ipha;
12907 				goto param_prob;
12908 			}
12909 			off = opt[IPOPT_OFFSET];
12910 			ip1dbg(("ip_output_options: next hop 0x%x\n",
12911 			    ntohl(dst)));
12912 			/*
12913 			 * For strict: verify that dst is directly
12914 			 * reachable.
12915 			 */
12916 			if (optval == IPOPT_SSRR) {
12917 				ire = ire_ftable_lookup_v4(dst, 0, 0,
12918 				    IRE_IF_ALL, NULL, ALL_ZONES, ixa->ixa_tsl,
12919 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
12920 				    NULL);
12921 				if (ire == NULL) {
12922 					ip1dbg(("ip_output_options: SSRR not"
12923 					    " directly reachable: 0x%x\n",
12924 					    ntohl(dst)));
12925 					goto bad_src_route;
12926 				}
12927 				ire_refrele(ire);
12928 			}
12929 			break;
12930 		case IPOPT_RR:
12931 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12932 				ip1dbg((
12933 				    "ip_output_options: bad option offset\n"));
12934 				code = (char *)&opt[IPOPT_OLEN] -
12935 				    (char *)ipha;
12936 				goto param_prob;
12937 			}
12938 			break;
12939 		case IPOPT_TS:
12940 			/*
12941 			 * Verify that length >=5 and that there is either
12942 			 * room for another timestamp or that the overflow
12943 			 * counter is not maxed out.
12944 			 */
12945 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
12946 			if (optlen < IPOPT_MINLEN_IT) {
12947 				goto param_prob;
12948 			}
12949 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12950 				ip1dbg((
12951 				    "ip_output_options: bad option offset\n"));
12952 				code = (char *)&opt[IPOPT_OFFSET] -
12953 				    (char *)ipha;
12954 				goto param_prob;
12955 			}
12956 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12957 			case IPOPT_TS_TSONLY:
12958 				off = IPOPT_TS_TIMELEN;
12959 				break;
12960 			case IPOPT_TS_TSANDADDR:
12961 			case IPOPT_TS_PRESPEC:
12962 			case IPOPT_TS_PRESPEC_RFC791:
12963 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12964 				break;
12965 			default:
12966 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
12967 				    (char *)ipha;
12968 				goto param_prob;
12969 			}
12970 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
12971 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
12972 				/*
12973 				 * No room and the overflow counter is 15
12974 				 * already.
12975 				 */
12976 				goto param_prob;
12977 			}
12978 			break;
12979 		}
12980 	}
12981 
12982 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
12983 		return (0);
12984 
12985 	ip1dbg(("ip_output_options: error processing IP options."));
12986 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
12987 
12988 param_prob:
12989 	bzero(&iras, sizeof (iras));
12990 	iras.ira_ill = iras.ira_rill = ill;
12991 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12992 	iras.ira_rifindex = iras.ira_ruifindex;
12993 	iras.ira_flags = IRAF_IS_IPV4;
12994 
12995 	ip_drop_output("ip_output_options", mp, ill);
12996 	icmp_param_problem(mp, (uint8_t)code, &iras);
12997 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12998 	return (-1);
12999 
13000 bad_src_route:
13001 	bzero(&iras, sizeof (iras));
13002 	iras.ira_ill = iras.ira_rill = ill;
13003 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13004 	iras.ira_rifindex = iras.ira_ruifindex;
13005 	iras.ira_flags = IRAF_IS_IPV4;
13006 
13007 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13008 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13009 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13010 	return (-1);
13011 }
13012 
13013 /*
13014  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13015  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13016  * thru /etc/system.
13017  */
13018 #define	CONN_MAXDRAINCNT	64
13019 
13020 static void
13021 conn_drain_init(ip_stack_t *ipst)
13022 {
13023 	int i, j;
13024 	idl_tx_list_t *itl_tx;
13025 
13026 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13027 
13028 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
13029 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13030 		/*
13031 		 * Default value of the number of drainers is the
13032 		 * number of cpus, subject to maximum of 8 drainers.
13033 		 */
13034 		if (boot_max_ncpus != -1)
13035 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13036 		else
13037 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13038 	}
13039 
13040 	ipst->ips_idl_tx_list =
13041 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13042 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13043 		itl_tx =  &ipst->ips_idl_tx_list[i];
13044 		itl_tx->txl_drain_list =
13045 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13046 		    sizeof (idl_t), KM_SLEEP);
13047 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13048 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13049 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13050 			    MUTEX_DEFAULT, NULL);
13051 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13052 		}
13053 	}
13054 }
13055 
13056 static void
13057 conn_drain_fini(ip_stack_t *ipst)
13058 {
13059 	int i;
13060 	idl_tx_list_t *itl_tx;
13061 
13062 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13063 		itl_tx =  &ipst->ips_idl_tx_list[i];
13064 		kmem_free(itl_tx->txl_drain_list,
13065 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13066 	}
13067 	kmem_free(ipst->ips_idl_tx_list,
13068 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13069 	ipst->ips_idl_tx_list = NULL;
13070 }
13071 
13072 /*
13073  * Flow control has blocked us from proceeding.  Insert the given conn in one
13074  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13075  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13076  * will call conn_walk_drain().  See the flow control notes at the top of this
13077  * file for more details.
13078  */
13079 void
13080 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13081 {
13082 	idl_t	*idl = tx_list->txl_drain_list;
13083 	uint_t	index;
13084 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13085 
13086 	mutex_enter(&connp->conn_lock);
13087 	if (connp->conn_state_flags & CONN_CLOSING) {
13088 		/*
13089 		 * The conn is closing as a result of which CONN_CLOSING
13090 		 * is set. Return.
13091 		 */
13092 		mutex_exit(&connp->conn_lock);
13093 		return;
13094 	} else if (connp->conn_idl == NULL) {
13095 		/*
13096 		 * Assign the next drain list round robin. We dont' use
13097 		 * a lock, and thus it may not be strictly round robin.
13098 		 * Atomicity of load/stores is enough to make sure that
13099 		 * conn_drain_list_index is always within bounds.
13100 		 */
13101 		index = tx_list->txl_drain_index;
13102 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13103 		connp->conn_idl = &tx_list->txl_drain_list[index];
13104 		index++;
13105 		if (index == ipst->ips_conn_drain_list_cnt)
13106 			index = 0;
13107 		tx_list->txl_drain_index = index;
13108 	} else {
13109 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13110 	}
13111 	mutex_exit(&connp->conn_lock);
13112 
13113 	idl = connp->conn_idl;
13114 	mutex_enter(&idl->idl_lock);
13115 	if ((connp->conn_drain_prev != NULL) ||
13116 	    (connp->conn_state_flags & CONN_CLOSING)) {
13117 		/*
13118 		 * The conn is either already in the drain list or closing.
13119 		 * (We needed to check for CONN_CLOSING again since close can
13120 		 * sneak in between dropping conn_lock and acquiring idl_lock.)
13121 		 */
13122 		mutex_exit(&idl->idl_lock);
13123 		return;
13124 	}
13125 
13126 	/*
13127 	 * The conn is not in the drain list. Insert it at the
13128 	 * tail of the drain list. The drain list is circular
13129 	 * and doubly linked. idl_conn points to the 1st element
13130 	 * in the list.
13131 	 */
13132 	if (idl->idl_conn == NULL) {
13133 		idl->idl_conn = connp;
13134 		connp->conn_drain_next = connp;
13135 		connp->conn_drain_prev = connp;
13136 	} else {
13137 		conn_t *head = idl->idl_conn;
13138 
13139 		connp->conn_drain_next = head;
13140 		connp->conn_drain_prev = head->conn_drain_prev;
13141 		head->conn_drain_prev->conn_drain_next = connp;
13142 		head->conn_drain_prev = connp;
13143 	}
13144 	/*
13145 	 * For non streams based sockets assert flow control.
13146 	 */
13147 	conn_setqfull(connp, NULL);
13148 	mutex_exit(&idl->idl_lock);
13149 }
13150 
13151 static void
13152 conn_drain_remove(conn_t *connp)
13153 {
13154 	idl_t *idl = connp->conn_idl;
13155 
13156 	if (idl != NULL) {
13157 		/*
13158 		 * Remove ourself from the drain list.
13159 		 */
13160 		if (connp->conn_drain_next == connp) {
13161 			/* Singleton in the list */
13162 			ASSERT(connp->conn_drain_prev == connp);
13163 			idl->idl_conn = NULL;
13164 		} else {
13165 			connp->conn_drain_prev->conn_drain_next =
13166 			    connp->conn_drain_next;
13167 			connp->conn_drain_next->conn_drain_prev =
13168 			    connp->conn_drain_prev;
13169 			if (idl->idl_conn == connp)
13170 				idl->idl_conn = connp->conn_drain_next;
13171 		}
13172 
13173 		/*
13174 		 * NOTE: because conn_idl is associated with a specific drain
13175 		 * list which in turn is tied to the index the TX ring
13176 		 * (txl_cookie) hashes to, and because the TX ring can change
13177 		 * over the lifetime of the conn_t, we must clear conn_idl so
13178 		 * a subsequent conn_drain_insert() will set conn_idl again
13179 		 * based on the latest txl_cookie.
13180 		 */
13181 		connp->conn_idl = NULL;
13182 	}
13183 	connp->conn_drain_next = NULL;
13184 	connp->conn_drain_prev = NULL;
13185 
13186 	conn_clrqfull(connp, NULL);
13187 	/*
13188 	 * For streams based sockets open up flow control.
13189 	 */
13190 	if (!IPCL_IS_NONSTR(connp))
13191 		enableok(connp->conn_wq);
13192 }
13193 
13194 /*
13195  * This conn is closing, and we are called from ip_close. OR
13196  * this conn is draining because flow-control on the ill has been relieved.
13197  *
13198  * We must also need to remove conn's on this idl from the list, and also
13199  * inform the sockfs upcalls about the change in flow-control.
13200  */
13201 static void
13202 conn_drain(conn_t *connp, boolean_t closing)
13203 {
13204 	idl_t *idl;
13205 	conn_t *next_connp;
13206 
13207 	/*
13208 	 * connp->conn_idl is stable at this point, and no lock is needed
13209 	 * to check it. If we are called from ip_close, close has already
13210 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13211 	 * called us only because conn_idl is non-null. If we are called thru
13212 	 * service, conn_idl could be null, but it cannot change because
13213 	 * service is single-threaded per queue, and there cannot be another
13214 	 * instance of service trying to call conn_drain_insert on this conn
13215 	 * now.
13216 	 */
13217 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13218 
13219 	/*
13220 	 * If the conn doesn't exist or is not on a drain list, bail.
13221 	 */
13222 	if (connp == NULL || connp->conn_idl == NULL ||
13223 	    connp->conn_drain_prev == NULL) {
13224 		return;
13225 	}
13226 
13227 	idl = connp->conn_idl;
13228 	ASSERT(MUTEX_HELD(&idl->idl_lock));
13229 
13230 	if (!closing) {
13231 		next_connp = connp->conn_drain_next;
13232 		while (next_connp != connp) {
13233 			conn_t *delconnp = next_connp;
13234 
13235 			next_connp = next_connp->conn_drain_next;
13236 			conn_drain_remove(delconnp);
13237 		}
13238 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13239 	}
13240 	conn_drain_remove(connp);
13241 }
13242 
13243 /*
13244  * Write service routine. Shared perimeter entry point.
13245  * The device queue's messages has fallen below the low water mark and STREAMS
13246  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13247  * each waiting conn.
13248  */
13249 void
13250 ip_wsrv(queue_t *q)
13251 {
13252 	ill_t	*ill;
13253 
13254 	ill = (ill_t *)q->q_ptr;
13255 	if (ill->ill_state_flags == 0) {
13256 		ip_stack_t *ipst = ill->ill_ipst;
13257 
13258 		/*
13259 		 * The device flow control has opened up.
13260 		 * Walk through conn drain lists and qenable the
13261 		 * first conn in each list. This makes sense only
13262 		 * if the stream is fully plumbed and setup.
13263 		 * Hence the ill_state_flags check above.
13264 		 */
13265 		ip1dbg(("ip_wsrv: walking\n"));
13266 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13267 		enableok(ill->ill_wq);
13268 	}
13269 }
13270 
13271 /*
13272  * Callback to disable flow control in IP.
13273  *
13274  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13275  * is enabled.
13276  *
13277  * When MAC_TX() is not able to send any more packets, dld sets its queue
13278  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13279  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13280  * function and wakes up corresponding mac worker threads, which in turn
13281  * calls this callback function, and disables flow control.
13282  */
13283 void
13284 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13285 {
13286 	ill_t *ill = (ill_t *)arg;
13287 	ip_stack_t *ipst = ill->ill_ipst;
13288 	idl_tx_list_t *idl_txl;
13289 
13290 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13291 	mutex_enter(&idl_txl->txl_lock);
13292 	/* add code to to set a flag to indicate idl_txl is enabled */
13293 	conn_walk_drain(ipst, idl_txl);
13294 	mutex_exit(&idl_txl->txl_lock);
13295 }
13296 
13297 /*
13298  * Flow control has been relieved and STREAMS has backenabled us; drain
13299  * all the conn lists on `tx_list'.
13300  */
13301 static void
13302 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13303 {
13304 	int i;
13305 	idl_t *idl;
13306 
13307 	IP_STAT(ipst, ip_conn_walk_drain);
13308 
13309 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13310 		idl = &tx_list->txl_drain_list[i];
13311 		mutex_enter(&idl->idl_lock);
13312 		conn_drain(idl->idl_conn, B_FALSE);
13313 		mutex_exit(&idl->idl_lock);
13314 	}
13315 }
13316 
13317 /*
13318  * Determine if the ill and multicast aspects of that packets
13319  * "matches" the conn.
13320  */
13321 boolean_t
13322 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13323 {
13324 	ill_t		*ill = ira->ira_rill;
13325 	zoneid_t	zoneid = ira->ira_zoneid;
13326 	uint_t		in_ifindex;
13327 	ipaddr_t	dst, src;
13328 
13329 	dst = ipha->ipha_dst;
13330 	src = ipha->ipha_src;
13331 
13332 	/*
13333 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13334 	 * unicast, broadcast and multicast reception to
13335 	 * conn_incoming_ifindex.
13336 	 * conn_wantpacket is called for unicast, broadcast and
13337 	 * multicast packets.
13338 	 */
13339 	in_ifindex = connp->conn_incoming_ifindex;
13340 
13341 	/* mpathd can bind to the under IPMP interface, which we allow */
13342 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13343 		if (!IS_UNDER_IPMP(ill))
13344 			return (B_FALSE);
13345 
13346 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13347 			return (B_FALSE);
13348 	}
13349 
13350 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13351 		return (B_FALSE);
13352 
13353 	if (!(ira->ira_flags & IRAF_MULTICAST))
13354 		return (B_TRUE);
13355 
13356 	if (connp->conn_multi_router) {
13357 		/* multicast packet and multicast router socket: send up */
13358 		return (B_TRUE);
13359 	}
13360 
13361 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13362 	    ipha->ipha_protocol == IPPROTO_RSVP)
13363 		return (B_TRUE);
13364 
13365 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13366 }
13367 
13368 void
13369 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13370 {
13371 	if (IPCL_IS_NONSTR(connp)) {
13372 		(*connp->conn_upcalls->su_txq_full)
13373 		    (connp->conn_upper_handle, B_TRUE);
13374 		if (flow_stopped != NULL)
13375 			*flow_stopped = B_TRUE;
13376 	} else {
13377 		queue_t *q = connp->conn_wq;
13378 
13379 		ASSERT(q != NULL);
13380 		if (!(q->q_flag & QFULL)) {
13381 			mutex_enter(QLOCK(q));
13382 			if (!(q->q_flag & QFULL)) {
13383 				/* still need to set QFULL */
13384 				q->q_flag |= QFULL;
13385 				/* set flow_stopped to true under QLOCK */
13386 				if (flow_stopped != NULL)
13387 					*flow_stopped = B_TRUE;
13388 				mutex_exit(QLOCK(q));
13389 			} else {
13390 				/* flow_stopped is left unchanged */
13391 				mutex_exit(QLOCK(q));
13392 			}
13393 		}
13394 	}
13395 }
13396 
13397 void
13398 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13399 {
13400 	if (IPCL_IS_NONSTR(connp)) {
13401 		(*connp->conn_upcalls->su_txq_full)
13402 		    (connp->conn_upper_handle, B_FALSE);
13403 		if (flow_stopped != NULL)
13404 			*flow_stopped = B_FALSE;
13405 	} else {
13406 		queue_t *q = connp->conn_wq;
13407 
13408 		ASSERT(q != NULL);
13409 		if (q->q_flag & QFULL) {
13410 			mutex_enter(QLOCK(q));
13411 			if (q->q_flag & QFULL) {
13412 				q->q_flag &= ~QFULL;
13413 				/* set flow_stopped to false under QLOCK */
13414 				if (flow_stopped != NULL)
13415 					*flow_stopped = B_FALSE;
13416 				mutex_exit(QLOCK(q));
13417 				if (q->q_flag & QWANTW)
13418 					qbackenable(q, 0);
13419 			} else {
13420 				/* flow_stopped is left unchanged */
13421 				mutex_exit(QLOCK(q));
13422 			}
13423 		}
13424 	}
13425 
13426 	mutex_enter(&connp->conn_lock);
13427 	connp->conn_blocked = B_FALSE;
13428 	mutex_exit(&connp->conn_lock);
13429 }
13430 
13431 /*
13432  * Return the length in bytes of the IPv4 headers (base header, label, and
13433  * other IP options) that will be needed based on the
13434  * ip_pkt_t structure passed by the caller.
13435  *
13436  * The returned length does not include the length of the upper level
13437  * protocol (ULP) header.
13438  * The caller needs to check that the length doesn't exceed the max for IPv4.
13439  */
13440 int
13441 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13442 {
13443 	int len;
13444 
13445 	len = IP_SIMPLE_HDR_LENGTH;
13446 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13447 		ASSERT(ipp->ipp_label_len_v4 != 0);
13448 		/* We need to round up here */
13449 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13450 	}
13451 
13452 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13453 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13454 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13455 		len += ipp->ipp_ipv4_options_len;
13456 	}
13457 	return (len);
13458 }
13459 
13460 /*
13461  * All-purpose routine to build an IPv4 header with options based
13462  * on the abstract ip_pkt_t.
13463  *
13464  * The caller has to set the source and destination address as well as
13465  * ipha_length. The caller has to massage any source route and compensate
13466  * for the ULP pseudo-header checksum due to the source route.
13467  */
13468 void
13469 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13470     uint8_t protocol)
13471 {
13472 	ipha_t	*ipha = (ipha_t *)buf;
13473 	uint8_t *cp;
13474 
13475 	/* Initialize IPv4 header */
13476 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13477 	ipha->ipha_length = 0;	/* Caller will set later */
13478 	ipha->ipha_ident = 0;
13479 	ipha->ipha_fragment_offset_and_flags = 0;
13480 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13481 	ipha->ipha_protocol = protocol;
13482 	ipha->ipha_hdr_checksum = 0;
13483 
13484 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13485 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13486 		ipha->ipha_src = ipp->ipp_addr_v4;
13487 
13488 	cp = (uint8_t *)&ipha[1];
13489 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13490 		ASSERT(ipp->ipp_label_len_v4 != 0);
13491 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13492 		cp += ipp->ipp_label_len_v4;
13493 		/* We need to round up here */
13494 		while ((uintptr_t)cp & 0x3) {
13495 			*cp++ = IPOPT_NOP;
13496 		}
13497 	}
13498 
13499 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13500 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13501 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13502 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13503 		cp += ipp->ipp_ipv4_options_len;
13504 	}
13505 	ipha->ipha_version_and_hdr_length =
13506 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13507 
13508 	ASSERT((int)(cp - buf) == buf_len);
13509 }
13510 
13511 /* Allocate the private structure */
13512 static int
13513 ip_priv_alloc(void **bufp)
13514 {
13515 	void	*buf;
13516 
13517 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13518 		return (ENOMEM);
13519 
13520 	*bufp = buf;
13521 	return (0);
13522 }
13523 
13524 /* Function to delete the private structure */
13525 void
13526 ip_priv_free(void *buf)
13527 {
13528 	ASSERT(buf != NULL);
13529 	kmem_free(buf, sizeof (ip_priv_t));
13530 }
13531 
13532 /*
13533  * The entry point for IPPF processing.
13534  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13535  * routine just returns.
13536  *
13537  * When called, ip_process generates an ipp_packet_t structure
13538  * which holds the state information for this packet and invokes the
13539  * the classifier (via ipp_packet_process). The classification, depending on
13540  * configured filters, results in a list of actions for this packet. Invoking
13541  * an action may cause the packet to be dropped, in which case we return NULL.
13542  * proc indicates the callout position for
13543  * this packet and ill is the interface this packet arrived on or will leave
13544  * on (inbound and outbound resp.).
13545  *
13546  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13547  * on the ill corrsponding to the destination IP address.
13548  */
13549 mblk_t *
13550 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13551 {
13552 	ip_priv_t	*priv;
13553 	ipp_action_id_t	aid;
13554 	int		rc = 0;
13555 	ipp_packet_t	*pp;
13556 
13557 	/* If the classifier is not loaded, return  */
13558 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13559 		return (mp);
13560 	}
13561 
13562 	ASSERT(mp != NULL);
13563 
13564 	/* Allocate the packet structure */
13565 	rc = ipp_packet_alloc(&pp, "ip", aid);
13566 	if (rc != 0)
13567 		goto drop;
13568 
13569 	/* Allocate the private structure */
13570 	rc = ip_priv_alloc((void **)&priv);
13571 	if (rc != 0) {
13572 		ipp_packet_free(pp);
13573 		goto drop;
13574 	}
13575 	priv->proc = proc;
13576 	priv->ill_index = ill_get_upper_ifindex(rill);
13577 
13578 	ipp_packet_set_private(pp, priv, ip_priv_free);
13579 	ipp_packet_set_data(pp, mp);
13580 
13581 	/* Invoke the classifier */
13582 	rc = ipp_packet_process(&pp);
13583 	if (pp != NULL) {
13584 		mp = ipp_packet_get_data(pp);
13585 		ipp_packet_free(pp);
13586 		if (rc != 0)
13587 			goto drop;
13588 		return (mp);
13589 	} else {
13590 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13591 		mp = NULL;
13592 	}
13593 drop:
13594 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13595 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13596 		ip_drop_input("ip_process", mp, ill);
13597 	} else {
13598 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13599 		ip_drop_output("ip_process", mp, ill);
13600 	}
13601 	freemsg(mp);
13602 	return (NULL);
13603 }
13604 
13605 /*
13606  * Propagate a multicast group membership operation (add/drop) on
13607  * all the interfaces crossed by the related multirt routes.
13608  * The call is considered successful if the operation succeeds
13609  * on at least one interface.
13610  *
13611  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13612  * multicast addresses with the ire argument being the first one.
13613  * We walk the bucket to find all the of those.
13614  *
13615  * Common to IPv4 and IPv6.
13616  */
13617 static int
13618 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13619     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13620     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13621     mcast_record_t fmode, const in6_addr_t *v6src)
13622 {
13623 	ire_t		*ire_gw;
13624 	irb_t		*irb;
13625 	int		ifindex;
13626 	int		error = 0;
13627 	int		result;
13628 	ip_stack_t	*ipst = ire->ire_ipst;
13629 	ipaddr_t	group;
13630 	boolean_t	isv6;
13631 	int		match_flags;
13632 
13633 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13634 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13635 		isv6 = B_FALSE;
13636 	} else {
13637 		isv6 = B_TRUE;
13638 	}
13639 
13640 	irb = ire->ire_bucket;
13641 	ASSERT(irb != NULL);
13642 
13643 	result = 0;
13644 	irb_refhold(irb);
13645 	for (; ire != NULL; ire = ire->ire_next) {
13646 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13647 			continue;
13648 
13649 		/* We handle -ifp routes by matching on the ill if set */
13650 		match_flags = MATCH_IRE_TYPE;
13651 		if (ire->ire_ill != NULL)
13652 			match_flags |= MATCH_IRE_ILL;
13653 
13654 		if (isv6) {
13655 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13656 				continue;
13657 
13658 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13659 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13660 			    match_flags, 0, ipst, NULL);
13661 		} else {
13662 			if (ire->ire_addr != group)
13663 				continue;
13664 
13665 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13666 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13667 			    match_flags, 0, ipst, NULL);
13668 		}
13669 		/* No interface route exists for the gateway; skip this ire. */
13670 		if (ire_gw == NULL)
13671 			continue;
13672 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13673 			ire_refrele(ire_gw);
13674 			continue;
13675 		}
13676 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13677 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13678 
13679 		/*
13680 		 * The operation is considered a success if
13681 		 * it succeeds at least once on any one interface.
13682 		 */
13683 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13684 		    fmode, v6src);
13685 		if (error == 0)
13686 			result = CGTP_MCAST_SUCCESS;
13687 
13688 		ire_refrele(ire_gw);
13689 	}
13690 	irb_refrele(irb);
13691 	/*
13692 	 * Consider the call as successful if we succeeded on at least
13693 	 * one interface. Otherwise, return the last encountered error.
13694 	 */
13695 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13696 }
13697 
13698 /*
13699  * Return the expected CGTP hooks version number.
13700  */
13701 int
13702 ip_cgtp_filter_supported(void)
13703 {
13704 	return (ip_cgtp_filter_rev);
13705 }
13706 
13707 /*
13708  * CGTP hooks can be registered by invoking this function.
13709  * Checks that the version number matches.
13710  */
13711 int
13712 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13713 {
13714 	netstack_t *ns;
13715 	ip_stack_t *ipst;
13716 
13717 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13718 		return (ENOTSUP);
13719 
13720 	ns = netstack_find_by_stackid(stackid);
13721 	if (ns == NULL)
13722 		return (EINVAL);
13723 	ipst = ns->netstack_ip;
13724 	ASSERT(ipst != NULL);
13725 
13726 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13727 		netstack_rele(ns);
13728 		return (EALREADY);
13729 	}
13730 
13731 	ipst->ips_ip_cgtp_filter_ops = ops;
13732 
13733 	ill_set_inputfn_all(ipst);
13734 
13735 	netstack_rele(ns);
13736 	return (0);
13737 }
13738 
13739 /*
13740  * CGTP hooks can be unregistered by invoking this function.
13741  * Returns ENXIO if there was no registration.
13742  * Returns EBUSY if the ndd variable has not been turned off.
13743  */
13744 int
13745 ip_cgtp_filter_unregister(netstackid_t stackid)
13746 {
13747 	netstack_t *ns;
13748 	ip_stack_t *ipst;
13749 
13750 	ns = netstack_find_by_stackid(stackid);
13751 	if (ns == NULL)
13752 		return (EINVAL);
13753 	ipst = ns->netstack_ip;
13754 	ASSERT(ipst != NULL);
13755 
13756 	if (ipst->ips_ip_cgtp_filter) {
13757 		netstack_rele(ns);
13758 		return (EBUSY);
13759 	}
13760 
13761 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13762 		netstack_rele(ns);
13763 		return (ENXIO);
13764 	}
13765 	ipst->ips_ip_cgtp_filter_ops = NULL;
13766 
13767 	ill_set_inputfn_all(ipst);
13768 
13769 	netstack_rele(ns);
13770 	return (0);
13771 }
13772 
13773 /*
13774  * Check whether there is a CGTP filter registration.
13775  * Returns non-zero if there is a registration, otherwise returns zero.
13776  * Note: returns zero if bad stackid.
13777  */
13778 int
13779 ip_cgtp_filter_is_registered(netstackid_t stackid)
13780 {
13781 	netstack_t *ns;
13782 	ip_stack_t *ipst;
13783 	int ret;
13784 
13785 	ns = netstack_find_by_stackid(stackid);
13786 	if (ns == NULL)
13787 		return (0);
13788 	ipst = ns->netstack_ip;
13789 	ASSERT(ipst != NULL);
13790 
13791 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13792 		ret = 1;
13793 	else
13794 		ret = 0;
13795 
13796 	netstack_rele(ns);
13797 	return (ret);
13798 }
13799 
13800 static int
13801 ip_squeue_switch(int val)
13802 {
13803 	int rval;
13804 
13805 	switch (val) {
13806 	case IP_SQUEUE_ENTER_NODRAIN:
13807 		rval = SQ_NODRAIN;
13808 		break;
13809 	case IP_SQUEUE_ENTER:
13810 		rval = SQ_PROCESS;
13811 		break;
13812 	case IP_SQUEUE_FILL:
13813 	default:
13814 		rval = SQ_FILL;
13815 		break;
13816 	}
13817 	return (rval);
13818 }
13819 
13820 static void *
13821 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13822 {
13823 	kstat_t *ksp;
13824 
13825 	ip_stat_t template = {
13826 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
13827 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
13828 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
13829 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13830 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13831 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13832 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13833 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13834 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13835 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13836 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13837 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13838 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13839 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13840 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13841 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13842 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13843 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13844 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13845 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13846 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13847 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13848 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13849 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13850 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13851 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13852 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13853 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13854 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13855 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13856 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
13857 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
13858 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
13859 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
13860 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
13861 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
13862 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
13863 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
13864 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
13865 	};
13866 
13867 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13868 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13869 	    KSTAT_FLAG_VIRTUAL, stackid);
13870 
13871 	if (ksp == NULL)
13872 		return (NULL);
13873 
13874 	bcopy(&template, ip_statisticsp, sizeof (template));
13875 	ksp->ks_data = (void *)ip_statisticsp;
13876 	ksp->ks_private = (void *)(uintptr_t)stackid;
13877 
13878 	kstat_install(ksp);
13879 	return (ksp);
13880 }
13881 
13882 static void
13883 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13884 {
13885 	if (ksp != NULL) {
13886 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13887 		kstat_delete_netstack(ksp, stackid);
13888 	}
13889 }
13890 
13891 static void *
13892 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13893 {
13894 	kstat_t	*ksp;
13895 
13896 	ip_named_kstat_t template = {
13897 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
13898 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
13899 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
13900 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
13901 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
13902 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
13903 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
13904 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
13905 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
13906 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
13907 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
13908 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
13909 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
13910 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
13911 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
13912 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
13913 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
13914 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
13915 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
13916 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
13917 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
13918 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
13919 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
13920 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
13921 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
13922 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
13923 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
13924 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
13925 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
13926 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
13927 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
13928 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
13929 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
13930 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
13931 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
13932 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
13933 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
13934 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
13935 	};
13936 
13937 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
13938 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
13939 	if (ksp == NULL || ksp->ks_data == NULL)
13940 		return (NULL);
13941 
13942 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
13943 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
13944 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
13945 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
13946 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
13947 
13948 	template.netToMediaEntrySize.value.i32 =
13949 	    sizeof (mib2_ipNetToMediaEntry_t);
13950 
13951 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
13952 
13953 	bcopy(&template, ksp->ks_data, sizeof (template));
13954 	ksp->ks_update = ip_kstat_update;
13955 	ksp->ks_private = (void *)(uintptr_t)stackid;
13956 
13957 	kstat_install(ksp);
13958 	return (ksp);
13959 }
13960 
13961 static void
13962 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
13963 {
13964 	if (ksp != NULL) {
13965 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13966 		kstat_delete_netstack(ksp, stackid);
13967 	}
13968 }
13969 
13970 static int
13971 ip_kstat_update(kstat_t *kp, int rw)
13972 {
13973 	ip_named_kstat_t *ipkp;
13974 	mib2_ipIfStatsEntry_t ipmib;
13975 	ill_walk_context_t ctx;
13976 	ill_t *ill;
13977 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
13978 	netstack_t	*ns;
13979 	ip_stack_t	*ipst;
13980 
13981 	if (kp == NULL || kp->ks_data == NULL)
13982 		return (EIO);
13983 
13984 	if (rw == KSTAT_WRITE)
13985 		return (EACCES);
13986 
13987 	ns = netstack_find_by_stackid(stackid);
13988 	if (ns == NULL)
13989 		return (-1);
13990 	ipst = ns->netstack_ip;
13991 	if (ipst == NULL) {
13992 		netstack_rele(ns);
13993 		return (-1);
13994 	}
13995 	ipkp = (ip_named_kstat_t *)kp->ks_data;
13996 
13997 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
13998 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
13999 	ill = ILL_START_WALK_V4(&ctx, ipst);
14000 	for (; ill != NULL; ill = ill_next(&ctx, ill))
14001 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14002 	rw_exit(&ipst->ips_ill_g_lock);
14003 
14004 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
14005 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
14006 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
14007 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
14008 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
14009 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14010 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
14011 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
14012 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
14013 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
14014 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
14015 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
14016 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
14017 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
14018 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
14019 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
14020 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
14021 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
14022 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
14023 
14024 	ipkp->routingDiscards.value.ui32 =	0;
14025 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
14026 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
14027 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
14028 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
14029 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
14030 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
14031 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
14032 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
14033 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
14034 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
14035 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
14036 
14037 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
14038 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
14039 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14040 
14041 	netstack_rele(ns);
14042 
14043 	return (0);
14044 }
14045 
14046 static void *
14047 icmp_kstat_init(netstackid_t stackid)
14048 {
14049 	kstat_t	*ksp;
14050 
14051 	icmp_named_kstat_t template = {
14052 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14053 		{ "inErrors",		KSTAT_DATA_UINT32 },
14054 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14055 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14056 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14057 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14058 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14059 		{ "inEchos",		KSTAT_DATA_UINT32 },
14060 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14061 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14062 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14063 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14064 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14065 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14066 		{ "outErrors",		KSTAT_DATA_UINT32 },
14067 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14068 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14069 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14070 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14071 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14072 		{ "outEchos",		KSTAT_DATA_UINT32 },
14073 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14074 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14075 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14076 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14077 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14078 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14079 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14080 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14081 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14082 		{ "outDrops",		KSTAT_DATA_UINT32 },
14083 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14084 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14085 	};
14086 
14087 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14088 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14089 	if (ksp == NULL || ksp->ks_data == NULL)
14090 		return (NULL);
14091 
14092 	bcopy(&template, ksp->ks_data, sizeof (template));
14093 
14094 	ksp->ks_update = icmp_kstat_update;
14095 	ksp->ks_private = (void *)(uintptr_t)stackid;
14096 
14097 	kstat_install(ksp);
14098 	return (ksp);
14099 }
14100 
14101 static void
14102 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14103 {
14104 	if (ksp != NULL) {
14105 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14106 		kstat_delete_netstack(ksp, stackid);
14107 	}
14108 }
14109 
14110 static int
14111 icmp_kstat_update(kstat_t *kp, int rw)
14112 {
14113 	icmp_named_kstat_t *icmpkp;
14114 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14115 	netstack_t	*ns;
14116 	ip_stack_t	*ipst;
14117 
14118 	if ((kp == NULL) || (kp->ks_data == NULL))
14119 		return (EIO);
14120 
14121 	if (rw == KSTAT_WRITE)
14122 		return (EACCES);
14123 
14124 	ns = netstack_find_by_stackid(stackid);
14125 	if (ns == NULL)
14126 		return (-1);
14127 	ipst = ns->netstack_ip;
14128 	if (ipst == NULL) {
14129 		netstack_rele(ns);
14130 		return (-1);
14131 	}
14132 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14133 
14134 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14135 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14136 	icmpkp->inDestUnreachs.value.ui32 =
14137 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14138 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14139 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14140 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14141 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14142 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14143 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14144 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14145 	icmpkp->inTimestampReps.value.ui32 =
14146 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14147 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14148 	icmpkp->inAddrMaskReps.value.ui32 =
14149 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14150 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14151 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14152 	icmpkp->outDestUnreachs.value.ui32 =
14153 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14154 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14155 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14156 	icmpkp->outSrcQuenchs.value.ui32 =
14157 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14158 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14159 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14160 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14161 	icmpkp->outTimestamps.value.ui32 =
14162 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14163 	icmpkp->outTimestampReps.value.ui32 =
14164 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14165 	icmpkp->outAddrMasks.value.ui32 =
14166 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14167 	icmpkp->outAddrMaskReps.value.ui32 =
14168 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14169 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14170 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14171 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14172 	icmpkp->outFragNeeded.value.ui32 =
14173 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14174 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14175 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14176 	icmpkp->inBadRedirects.value.ui32 =
14177 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14178 
14179 	netstack_rele(ns);
14180 	return (0);
14181 }
14182 
14183 /*
14184  * This is the fanout function for raw socket opened for SCTP.  Note
14185  * that it is called after SCTP checks that there is no socket which
14186  * wants a packet.  Then before SCTP handles this out of the blue packet,
14187  * this function is called to see if there is any raw socket for SCTP.
14188  * If there is and it is bound to the correct address, the packet will
14189  * be sent to that socket.  Note that only one raw socket can be bound to
14190  * a port.  This is assured in ipcl_sctp_hash_insert();
14191  */
14192 void
14193 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14194     ip_recv_attr_t *ira)
14195 {
14196 	conn_t		*connp;
14197 	queue_t		*rq;
14198 	boolean_t	secure;
14199 	ill_t		*ill = ira->ira_ill;
14200 	ip_stack_t	*ipst = ill->ill_ipst;
14201 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14202 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14203 	iaflags_t	iraflags = ira->ira_flags;
14204 	ill_t		*rill = ira->ira_rill;
14205 
14206 	secure = iraflags & IRAF_IPSEC_SECURE;
14207 
14208 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14209 	    ira, ipst);
14210 	if (connp == NULL) {
14211 		/*
14212 		 * Although raw sctp is not summed, OOB chunks must be.
14213 		 * Drop the packet here if the sctp checksum failed.
14214 		 */
14215 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14216 			SCTPS_BUMP_MIB(sctps, sctpChecksumError);
14217 			freemsg(mp);
14218 			return;
14219 		}
14220 		ira->ira_ill = ira->ira_rill = NULL;
14221 		sctp_ootb_input(mp, ira, ipst);
14222 		ira->ira_ill = ill;
14223 		ira->ira_rill = rill;
14224 		return;
14225 	}
14226 	rq = connp->conn_rq;
14227 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14228 		CONN_DEC_REF(connp);
14229 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14230 		freemsg(mp);
14231 		return;
14232 	}
14233 	if (((iraflags & IRAF_IS_IPV4) ?
14234 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14235 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14236 	    secure) {
14237 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14238 		    ip6h, ira);
14239 		if (mp == NULL) {
14240 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14241 			/* Note that mp is NULL */
14242 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14243 			CONN_DEC_REF(connp);
14244 			return;
14245 		}
14246 	}
14247 
14248 	if (iraflags & IRAF_ICMP_ERROR) {
14249 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14250 	} else {
14251 		ill_t *rill = ira->ira_rill;
14252 
14253 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14254 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14255 		ira->ira_ill = ira->ira_rill = NULL;
14256 		(connp->conn_recv)(connp, mp, NULL, ira);
14257 		ira->ira_ill = ill;
14258 		ira->ira_rill = rill;
14259 	}
14260 	CONN_DEC_REF(connp);
14261 }
14262 
14263 /*
14264  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14265  * header before the ip payload.
14266  */
14267 static void
14268 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14269 {
14270 	int len = (mp->b_wptr - mp->b_rptr);
14271 	mblk_t *ip_mp;
14272 
14273 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14274 	if (is_fp_mp || len != fp_mp_len) {
14275 		if (len > fp_mp_len) {
14276 			/*
14277 			 * fastpath header and ip header in the first mblk
14278 			 */
14279 			mp->b_rptr += fp_mp_len;
14280 		} else {
14281 			/*
14282 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14283 			 * attach the fastpath header before ip header.
14284 			 */
14285 			ip_mp = mp->b_cont;
14286 			freeb(mp);
14287 			mp = ip_mp;
14288 			mp->b_rptr += (fp_mp_len - len);
14289 		}
14290 	} else {
14291 		ip_mp = mp->b_cont;
14292 		freeb(mp);
14293 		mp = ip_mp;
14294 	}
14295 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14296 	freemsg(mp);
14297 }
14298 
14299 /*
14300  * Normal post fragmentation function.
14301  *
14302  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14303  * using the same state machine.
14304  *
14305  * We return an error on failure. In particular we return EWOULDBLOCK
14306  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14307  * (currently by canputnext failure resulting in backenabling from GLD.)
14308  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14309  * indication that they can flow control until ip_wsrv() tells then to restart.
14310  *
14311  * If the nce passed by caller is incomplete, this function
14312  * queues the packet and if necessary, sends ARP request and bails.
14313  * If the Neighbor Cache passed is fully resolved, we simply prepend
14314  * the link-layer header to the packet, do ipsec hw acceleration
14315  * work if necessary, and send the packet out on the wire.
14316  */
14317 /* ARGSUSED6 */
14318 int
14319 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14320     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14321 {
14322 	queue_t		*wq;
14323 	ill_t		*ill = nce->nce_ill;
14324 	ip_stack_t	*ipst = ill->ill_ipst;
14325 	uint64_t	delta;
14326 	boolean_t	isv6 = ill->ill_isv6;
14327 	boolean_t	fp_mp;
14328 	ncec_t		*ncec = nce->nce_common;
14329 	int64_t		now = LBOLT_FASTPATH64;
14330 	boolean_t	is_probe;
14331 
14332 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14333 
14334 	ASSERT(mp != NULL);
14335 	ASSERT(mp->b_datap->db_type == M_DATA);
14336 	ASSERT(pkt_len == msgdsize(mp));
14337 
14338 	/*
14339 	 * If we have already been here and are coming back after ARP/ND.
14340 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14341 	 * in that case since they have seen the packet when it came here
14342 	 * the first time.
14343 	 */
14344 	if (ixaflags & IXAF_NO_TRACE)
14345 		goto sendit;
14346 
14347 	if (ixaflags & IXAF_IS_IPV4) {
14348 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14349 
14350 		ASSERT(!isv6);
14351 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14352 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14353 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14354 			int	error;
14355 
14356 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14357 			    ipst->ips_ipv4firewall_physical_out,
14358 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14359 			DTRACE_PROBE1(ip4__physical__out__end,
14360 			    mblk_t *, mp);
14361 			if (mp == NULL)
14362 				return (error);
14363 
14364 			/* The length could have changed */
14365 			pkt_len = msgdsize(mp);
14366 		}
14367 		if (ipst->ips_ip4_observe.he_interested) {
14368 			/*
14369 			 * Note that for TX the zoneid is the sending
14370 			 * zone, whether or not MLP is in play.
14371 			 * Since the szone argument is the IP zoneid (i.e.,
14372 			 * zero for exclusive-IP zones) and ipobs wants
14373 			 * the system zoneid, we map it here.
14374 			 */
14375 			szone = IP_REAL_ZONEID(szone, ipst);
14376 
14377 			/*
14378 			 * On the outbound path the destination zone will be
14379 			 * unknown as we're sending this packet out on the
14380 			 * wire.
14381 			 */
14382 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14383 			    ill, ipst);
14384 		}
14385 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14386 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14387 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14388 	} else {
14389 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14390 
14391 		ASSERT(isv6);
14392 		ASSERT(pkt_len ==
14393 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14394 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14395 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14396 			int	error;
14397 
14398 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14399 			    ipst->ips_ipv6firewall_physical_out,
14400 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14401 			DTRACE_PROBE1(ip6__physical__out__end,
14402 			    mblk_t *, mp);
14403 			if (mp == NULL)
14404 				return (error);
14405 
14406 			/* The length could have changed */
14407 			pkt_len = msgdsize(mp);
14408 		}
14409 		if (ipst->ips_ip6_observe.he_interested) {
14410 			/* See above */
14411 			szone = IP_REAL_ZONEID(szone, ipst);
14412 
14413 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14414 			    ill, ipst);
14415 		}
14416 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14417 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14418 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14419 	}
14420 
14421 sendit:
14422 	/*
14423 	 * We check the state without a lock because the state can never
14424 	 * move "backwards" to initial or incomplete.
14425 	 */
14426 	switch (ncec->ncec_state) {
14427 	case ND_REACHABLE:
14428 	case ND_STALE:
14429 	case ND_DELAY:
14430 	case ND_PROBE:
14431 		mp = ip_xmit_attach_llhdr(mp, nce);
14432 		if (mp == NULL) {
14433 			/*
14434 			 * ip_xmit_attach_llhdr has increased
14435 			 * ipIfStatsOutDiscards and called ip_drop_output()
14436 			 */
14437 			return (ENOBUFS);
14438 		}
14439 		/*
14440 		 * check if nce_fastpath completed and we tagged on a
14441 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14442 		 */
14443 		fp_mp = (mp->b_datap->db_type == M_DATA);
14444 
14445 		if (fp_mp &&
14446 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14447 			ill_dld_direct_t *idd;
14448 
14449 			idd = &ill->ill_dld_capab->idc_direct;
14450 			/*
14451 			 * Send the packet directly to DLD, where it
14452 			 * may be queued depending on the availability
14453 			 * of transmit resources at the media layer.
14454 			 * Return value should be taken into
14455 			 * account and flow control the TCP.
14456 			 */
14457 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14458 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14459 			    pkt_len);
14460 
14461 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14462 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14463 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14464 			} else {
14465 				uintptr_t cookie;
14466 
14467 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14468 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14469 					if (ixacookie != NULL)
14470 						*ixacookie = cookie;
14471 					return (EWOULDBLOCK);
14472 				}
14473 			}
14474 		} else {
14475 			wq = ill->ill_wq;
14476 
14477 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14478 			    !canputnext(wq)) {
14479 				if (ixacookie != NULL)
14480 					*ixacookie = 0;
14481 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14482 				    nce->nce_fp_mp != NULL ?
14483 				    MBLKL(nce->nce_fp_mp) : 0);
14484 				return (EWOULDBLOCK);
14485 			}
14486 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14487 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14488 			    pkt_len);
14489 			putnext(wq, mp);
14490 		}
14491 
14492 		/*
14493 		 * The rest of this function implements Neighbor Unreachability
14494 		 * detection. Determine if the ncec is eligible for NUD.
14495 		 */
14496 		if (ncec->ncec_flags & NCE_F_NONUD)
14497 			return (0);
14498 
14499 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14500 
14501 		/*
14502 		 * Check for upper layer advice
14503 		 */
14504 		if (ixaflags & IXAF_REACH_CONF) {
14505 			timeout_id_t tid;
14506 
14507 			/*
14508 			 * It should be o.k. to check the state without
14509 			 * a lock here, at most we lose an advice.
14510 			 */
14511 			ncec->ncec_last = TICK_TO_MSEC(now);
14512 			if (ncec->ncec_state != ND_REACHABLE) {
14513 				mutex_enter(&ncec->ncec_lock);
14514 				ncec->ncec_state = ND_REACHABLE;
14515 				tid = ncec->ncec_timeout_id;
14516 				ncec->ncec_timeout_id = 0;
14517 				mutex_exit(&ncec->ncec_lock);
14518 				(void) untimeout(tid);
14519 				if (ip_debug > 2) {
14520 					/* ip1dbg */
14521 					pr_addr_dbg("ip_xmit: state"
14522 					    " for %s changed to"
14523 					    " REACHABLE\n", AF_INET6,
14524 					    &ncec->ncec_addr);
14525 				}
14526 			}
14527 			return (0);
14528 		}
14529 
14530 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14531 		ip1dbg(("ip_xmit: delta = %" PRId64
14532 		    " ill_reachable_time = %d \n", delta,
14533 		    ill->ill_reachable_time));
14534 		if (delta > (uint64_t)ill->ill_reachable_time) {
14535 			mutex_enter(&ncec->ncec_lock);
14536 			switch (ncec->ncec_state) {
14537 			case ND_REACHABLE:
14538 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14539 				/* FALLTHROUGH */
14540 			case ND_STALE:
14541 				/*
14542 				 * ND_REACHABLE is identical to
14543 				 * ND_STALE in this specific case. If
14544 				 * reachable time has expired for this
14545 				 * neighbor (delta is greater than
14546 				 * reachable time), conceptually, the
14547 				 * neighbor cache is no longer in
14548 				 * REACHABLE state, but already in
14549 				 * STALE state.  So the correct
14550 				 * transition here is to ND_DELAY.
14551 				 */
14552 				ncec->ncec_state = ND_DELAY;
14553 				mutex_exit(&ncec->ncec_lock);
14554 				nce_restart_timer(ncec,
14555 				    ipst->ips_delay_first_probe_time);
14556 				if (ip_debug > 3) {
14557 					/* ip2dbg */
14558 					pr_addr_dbg("ip_xmit: state"
14559 					    " for %s changed to"
14560 					    " DELAY\n", AF_INET6,
14561 					    &ncec->ncec_addr);
14562 				}
14563 				break;
14564 			case ND_DELAY:
14565 			case ND_PROBE:
14566 				mutex_exit(&ncec->ncec_lock);
14567 				/* Timers have already started */
14568 				break;
14569 			case ND_UNREACHABLE:
14570 				/*
14571 				 * nce_timer has detected that this ncec
14572 				 * is unreachable and initiated deleting
14573 				 * this ncec.
14574 				 * This is a harmless race where we found the
14575 				 * ncec before it was deleted and have
14576 				 * just sent out a packet using this
14577 				 * unreachable ncec.
14578 				 */
14579 				mutex_exit(&ncec->ncec_lock);
14580 				break;
14581 			default:
14582 				ASSERT(0);
14583 				mutex_exit(&ncec->ncec_lock);
14584 			}
14585 		}
14586 		return (0);
14587 
14588 	case ND_INCOMPLETE:
14589 		/*
14590 		 * the state could have changed since we didn't hold the lock.
14591 		 * Re-verify state under lock.
14592 		 */
14593 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14594 		mutex_enter(&ncec->ncec_lock);
14595 		if (NCE_ISREACHABLE(ncec)) {
14596 			mutex_exit(&ncec->ncec_lock);
14597 			goto sendit;
14598 		}
14599 		/* queue the packet */
14600 		nce_queue_mp(ncec, mp, is_probe);
14601 		mutex_exit(&ncec->ncec_lock);
14602 		DTRACE_PROBE2(ip__xmit__incomplete,
14603 		    (ncec_t *), ncec, (mblk_t *), mp);
14604 		return (0);
14605 
14606 	case ND_INITIAL:
14607 		/*
14608 		 * State could have changed since we didn't hold the lock, so
14609 		 * re-verify state.
14610 		 */
14611 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14612 		mutex_enter(&ncec->ncec_lock);
14613 		if (NCE_ISREACHABLE(ncec))  {
14614 			mutex_exit(&ncec->ncec_lock);
14615 			goto sendit;
14616 		}
14617 		nce_queue_mp(ncec, mp, is_probe);
14618 		if (ncec->ncec_state == ND_INITIAL) {
14619 			ncec->ncec_state = ND_INCOMPLETE;
14620 			mutex_exit(&ncec->ncec_lock);
14621 			/*
14622 			 * figure out the source we want to use
14623 			 * and resolve it.
14624 			 */
14625 			ip_ndp_resolve(ncec);
14626 		} else  {
14627 			mutex_exit(&ncec->ncec_lock);
14628 		}
14629 		return (0);
14630 
14631 	case ND_UNREACHABLE:
14632 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14633 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14634 		    mp, ill);
14635 		freemsg(mp);
14636 		return (0);
14637 
14638 	default:
14639 		ASSERT(0);
14640 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14641 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14642 		    mp, ill);
14643 		freemsg(mp);
14644 		return (ENETUNREACH);
14645 	}
14646 }
14647 
14648 /*
14649  * Return B_TRUE if the buffers differ in length or content.
14650  * This is used for comparing extension header buffers.
14651  * Note that an extension header would be declared different
14652  * even if all that changed was the next header value in that header i.e.
14653  * what really changed is the next extension header.
14654  */
14655 boolean_t
14656 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14657     uint_t blen)
14658 {
14659 	if (!b_valid)
14660 		blen = 0;
14661 
14662 	if (alen != blen)
14663 		return (B_TRUE);
14664 	if (alen == 0)
14665 		return (B_FALSE);	/* Both zero length */
14666 	return (bcmp(abuf, bbuf, alen));
14667 }
14668 
14669 /*
14670  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14671  * Return B_FALSE if memory allocation fails - don't change any state!
14672  */
14673 boolean_t
14674 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14675     const void *src, uint_t srclen)
14676 {
14677 	void *dst;
14678 
14679 	if (!src_valid)
14680 		srclen = 0;
14681 
14682 	ASSERT(*dstlenp == 0);
14683 	if (src != NULL && srclen != 0) {
14684 		dst = mi_alloc(srclen, BPRI_MED);
14685 		if (dst == NULL)
14686 			return (B_FALSE);
14687 	} else {
14688 		dst = NULL;
14689 	}
14690 	if (*dstp != NULL)
14691 		mi_free(*dstp);
14692 	*dstp = dst;
14693 	*dstlenp = dst == NULL ? 0 : srclen;
14694 	return (B_TRUE);
14695 }
14696 
14697 /*
14698  * Replace what is in *dst, *dstlen with the source.
14699  * Assumes ip_allocbuf has already been called.
14700  */
14701 void
14702 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14703     const void *src, uint_t srclen)
14704 {
14705 	if (!src_valid)
14706 		srclen = 0;
14707 
14708 	ASSERT(*dstlenp == srclen);
14709 	if (src != NULL && srclen != 0)
14710 		bcopy(src, *dstp, srclen);
14711 }
14712 
14713 /*
14714  * Free the storage pointed to by the members of an ip_pkt_t.
14715  */
14716 void
14717 ip_pkt_free(ip_pkt_t *ipp)
14718 {
14719 	uint_t	fields = ipp->ipp_fields;
14720 
14721 	if (fields & IPPF_HOPOPTS) {
14722 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14723 		ipp->ipp_hopopts = NULL;
14724 		ipp->ipp_hopoptslen = 0;
14725 	}
14726 	if (fields & IPPF_RTHDRDSTOPTS) {
14727 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14728 		ipp->ipp_rthdrdstopts = NULL;
14729 		ipp->ipp_rthdrdstoptslen = 0;
14730 	}
14731 	if (fields & IPPF_DSTOPTS) {
14732 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14733 		ipp->ipp_dstopts = NULL;
14734 		ipp->ipp_dstoptslen = 0;
14735 	}
14736 	if (fields & IPPF_RTHDR) {
14737 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14738 		ipp->ipp_rthdr = NULL;
14739 		ipp->ipp_rthdrlen = 0;
14740 	}
14741 	if (fields & IPPF_IPV4_OPTIONS) {
14742 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14743 		ipp->ipp_ipv4_options = NULL;
14744 		ipp->ipp_ipv4_options_len = 0;
14745 	}
14746 	if (fields & IPPF_LABEL_V4) {
14747 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14748 		ipp->ipp_label_v4 = NULL;
14749 		ipp->ipp_label_len_v4 = 0;
14750 	}
14751 	if (fields & IPPF_LABEL_V6) {
14752 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14753 		ipp->ipp_label_v6 = NULL;
14754 		ipp->ipp_label_len_v6 = 0;
14755 	}
14756 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14757 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14758 }
14759 
14760 /*
14761  * Copy from src to dst and allocate as needed.
14762  * Returns zero or ENOMEM.
14763  *
14764  * The caller must initialize dst to zero.
14765  */
14766 int
14767 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14768 {
14769 	uint_t	fields = src->ipp_fields;
14770 
14771 	/* Start with fields that don't require memory allocation */
14772 	dst->ipp_fields = fields &
14773 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14774 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14775 
14776 	dst->ipp_addr = src->ipp_addr;
14777 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14778 	dst->ipp_hoplimit = src->ipp_hoplimit;
14779 	dst->ipp_tclass = src->ipp_tclass;
14780 	dst->ipp_type_of_service = src->ipp_type_of_service;
14781 
14782 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14783 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14784 		return (0);
14785 
14786 	if (fields & IPPF_HOPOPTS) {
14787 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14788 		if (dst->ipp_hopopts == NULL) {
14789 			ip_pkt_free(dst);
14790 			return (ENOMEM);
14791 		}
14792 		dst->ipp_fields |= IPPF_HOPOPTS;
14793 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14794 		    src->ipp_hopoptslen);
14795 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14796 	}
14797 	if (fields & IPPF_RTHDRDSTOPTS) {
14798 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14799 		    kmflag);
14800 		if (dst->ipp_rthdrdstopts == NULL) {
14801 			ip_pkt_free(dst);
14802 			return (ENOMEM);
14803 		}
14804 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14805 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14806 		    src->ipp_rthdrdstoptslen);
14807 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14808 	}
14809 	if (fields & IPPF_DSTOPTS) {
14810 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14811 		if (dst->ipp_dstopts == NULL) {
14812 			ip_pkt_free(dst);
14813 			return (ENOMEM);
14814 		}
14815 		dst->ipp_fields |= IPPF_DSTOPTS;
14816 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14817 		    src->ipp_dstoptslen);
14818 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14819 	}
14820 	if (fields & IPPF_RTHDR) {
14821 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14822 		if (dst->ipp_rthdr == NULL) {
14823 			ip_pkt_free(dst);
14824 			return (ENOMEM);
14825 		}
14826 		dst->ipp_fields |= IPPF_RTHDR;
14827 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14828 		    src->ipp_rthdrlen);
14829 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14830 	}
14831 	if (fields & IPPF_IPV4_OPTIONS) {
14832 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14833 		    kmflag);
14834 		if (dst->ipp_ipv4_options == NULL) {
14835 			ip_pkt_free(dst);
14836 			return (ENOMEM);
14837 		}
14838 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14839 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14840 		    src->ipp_ipv4_options_len);
14841 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14842 	}
14843 	if (fields & IPPF_LABEL_V4) {
14844 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14845 		if (dst->ipp_label_v4 == NULL) {
14846 			ip_pkt_free(dst);
14847 			return (ENOMEM);
14848 		}
14849 		dst->ipp_fields |= IPPF_LABEL_V4;
14850 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14851 		    src->ipp_label_len_v4);
14852 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14853 	}
14854 	if (fields & IPPF_LABEL_V6) {
14855 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14856 		if (dst->ipp_label_v6 == NULL) {
14857 			ip_pkt_free(dst);
14858 			return (ENOMEM);
14859 		}
14860 		dst->ipp_fields |= IPPF_LABEL_V6;
14861 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14862 		    src->ipp_label_len_v6);
14863 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14864 	}
14865 	if (fields & IPPF_FRAGHDR) {
14866 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14867 		if (dst->ipp_fraghdr == NULL) {
14868 			ip_pkt_free(dst);
14869 			return (ENOMEM);
14870 		}
14871 		dst->ipp_fields |= IPPF_FRAGHDR;
14872 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14873 		    src->ipp_fraghdrlen);
14874 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14875 	}
14876 	return (0);
14877 }
14878 
14879 /*
14880  * Returns INADDR_ANY if no source route
14881  */
14882 ipaddr_t
14883 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14884 {
14885 	ipaddr_t	nexthop = INADDR_ANY;
14886 	ipoptp_t	opts;
14887 	uchar_t		*opt;
14888 	uint8_t		optval;
14889 	uint8_t		optlen;
14890 	uint32_t	totallen;
14891 
14892 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14893 		return (INADDR_ANY);
14894 
14895 	totallen = ipp->ipp_ipv4_options_len;
14896 	if (totallen & 0x3)
14897 		return (INADDR_ANY);
14898 
14899 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14900 	    optval != IPOPT_EOL;
14901 	    optval = ipoptp_next(&opts)) {
14902 		opt = opts.ipoptp_cur;
14903 		switch (optval) {
14904 			uint8_t off;
14905 		case IPOPT_SSRR:
14906 		case IPOPT_LSRR:
14907 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14908 				break;
14909 			}
14910 			optlen = opts.ipoptp_len;
14911 			off = opt[IPOPT_OFFSET];
14912 			off--;
14913 			if (optlen < IP_ADDR_LEN ||
14914 			    off > optlen - IP_ADDR_LEN) {
14915 				/* End of source route */
14916 				break;
14917 			}
14918 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
14919 			if (nexthop == htonl(INADDR_LOOPBACK)) {
14920 				/* Ignore */
14921 				nexthop = INADDR_ANY;
14922 				break;
14923 			}
14924 			break;
14925 		}
14926 	}
14927 	return (nexthop);
14928 }
14929 
14930 /*
14931  * Reverse a source route.
14932  */
14933 void
14934 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
14935 {
14936 	ipaddr_t	tmp;
14937 	ipoptp_t	opts;
14938 	uchar_t		*opt;
14939 	uint8_t		optval;
14940 	uint32_t	totallen;
14941 
14942 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14943 		return;
14944 
14945 	totallen = ipp->ipp_ipv4_options_len;
14946 	if (totallen & 0x3)
14947 		return;
14948 
14949 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14950 	    optval != IPOPT_EOL;
14951 	    optval = ipoptp_next(&opts)) {
14952 		uint8_t off1, off2;
14953 
14954 		opt = opts.ipoptp_cur;
14955 		switch (optval) {
14956 		case IPOPT_SSRR:
14957 		case IPOPT_LSRR:
14958 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14959 				break;
14960 			}
14961 			off1 = IPOPT_MINOFF_SR - 1;
14962 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
14963 			while (off2 > off1) {
14964 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
14965 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
14966 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
14967 				off2 -= IP_ADDR_LEN;
14968 				off1 += IP_ADDR_LEN;
14969 			}
14970 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
14971 			break;
14972 		}
14973 	}
14974 }
14975 
14976 /*
14977  * Returns NULL if no routing header
14978  */
14979 in6_addr_t *
14980 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
14981 {
14982 	in6_addr_t	*nexthop = NULL;
14983 	ip6_rthdr0_t	*rthdr;
14984 
14985 	if (!(ipp->ipp_fields & IPPF_RTHDR))
14986 		return (NULL);
14987 
14988 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
14989 	if (rthdr->ip6r0_segleft == 0)
14990 		return (NULL);
14991 
14992 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
14993 	return (nexthop);
14994 }
14995 
14996 zoneid_t
14997 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
14998     zoneid_t lookup_zoneid)
14999 {
15000 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15001 	ire_t		*ire;
15002 	int		ire_flags = MATCH_IRE_TYPE;
15003 	zoneid_t	zoneid = ALL_ZONES;
15004 
15005 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15006 		return (ALL_ZONES);
15007 
15008 	if (lookup_zoneid != ALL_ZONES)
15009 		ire_flags |= MATCH_IRE_ZONEONLY;
15010 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15011 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15012 	if (ire != NULL) {
15013 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15014 		ire_refrele(ire);
15015 	}
15016 	return (zoneid);
15017 }
15018 
15019 zoneid_t
15020 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15021     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15022 {
15023 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15024 	ire_t		*ire;
15025 	int		ire_flags = MATCH_IRE_TYPE;
15026 	zoneid_t	zoneid = ALL_ZONES;
15027 
15028 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15029 		return (ALL_ZONES);
15030 
15031 	if (IN6_IS_ADDR_LINKLOCAL(addr))
15032 		ire_flags |= MATCH_IRE_ILL;
15033 
15034 	if (lookup_zoneid != ALL_ZONES)
15035 		ire_flags |= MATCH_IRE_ZONEONLY;
15036 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15037 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15038 	if (ire != NULL) {
15039 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15040 		ire_refrele(ire);
15041 	}
15042 	return (zoneid);
15043 }
15044 
15045 /*
15046  * IP obserability hook support functions.
15047  */
15048 static void
15049 ipobs_init(ip_stack_t *ipst)
15050 {
15051 	netid_t id;
15052 
15053 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15054 
15055 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15056 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15057 
15058 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15059 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15060 }
15061 
15062 static void
15063 ipobs_fini(ip_stack_t *ipst)
15064 {
15065 
15066 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15067 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15068 }
15069 
15070 /*
15071  * hook_pkt_observe_t is composed in network byte order so that the
15072  * entire mblk_t chain handed into hook_run can be used as-is.
15073  * The caveat is that use of the fields, such as the zone fields,
15074  * requires conversion into host byte order first.
15075  */
15076 void
15077 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15078     const ill_t *ill, ip_stack_t *ipst)
15079 {
15080 	hook_pkt_observe_t *hdr;
15081 	uint64_t grifindex;
15082 	mblk_t *imp;
15083 
15084 	imp = allocb(sizeof (*hdr), BPRI_HI);
15085 	if (imp == NULL)
15086 		return;
15087 
15088 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15089 	/*
15090 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15091 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15092 	 */
15093 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15094 	imp->b_cont = mp;
15095 
15096 	ASSERT(DB_TYPE(mp) == M_DATA);
15097 
15098 	if (IS_UNDER_IPMP(ill))
15099 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15100 	else
15101 		grifindex = 0;
15102 
15103 	hdr->hpo_version = 1;
15104 	hdr->hpo_htype = htons(htype);
15105 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15106 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15107 	hdr->hpo_grifindex = htonl(grifindex);
15108 	hdr->hpo_zsrc = htonl(zsrc);
15109 	hdr->hpo_zdst = htonl(zdst);
15110 	hdr->hpo_pkt = imp;
15111 	hdr->hpo_ctx = ipst->ips_netstack;
15112 
15113 	if (ill->ill_isv6) {
15114 		hdr->hpo_family = AF_INET6;
15115 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15116 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15117 	} else {
15118 		hdr->hpo_family = AF_INET;
15119 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15120 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15121 	}
15122 
15123 	imp->b_cont = NULL;
15124 	freemsg(imp);
15125 }
15126 
15127 /*
15128  * Utility routine that checks if `v4srcp' is a valid address on underlying
15129  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15130  * associated with `v4srcp' on success.  NOTE: if this is not called from
15131  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15132  * group during or after this lookup.
15133  */
15134 boolean_t
15135 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15136 {
15137 	ipif_t *ipif;
15138 
15139 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15140 	if (ipif != NULL) {
15141 		if (ipifp != NULL)
15142 			*ipifp = ipif;
15143 		else
15144 			ipif_refrele(ipif);
15145 		return (B_TRUE);
15146 	}
15147 
15148 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15149 	    *v4srcp));
15150 	return (B_FALSE);
15151 }
15152 
15153 /*
15154  * Transport protocol call back function for CPU state change.
15155  */
15156 /* ARGSUSED */
15157 static int
15158 ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
15159 {
15160 	processorid_t cpu_seqid;
15161 	netstack_handle_t nh;
15162 	netstack_t *ns;
15163 
15164 	ASSERT(MUTEX_HELD(&cpu_lock));
15165 	cpu_seqid = cpu[id]->cpu_seqid;
15166 
15167 	switch (what) {
15168 	case CPU_CONFIG:
15169 	case CPU_ON:
15170 	case CPU_INIT:
15171 	case CPU_CPUPART_IN:
15172 		netstack_next_init(&nh);
15173 		while ((ns = netstack_next(&nh)) != NULL) {
15174 			tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
15175 			sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
15176 			udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
15177 			netstack_rele(ns);
15178 		}
15179 		netstack_next_fini(&nh);
15180 		break;
15181 	case CPU_UNCONFIG:
15182 	case CPU_OFF:
15183 	case CPU_CPUPART_OUT:
15184 		/*
15185 		 * Nothing to do.  We don't remove the per CPU stats from
15186 		 * the IP stack even when the CPU goes offline.
15187 		 */
15188 		break;
15189 	default:
15190 		break;
15191 	}
15192 	return (0);
15193 }
15194