xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision e20e22c9fb9e2f586b0b23e03f75830e3cece213)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 1990 Mentat Inc.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/stream.h>
29 #include <sys/dlpi.h>
30 #include <sys/stropts.h>
31 #include <sys/sysmacros.h>
32 #include <sys/strsubr.h>
33 #include <sys/strlog.h>
34 #include <sys/strsun.h>
35 #include <sys/zone.h>
36 #define	_SUN_TPI_VERSION 2
37 #include <sys/tihdr.h>
38 #include <sys/xti_inet.h>
39 #include <sys/ddi.h>
40 #include <sys/suntpi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/sadb.h>
98 #include <inet/ipsec_impl.h>
99 #include <inet/iptun/iptun_impl.h>
100 #include <inet/ipdrop.h>
101 #include <inet/ip_netinfo.h>
102 #include <inet/ilb_ip.h>
103 
104 #include <sys/ethernet.h>
105 #include <net/if_types.h>
106 #include <sys/cpuvar.h>
107 
108 #include <ipp/ipp.h>
109 #include <ipp/ipp_impl.h>
110 #include <ipp/ipgpc/ipgpc.h>
111 
112 #include <sys/pattr.h>
113 #include <inet/ipclassifier.h>
114 #include <inet/sctp_ip.h>
115 #include <inet/sctp/sctp_impl.h>
116 #include <inet/udp_impl.h>
117 #include <inet/rawip_impl.h>
118 #include <inet/rts_impl.h>
119 
120 #include <sys/tsol/label.h>
121 #include <sys/tsol/tnet.h>
122 
123 #include <sys/squeue_impl.h>
124 #include <inet/ip_arp.h>
125 
126 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
131  * IP_SQUEUE_ENTER: SQ_PROCESS
132  * IP_SQUEUE_FILL: SQ_FILL
133  */
134 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
135 
136 int ip_squeue_flag;
137 
138 /*
139  * Setable in /etc/system
140  */
141 int ip_poll_normal_ms = 100;
142 int ip_poll_normal_ticks = 0;
143 int ip_modclose_ackwait_ms = 3000;
144 
145 /*
146  * It would be nice to have these present only in DEBUG systems, but the
147  * current design of the global symbol checking logic requires them to be
148  * unconditionally present.
149  */
150 uint_t ip_thread_data;			/* TSD key for debug support */
151 krwlock_t ip_thread_rwlock;
152 list_t	ip_thread_list;
153 
154 /*
155  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
156  */
157 
158 struct listptr_s {
159 	mblk_t	*lp_head;	/* pointer to the head of the list */
160 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
161 };
162 
163 typedef struct listptr_s listptr_t;
164 
165 /*
166  * This is used by ip_snmp_get_mib2_ip_route_media and
167  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
168  */
169 typedef struct iproutedata_s {
170 	uint_t		ird_idx;
171 	uint_t		ird_flags;	/* see below */
172 	listptr_t	ird_route;	/* ipRouteEntryTable */
173 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
174 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
175 } iproutedata_t;
176 
177 /* Include ire_testhidden and IRE_IF_CLONE routes */
178 #define	IRD_REPORT_ALL	0x01
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
199     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
200     void *args) = NULL;
201 
202 /*
203  * Hook function to generate cluster wide SPI.
204  */
205 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
206     void *) = NULL;
207 
208 /*
209  * Hook function to verify if the SPI is already utlized.
210  */
211 
212 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
213 
214 /*
215  * Hook function to delete the SPI from the cluster wide repository.
216  */
217 
218 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
219 
220 /*
221  * Hook function to inform the cluster when packet received on an IDLE SA
222  */
223 
224 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
225     in6_addr_t, in6_addr_t, void *) = NULL;
226 
227 /*
228  * Synchronization notes:
229  *
230  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
231  * MT level protection given by STREAMS. IP uses a combination of its own
232  * internal serialization mechanism and standard Solaris locking techniques.
233  * The internal serialization is per phyint.  This is used to serialize
234  * plumbing operations, IPMP operations, most set ioctls, etc.
235  *
236  * Plumbing is a long sequence of operations involving message
237  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
238  * involved in plumbing operations. A natural model is to serialize these
239  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
240  * parallel without any interference. But various set ioctls on hme0 are best
241  * serialized, along with IPMP operations and processing of DLPI control
242  * messages received from drivers on a per phyint basis. This serialization is
243  * provided by the ipsq_t and primitives operating on this. Details can
244  * be found in ip_if.c above the core primitives operating on ipsq_t.
245  *
246  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
247  * Simiarly lookup of an ire by a thread also returns a refheld ire.
248  * In addition ipif's and ill's referenced by the ire are also indirectly
249  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
250  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
251  * address of an ipif has to go through the ipsq_t. This ensures that only
252  * one such exclusive operation proceeds at any time on the ipif. It then
253  * waits for all refcnts
254  * associated with this ipif to come down to zero. The address is changed
255  * only after the ipif has been quiesced. Then the ipif is brought up again.
256  * More details are described above the comment in ip_sioctl_flags.
257  *
258  * Packet processing is based mostly on IREs and are fully multi-threaded
259  * using standard Solaris MT techniques.
260  *
261  * There are explicit locks in IP to handle:
262  * - The ip_g_head list maintained by mi_open_link() and friends.
263  *
264  * - The reassembly data structures (one lock per hash bucket)
265  *
266  * - conn_lock is meant to protect conn_t fields. The fields actually
267  *   protected by conn_lock are documented in the conn_t definition.
268  *
269  * - ire_lock to protect some of the fields of the ire, IRE tables
270  *   (one lock per hash bucket). Refer to ip_ire.c for details.
271  *
272  * - ndp_g_lock and ncec_lock for protecting NCEs.
273  *
274  * - ill_lock protects fields of the ill and ipif. Details in ip.h
275  *
276  * - ill_g_lock: This is a global reader/writer lock. Protects the following
277  *	* The AVL tree based global multi list of all ills.
278  *	* The linked list of all ipifs of an ill
279  *	* The <ipsq-xop> mapping
280  *	* <ill-phyint> association
281  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
282  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
283  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
284  *   writer for the actual duration of the insertion/deletion/change.
285  *
286  * - ill_lock:  This is a per ill mutex.
287  *   It protects some members of the ill_t struct; see ip.h for details.
288  *   It also protects the <ill-phyint> assoc.
289  *   It also protects the list of ipifs hanging off the ill.
290  *
291  * - ipsq_lock: This is a per ipsq_t mutex lock.
292  *   This protects some members of the ipsq_t struct; see ip.h for details.
293  *   It also protects the <ipsq-ipxop> mapping
294  *
295  * - ipx_lock: This is a per ipxop_t mutex lock.
296  *   This protects some members of the ipxop_t struct; see ip.h for details.
297  *
298  * - phyint_lock: This is a per phyint mutex lock. Protects just the
299  *   phyint_flags
300  *
301  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
302  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
303  *   uniqueness check also done atomically.
304  *
305  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
306  *   group list linked by ill_usesrc_grp_next. It also protects the
307  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
308  *   group is being added or deleted.  This lock is taken as a reader when
309  *   walking the list/group(eg: to get the number of members in a usesrc group).
310  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
311  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
312  *   example, it is not necessary to take this lock in the initial portion
313  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
314  *   operations are executed exclusively and that ensures that the "usesrc
315  *   group state" cannot change. The "usesrc group state" change can happen
316  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ipsq-xop> assocications:
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ipsq-xop> association, the ill_g_lock must be held as
325  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
326  * This is only done when ills are added or removed from IPMP groups.
327  *
328  * To add or delete an ipif from the list of ipifs hanging off the ill,
329  * ill_g_lock (writer) and ill_lock must be held and the thread must be
330  * a writer on the associated ipsq.
331  *
332  * To add or delete an ill to the system, the ill_g_lock must be held as
333  * writer and the thread must be a writer on the associated ipsq.
334  *
335  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
336  * must be a writer on the associated ipsq.
337  *
338  * Lock hierarchy
339  *
340  * Some lock hierarchy scenarios are listed below.
341  *
342  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
343  * ill_g_lock -> ill_lock(s) -> phyint_lock
344  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
345  * ill_g_lock -> ip_addr_avail_lock
346  * conn_lock -> irb_lock -> ill_lock -> ire_lock
347  * ill_g_lock -> ip_g_nd_lock
348  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
350  * arl_lock -> ill_lock
351  * ips_ire_dep_lock -> irb_lock
352  *
353  * When more than 1 ill lock is needed to be held, all ill lock addresses
354  * are sorted on address and locked starting from highest addressed lock
355  * downward.
356  *
357  * Multicast scenarios
358  * ips_ill_g_lock -> ill_mcast_lock
359  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
360  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
361  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
362  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
363  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
364  *
365  * IPsec scenarios
366  *
367  * ipsa_lock -> ill_g_lock -> ill_lock
368  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
369  *
370  * Trusted Solaris scenarios
371  *
372  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
373  * igsa_lock -> gcdb_lock
374  * gcgrp_rwlock -> ire_lock
375  * gcgrp_rwlock -> gcdb_lock
376  *
377  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
378  *
379  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
380  * sq_lock -> conn_lock -> QLOCK(q)
381  * ill_lock -> ft_lock -> fe_lock
382  *
383  * Routing/forwarding table locking notes:
384  *
385  * Lock acquisition order: Radix tree lock, irb_lock.
386  * Requirements:
387  * i.  Walker must not hold any locks during the walker callback.
388  * ii  Walker must not see a truncated tree during the walk because of any node
389  *     deletion.
390  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
391  *     in many places in the code to walk the irb list. Thus even if all the
392  *     ires in a bucket have been deleted, we still can't free the radix node
393  *     until the ires have actually been inactive'd (freed).
394  *
395  * Tree traversal - Need to hold the global tree lock in read mode.
396  * Before dropping the global tree lock, need to either increment the ire_refcnt
397  * to ensure that the radix node can't be deleted.
398  *
399  * Tree add - Need to hold the global tree lock in write mode to add a
400  * radix node. To prevent the node from being deleted, increment the
401  * irb_refcnt, after the node is added to the tree. The ire itself is
402  * added later while holding the irb_lock, but not the tree lock.
403  *
404  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
405  * All associated ires must be inactive (i.e. freed), and irb_refcnt
406  * must be zero.
407  *
408  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
409  * global tree lock (read mode) for traversal.
410  *
411  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
412  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
413  *
414  * IPsec notes :
415  *
416  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
417  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
418  * ip_xmit_attr_t has the
419  * information used by the IPsec code for applying the right level of
420  * protection. The information initialized by IP in the ip_xmit_attr_t
421  * is determined by the per-socket policy or global policy in the system.
422  * For inbound datagrams, the ip_recv_attr_t
423  * starts out with nothing in it. It gets filled
424  * with the right information if it goes through the AH/ESP code, which
425  * happens if the incoming packet is secure. The information initialized
426  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
427  * the policy requirements needed by per-socket policy or global policy
428  * is met or not.
429  *
430  * For fully connected sockets i.e dst, src [addr, port] is known,
431  * conn_policy_cached is set indicating that policy has been cached.
432  * conn_in_enforce_policy may or may not be set depending on whether
433  * there is a global policy match or per-socket policy match.
434  * Policy inheriting happpens in ip_policy_set once the destination is known.
435  * Once the right policy is set on the conn_t, policy cannot change for
436  * this socket. This makes life simpler for TCP (UDP ?) where
437  * re-transmissions go out with the same policy. For symmetry, policy
438  * is cached for fully connected UDP sockets also. Thus if policy is cached,
439  * it also implies that policy is latched i.e policy cannot change
440  * on these sockets. As we have the right policy on the conn, we don't
441  * have to lookup global policy for every outbound and inbound datagram
442  * and thus serving as an optimization. Note that a global policy change
443  * does not affect fully connected sockets if they have policy. If fully
444  * connected sockets did not have any policy associated with it, global
445  * policy change may affect them.
446  *
447  * IP Flow control notes:
448  * ---------------------
449  * Non-TCP streams are flow controlled by IP. The way this is accomplished
450  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
451  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
452  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
453  * functions.
454  *
455  * Per Tx ring udp flow control:
456  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
457  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
458  *
459  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
460  * To achieve best performance, outgoing traffic need to be fanned out among
461  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
462  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
463  * the address of connp as fanout hint to mac_tx(). Under flow controlled
464  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
465  * cookie points to a specific Tx ring that is blocked. The cookie is used to
466  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
467  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
468  * connp's. The drain list is not a single list but a configurable number of
469  * lists.
470  *
471  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
472  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
473  * which is equal to 128. This array in turn contains a pointer to idl_t[],
474  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
475  * list will point to the list of connp's that are flow controlled.
476  *
477  *                      ---------------   -------   -------   -------
478  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
479  *                   |  ---------------   -------   -------   -------
480  *                   |  ---------------   -------   -------   -------
481  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
482  * ----------------  |  ---------------   -------   -------   -------
483  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
484  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   .        .              .         .         .
487  *                   |  ---------------   -------   -------   -------
488  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
489  *                      ---------------   -------   -------   -------
490  *                      ---------------   -------   -------   -------
491  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
492  *                   |  ---------------   -------   -------   -------
493  *                   |  ---------------   -------   -------   -------
494  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
495  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
496  * ----------------  |        .              .         .         .
497  *                   |  ---------------   -------   -------   -------
498  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
499  *                      ---------------   -------   -------   -------
500  *     .....
501  * ----------------
502  * |idl_tx_list[n]|-> ...
503  * ----------------
504  *
505  * When mac_tx() returns a cookie, the cookie is hashed into an index into
506  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
507  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
508  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
509  * Further, conn_blocked is set to indicate that the conn is blocked.
510  *
511  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
512  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
513  * is again hashed to locate the appropriate idl_tx_list, which is then
514  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
515  * the drain list and calls conn_drain_remove() to clear flow control (via
516  * calling su_txq_full() or clearing QFULL), and remove the conn from the
517  * drain list.
518  *
519  * Note that the drain list is not a single list but a (configurable) array of
520  * lists (8 elements by default).  Synchronization between drain insertion and
521  * flow control wakeup is handled by using idl_txl->txl_lock, and only
522  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
523  *
524  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
525  * On the send side, if the packet cannot be sent down to the driver by IP
526  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
527  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
528  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
529  * control has been relieved, the blocked conns in the 0'th drain list are
530  * drained as in the non-STREAMS case.
531  *
532  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
533  * is done when the conn is inserted into the drain list (conn_drain_insert())
534  * and cleared when the conn is removed from the it (conn_drain_remove()).
535  *
536  * IPQOS notes:
537  *
538  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
539  * and IPQoS modules. IPPF includes hooks in IP at different control points
540  * (callout positions) which direct packets to IPQoS modules for policy
541  * processing. Policies, if present, are global.
542  *
543  * The callout positions are located in the following paths:
544  *		o local_in (packets destined for this host)
545  *		o local_out (packets orginating from this host )
546  *		o fwd_in  (packets forwarded by this m/c - inbound)
547  *		o fwd_out (packets forwarded by this m/c - outbound)
548  * Hooks at these callout points can be enabled/disabled using the ndd variable
549  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
550  * By default all the callout positions are enabled.
551  *
552  * Outbound (local_out)
553  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
554  *
555  * Inbound (local_in)
556  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
557  *
558  * Forwarding (in and out)
559  * Hooks are placed in ire_recv_forward_v4/v6.
560  *
561  * IP Policy Framework processing (IPPF processing)
562  * Policy processing for a packet is initiated by ip_process, which ascertains
563  * that the classifier (ipgpc) is loaded and configured, failing which the
564  * packet resumes normal processing in IP. If the clasifier is present, the
565  * packet is acted upon by one or more IPQoS modules (action instances), per
566  * filters configured in ipgpc and resumes normal IP processing thereafter.
567  * An action instance can drop a packet in course of its processing.
568  *
569  * Zones notes:
570  *
571  * The partitioning rules for networking are as follows:
572  * 1) Packets coming from a zone must have a source address belonging to that
573  * zone.
574  * 2) Packets coming from a zone can only be sent on a physical interface on
575  * which the zone has an IP address.
576  * 3) Between two zones on the same machine, packet delivery is only allowed if
577  * there's a matching route for the destination and zone in the forwarding
578  * table.
579  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
580  * different zones can bind to the same port with the wildcard address
581  * (INADDR_ANY).
582  *
583  * The granularity of interface partitioning is at the logical interface level.
584  * Therefore, every zone has its own IP addresses, and incoming packets can be
585  * attributed to a zone unambiguously. A logical interface is placed into a zone
586  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
587  * structure. Rule (1) is implemented by modifying the source address selection
588  * algorithm so that the list of eligible addresses is filtered based on the
589  * sending process zone.
590  *
591  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
592  * across all zones, depending on their type. Here is the break-up:
593  *
594  * IRE type				Shared/exclusive
595  * --------				----------------
596  * IRE_BROADCAST			Exclusive
597  * IRE_DEFAULT (default routes)		Shared (*)
598  * IRE_LOCAL				Exclusive (x)
599  * IRE_LOOPBACK				Exclusive
600  * IRE_PREFIX (net routes)		Shared (*)
601  * IRE_IF_NORESOLVER (interface routes)	Exclusive
602  * IRE_IF_RESOLVER (interface routes)	Exclusive
603  * IRE_IF_CLONE (interface routes)	Exclusive
604  * IRE_HOST (host routes)		Shared (*)
605  *
606  * (*) A zone can only use a default or off-subnet route if the gateway is
607  * directly reachable from the zone, that is, if the gateway's address matches
608  * one of the zone's logical interfaces.
609  *
610  * (x) IRE_LOCAL are handled a bit differently.
611  * When ip_restrict_interzone_loopback is set (the default),
612  * ire_route_recursive restricts loopback using an IRE_LOCAL
613  * between zone to the case when L2 would have conceptually looped the packet
614  * back, i.e. the loopback which is required since neither Ethernet drivers
615  * nor Ethernet hardware loops them back. This is the case when the normal
616  * routes (ignoring IREs with different zoneids) would send out the packet on
617  * the same ill as the ill with which is IRE_LOCAL is associated.
618  *
619  * Multiple zones can share a common broadcast address; typically all zones
620  * share the 255.255.255.255 address. Incoming as well as locally originated
621  * broadcast packets must be dispatched to all the zones on the broadcast
622  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
623  * since some zones may not be on the 10.16.72/24 network. To handle this, each
624  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
625  * sent to every zone that has an IRE_BROADCAST entry for the destination
626  * address on the input ill, see ip_input_broadcast().
627  *
628  * Applications in different zones can join the same multicast group address.
629  * The same logic applies for multicast as for broadcast. ip_input_multicast
630  * dispatches packets to all zones that have members on the physical interface.
631  */
632 
633 /*
634  * Squeue Fanout flags:
635  *	0: No fanout.
636  *	1: Fanout across all squeues
637  */
638 boolean_t	ip_squeue_fanout = 0;
639 
640 /*
641  * Maximum dups allowed per packet.
642  */
643 uint_t ip_max_frag_dups = 10;
644 
645 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
646 		    cred_t *credp, boolean_t isv6);
647 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
648 
649 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
650 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
651 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
652     ip_recv_attr_t *);
653 static void	icmp_options_update(ipha_t *);
654 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
655 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
656 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
657 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
658     ip_recv_attr_t *);
659 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
660 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
661     ip_recv_attr_t *);
662 
663 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
664 char		*ip_dot_addr(ipaddr_t, char *);
665 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
666 int		ip_close(queue_t *, int);
667 static char	*ip_dot_saddr(uchar_t *, char *);
668 static void	ip_lrput(queue_t *, mblk_t *);
669 ipaddr_t	ip_net_mask(ipaddr_t);
670 char		*ip_nv_lookup(nv_t *, int);
671 void	ip_rput(queue_t *, mblk_t *);
672 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
673 		    void *dummy_arg);
674 int		ip_snmp_get(queue_t *, mblk_t *, int);
675 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
676 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
678 		    ip_stack_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
680 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
703 		    ip_stack_t *ipst);
704 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
705 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
706 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
707 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
708 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
709 
710 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
711 		    mblk_t *);
712 
713 static void	conn_drain_init(ip_stack_t *);
714 static void	conn_drain_fini(ip_stack_t *);
715 static void	conn_drain(conn_t *connp, boolean_t closing);
716 
717 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
718 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
719 
720 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
721 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
722 static void	ip_stack_fini(netstackid_t stackid, void *arg);
723 
724 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
725     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
726     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
727     const in6_addr_t *);
728 
729 static int	ip_squeue_switch(int);
730 
731 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
732 static void	ip_kstat_fini(netstackid_t, kstat_t *);
733 static int	ip_kstat_update(kstat_t *kp, int rw);
734 static void	*icmp_kstat_init(netstackid_t);
735 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
736 static int	icmp_kstat_update(kstat_t *kp, int rw);
737 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
738 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
739 
740 static void	ipobs_init(ip_stack_t *);
741 static void	ipobs_fini(ip_stack_t *);
742 
743 static int	ip_tp_cpu_update(cpu_setup_t, int, void *);
744 
745 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
746 
747 static long ip_rput_pullups;
748 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
749 
750 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
751 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
752 
753 int	ip_debug;
754 
755 /*
756  * Multirouting/CGTP stuff
757  */
758 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
759 
760 /*
761  * IP tunables related declarations. Definitions are in ip_tunables.c
762  */
763 extern mod_prop_info_t ip_propinfo_tbl[];
764 extern int ip_propinfo_count;
765 
766 /*
767  * Table of IP ioctls encoding the various properties of the ioctl and
768  * indexed based on the last byte of the ioctl command. Occasionally there
769  * is a clash, and there is more than 1 ioctl with the same last byte.
770  * In such a case 1 ioctl is encoded in the ndx table and the remaining
771  * ioctls are encoded in the misc table. An entry in the ndx table is
772  * retrieved by indexing on the last byte of the ioctl command and comparing
773  * the ioctl command with the value in the ndx table. In the event of a
774  * mismatch the misc table is then searched sequentially for the desired
775  * ioctl command.
776  *
777  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
778  */
779 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
780 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
781 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
782 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
783 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
784 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
785 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
786 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
787 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
788 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
789 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
790 
791 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
792 			MISC_CMD, ip_siocaddrt, NULL },
793 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
794 			MISC_CMD, ip_siocdelrt, NULL },
795 
796 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
797 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
798 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
799 			IF_CMD, ip_sioctl_get_addr, NULL },
800 
801 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
802 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
803 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
804 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
805 
806 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
807 			IPI_PRIV | IPI_WR,
808 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
809 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
810 			IPI_MODOK | IPI_GET_CMD,
811 			IF_CMD, ip_sioctl_get_flags, NULL },
812 
813 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
814 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
815 
816 	/* copyin size cannot be coded for SIOCGIFCONF */
817 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
818 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
819 
820 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
821 			IF_CMD, ip_sioctl_mtu, NULL },
822 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
823 			IF_CMD, ip_sioctl_get_mtu, NULL },
824 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
825 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
826 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
827 			IF_CMD, ip_sioctl_brdaddr, NULL },
828 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
829 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
830 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
831 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
832 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
833 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
834 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
835 			IF_CMD, ip_sioctl_metric, NULL },
836 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
837 
838 	/* See 166-168 below for extended SIOC*XARP ioctls */
839 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
840 			ARP_CMD, ip_sioctl_arp, NULL },
841 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
842 			ARP_CMD, ip_sioctl_arp, NULL },
843 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
844 			ARP_CMD, ip_sioctl_arp, NULL },
845 
846 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
847 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
848 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
849 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
850 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
851 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
852 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
853 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
854 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
855 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
856 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
857 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
858 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
859 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
860 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
861 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
862 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
863 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
864 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
865 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
866 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
867 
868 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
869 			MISC_CMD, if_unitsel, if_unitsel_restart },
870 
871 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
872 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
873 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
874 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
875 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
876 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
877 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
878 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
879 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
880 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
881 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
882 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
883 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
884 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
885 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
886 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
887 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
888 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
889 
890 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
891 			IPI_PRIV | IPI_WR | IPI_MODOK,
892 			IF_CMD, ip_sioctl_sifname, NULL },
893 
894 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
895 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
896 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
897 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
898 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
899 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
900 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
901 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
902 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
903 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
904 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
905 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
906 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
907 
908 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
909 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
910 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
911 			IF_CMD, ip_sioctl_get_muxid, NULL },
912 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
913 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
914 
915 	/* Both if and lif variants share same func */
916 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
917 			IF_CMD, ip_sioctl_get_lifindex, NULL },
918 	/* Both if and lif variants share same func */
919 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
920 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
921 
922 	/* copyin size cannot be coded for SIOCGIFCONF */
923 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
924 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
925 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
926 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
927 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
928 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
929 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
930 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
931 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
932 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
933 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
934 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
935 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
936 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
937 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
938 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
939 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
940 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
941 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
942 
943 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
944 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
945 			ip_sioctl_removeif_restart },
946 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
947 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
948 			LIF_CMD, ip_sioctl_addif, NULL },
949 #define	SIOCLIFADDR_NDX 112
950 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
951 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
952 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
953 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
954 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
955 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
956 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
957 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
958 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
959 			IPI_PRIV | IPI_WR,
960 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
961 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
962 			IPI_GET_CMD | IPI_MODOK,
963 			LIF_CMD, ip_sioctl_get_flags, NULL },
964 
965 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
966 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
967 
968 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
969 			ip_sioctl_get_lifconf, NULL },
970 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
971 			LIF_CMD, ip_sioctl_mtu, NULL },
972 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
973 			LIF_CMD, ip_sioctl_get_mtu, NULL },
974 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
975 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
976 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
977 			LIF_CMD, ip_sioctl_brdaddr, NULL },
978 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
979 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
980 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
981 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
982 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
983 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
984 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
985 			LIF_CMD, ip_sioctl_metric, NULL },
986 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
987 			IPI_PRIV | IPI_WR | IPI_MODOK,
988 			LIF_CMD, ip_sioctl_slifname,
989 			ip_sioctl_slifname_restart },
990 
991 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
992 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
993 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
994 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
995 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
996 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
997 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
998 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
999 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1000 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1001 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1002 			LIF_CMD, ip_sioctl_token, NULL },
1003 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1004 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1005 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1006 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1007 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1008 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1009 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1010 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1011 
1012 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1013 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1014 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1015 			LIF_CMD, ip_siocdelndp_v6, NULL },
1016 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1017 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1018 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1019 			LIF_CMD, ip_siocsetndp_v6, NULL },
1020 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1021 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1022 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1023 			MISC_CMD, ip_sioctl_tonlink, NULL },
1024 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1025 			MISC_CMD, ip_sioctl_tmysite, NULL },
1026 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1029 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1030 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1031 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1032 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1033 
1034 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1037 			LIF_CMD, ip_sioctl_get_binding, NULL },
1038 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1039 			IPI_PRIV | IPI_WR,
1040 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1041 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1042 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1043 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1044 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1045 
1046 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1047 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 
1051 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 
1053 	/* These are handled in ip_sioctl_copyin_setup itself */
1054 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1055 			MISC_CMD, NULL, NULL },
1056 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1057 			MISC_CMD, NULL, NULL },
1058 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1059 
1060 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1061 			ip_sioctl_get_lifconf, NULL },
1062 
1063 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1064 			XARP_CMD, ip_sioctl_arp, NULL },
1065 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1066 			XARP_CMD, ip_sioctl_arp, NULL },
1067 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1068 			XARP_CMD, ip_sioctl_arp, NULL },
1069 
1070 	/* SIOCPOPSOCKFS is not handled by IP */
1071 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1072 
1073 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1074 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1075 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1076 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1077 			ip_sioctl_slifzone_restart },
1078 	/* 172-174 are SCTP ioctls and not handled by IP */
1079 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1083 			IPI_GET_CMD, LIF_CMD,
1084 			ip_sioctl_get_lifusesrc, 0 },
1085 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1086 			IPI_PRIV | IPI_WR,
1087 			LIF_CMD, ip_sioctl_slifusesrc,
1088 			NULL },
1089 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1090 			ip_sioctl_get_lifsrcof, NULL },
1091 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1092 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1093 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1094 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1095 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1096 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1097 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1098 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1099 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* SIOCSENABLESDP is handled by SDP */
1101 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1102 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1103 	/* 185 */ { IPI_DONTCARE /* SIOCGIFHWADDR */, 0, 0, 0, NULL, NULL },
1104 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1105 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1106 			ip_sioctl_ilb_cmd, NULL },
1107 	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1108 	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1109 	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1110 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1111 	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1112 			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart }
1113 };
1114 
1115 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1116 
1117 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1118 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1119 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1120 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1121 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1122 	{ ND_GET,	0, 0, 0, NULL, NULL },
1123 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1124 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1125 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1126 		MISC_CMD, mrt_ioctl},
1127 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1128 		MISC_CMD, mrt_ioctl},
1129 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1130 		MISC_CMD, mrt_ioctl}
1131 };
1132 
1133 int ip_misc_ioctl_count =
1134     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1135 
1136 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1137 					/* Settable in /etc/system */
1138 /* Defined in ip_ire.c */
1139 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1140 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1141 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1142 
1143 static nv_t	ire_nv_arr[] = {
1144 	{ IRE_BROADCAST, "BROADCAST" },
1145 	{ IRE_LOCAL, "LOCAL" },
1146 	{ IRE_LOOPBACK, "LOOPBACK" },
1147 	{ IRE_DEFAULT, "DEFAULT" },
1148 	{ IRE_PREFIX, "PREFIX" },
1149 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1150 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1151 	{ IRE_IF_CLONE, "IF_CLONE" },
1152 	{ IRE_HOST, "HOST" },
1153 	{ IRE_MULTICAST, "MULTICAST" },
1154 	{ IRE_NOROUTE, "NOROUTE" },
1155 	{ 0 }
1156 };
1157 
1158 nv_t	*ire_nv_tbl = ire_nv_arr;
1159 
1160 /* Simple ICMP IP Header Template */
1161 static ipha_t icmp_ipha = {
1162 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1163 };
1164 
1165 struct module_info ip_mod_info = {
1166 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1167 	IP_MOD_LOWAT
1168 };
1169 
1170 /*
1171  * Duplicate static symbols within a module confuses mdb; so we avoid the
1172  * problem by making the symbols here distinct from those in udp.c.
1173  */
1174 
1175 /*
1176  * Entry points for IP as a device and as a module.
1177  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1178  */
1179 static struct qinit iprinitv4 = {
1180 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1181 	&ip_mod_info
1182 };
1183 
1184 struct qinit iprinitv6 = {
1185 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1186 	&ip_mod_info
1187 };
1188 
1189 static struct qinit ipwinit = {
1190 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1191 	&ip_mod_info
1192 };
1193 
1194 static struct qinit iplrinit = {
1195 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1196 	&ip_mod_info
1197 };
1198 
1199 static struct qinit iplwinit = {
1200 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1201 	&ip_mod_info
1202 };
1203 
1204 /* For AF_INET aka /dev/ip */
1205 struct streamtab ipinfov4 = {
1206 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1207 };
1208 
1209 /* For AF_INET6 aka /dev/ip6 */
1210 struct streamtab ipinfov6 = {
1211 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1212 };
1213 
1214 #ifdef	DEBUG
1215 boolean_t skip_sctp_cksum = B_FALSE;
1216 #endif
1217 
1218 /*
1219  * Generate an ICMP fragmentation needed message.
1220  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1221  * constructed by the caller.
1222  */
1223 void
1224 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1225 {
1226 	icmph_t	icmph;
1227 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1228 
1229 	mp = icmp_pkt_err_ok(mp, ira);
1230 	if (mp == NULL)
1231 		return;
1232 
1233 	bzero(&icmph, sizeof (icmph_t));
1234 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1235 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1236 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1237 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1238 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1239 
1240 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1241 }
1242 
1243 /*
1244  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1245  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1246  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1247  * Likewise, if the ICMP error is misformed (too short, etc), then it
1248  * returns NULL. The caller uses this to determine whether or not to send
1249  * to raw sockets.
1250  *
1251  * All error messages are passed to the matching transport stream.
1252  *
1253  * The following cases are handled by icmp_inbound:
1254  * 1) It needs to send a reply back and possibly delivering it
1255  *    to the "interested" upper clients.
1256  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1257  * 3) It needs to change some values in IP only.
1258  * 4) It needs to change some values in IP and upper layers e.g TCP
1259  *    by delivering an error to the upper layers.
1260  *
1261  * We handle the above three cases in the context of IPsec in the
1262  * following way :
1263  *
1264  * 1) Send the reply back in the same way as the request came in.
1265  *    If it came in encrypted, it goes out encrypted. If it came in
1266  *    clear, it goes out in clear. Thus, this will prevent chosen
1267  *    plain text attack.
1268  * 2) The client may or may not expect things to come in secure.
1269  *    If it comes in secure, the policy constraints are checked
1270  *    before delivering it to the upper layers. If it comes in
1271  *    clear, ipsec_inbound_accept_clear will decide whether to
1272  *    accept this in clear or not. In both the cases, if the returned
1273  *    message (IP header + 8 bytes) that caused the icmp message has
1274  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1275  *    sending up. If there are only 8 bytes of returned message, then
1276  *    upper client will not be notified.
1277  * 3) Check with global policy to see whether it matches the constaints.
1278  *    But this will be done only if icmp_accept_messages_in_clear is
1279  *    zero.
1280  * 4) If we need to change both in IP and ULP, then the decision taken
1281  *    while affecting the values in IP and while delivering up to TCP
1282  *    should be the same.
1283  *
1284  * 	There are two cases.
1285  *
1286  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1287  *	   failed), we will not deliver it to the ULP, even though they
1288  *	   are *willing* to accept in *clear*. This is fine as our global
1289  *	   disposition to icmp messages asks us reject the datagram.
1290  *
1291  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1292  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1293  *	   to deliver it to ULP (policy failed), it can lead to
1294  *	   consistency problems. The cases known at this time are
1295  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1296  *	   values :
1297  *
1298  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1299  *	     and Upper layer rejects. Then the communication will
1300  *	     come to a stop. This is solved by making similar decisions
1301  *	     at both levels. Currently, when we are unable to deliver
1302  *	     to the Upper Layer (due to policy failures) while IP has
1303  *	     adjusted dce_pmtu, the next outbound datagram would
1304  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1305  *	     will be with the right level of protection. Thus the right
1306  *	     value will be communicated even if we are not able to
1307  *	     communicate when we get from the wire initially. But this
1308  *	     assumes there would be at least one outbound datagram after
1309  *	     IP has adjusted its dce_pmtu value. To make things
1310  *	     simpler, we accept in clear after the validation of
1311  *	     AH/ESP headers.
1312  *
1313  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1314  *	     upper layer depending on the level of protection the upper
1315  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1316  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1317  *	     should be accepted in clear when the Upper layer expects secure.
1318  *	     Thus the communication may get aborted by some bad ICMP
1319  *	     packets.
1320  */
1321 mblk_t *
1322 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1323 {
1324 	icmph_t		*icmph;
1325 	ipha_t		*ipha;		/* Outer header */
1326 	int		ip_hdr_length;	/* Outer header length */
1327 	boolean_t	interested;
1328 	ipif_t		*ipif;
1329 	uint32_t	ts;
1330 	uint32_t	*tsp;
1331 	timestruc_t	now;
1332 	ill_t		*ill = ira->ira_ill;
1333 	ip_stack_t	*ipst = ill->ill_ipst;
1334 	zoneid_t	zoneid = ira->ira_zoneid;
1335 	int		len_needed;
1336 	mblk_t		*mp_ret = NULL;
1337 
1338 	ipha = (ipha_t *)mp->b_rptr;
1339 
1340 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1341 
1342 	ip_hdr_length = ira->ira_ip_hdr_length;
1343 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1344 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1345 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1346 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1347 			freemsg(mp);
1348 			return (NULL);
1349 		}
1350 		/* Last chance to get real. */
1351 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1352 		if (ipha == NULL) {
1353 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1354 			freemsg(mp);
1355 			return (NULL);
1356 		}
1357 	}
1358 
1359 	/* The IP header will always be a multiple of four bytes */
1360 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1361 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1362 	    icmph->icmph_code));
1363 
1364 	/*
1365 	 * We will set "interested" to "true" if we should pass a copy to
1366 	 * the transport or if we handle the packet locally.
1367 	 */
1368 	interested = B_FALSE;
1369 	switch (icmph->icmph_type) {
1370 	case ICMP_ECHO_REPLY:
1371 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1372 		break;
1373 	case ICMP_DEST_UNREACHABLE:
1374 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1375 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1376 		interested = B_TRUE;	/* Pass up to transport */
1377 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1378 		break;
1379 	case ICMP_SOURCE_QUENCH:
1380 		interested = B_TRUE;	/* Pass up to transport */
1381 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1382 		break;
1383 	case ICMP_REDIRECT:
1384 		if (!ipst->ips_ip_ignore_redirect)
1385 			interested = B_TRUE;
1386 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1387 		break;
1388 	case ICMP_ECHO_REQUEST:
1389 		/*
1390 		 * Whether to respond to echo requests that come in as IP
1391 		 * broadcasts or as IP multicast is subject to debate
1392 		 * (what isn't?).  We aim to please, you pick it.
1393 		 * Default is do it.
1394 		 */
1395 		if (ira->ira_flags & IRAF_MULTICAST) {
1396 			/* multicast: respond based on tunable */
1397 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1398 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1399 			/* broadcast: respond based on tunable */
1400 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1401 		} else {
1402 			/* unicast: always respond */
1403 			interested = B_TRUE;
1404 		}
1405 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1406 		if (!interested) {
1407 			/* We never pass these to RAW sockets */
1408 			freemsg(mp);
1409 			return (NULL);
1410 		}
1411 
1412 		/* Check db_ref to make sure we can modify the packet. */
1413 		if (mp->b_datap->db_ref > 1) {
1414 			mblk_t	*mp1;
1415 
1416 			mp1 = copymsg(mp);
1417 			freemsg(mp);
1418 			if (!mp1) {
1419 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1420 				return (NULL);
1421 			}
1422 			mp = mp1;
1423 			ipha = (ipha_t *)mp->b_rptr;
1424 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1425 		}
1426 		icmph->icmph_type = ICMP_ECHO_REPLY;
1427 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1428 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1429 		return (NULL);
1430 
1431 	case ICMP_ROUTER_ADVERTISEMENT:
1432 	case ICMP_ROUTER_SOLICITATION:
1433 		break;
1434 	case ICMP_TIME_EXCEEDED:
1435 		interested = B_TRUE;	/* Pass up to transport */
1436 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1437 		break;
1438 	case ICMP_PARAM_PROBLEM:
1439 		interested = B_TRUE;	/* Pass up to transport */
1440 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1441 		break;
1442 	case ICMP_TIME_STAMP_REQUEST:
1443 		/* Response to Time Stamp Requests is local policy. */
1444 		if (ipst->ips_ip_g_resp_to_timestamp) {
1445 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1446 				interested =
1447 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1448 			else
1449 				interested = B_TRUE;
1450 		}
1451 		if (!interested) {
1452 			/* We never pass these to RAW sockets */
1453 			freemsg(mp);
1454 			return (NULL);
1455 		}
1456 
1457 		/* Make sure we have enough of the packet */
1458 		len_needed = ip_hdr_length + ICMPH_SIZE +
1459 		    3 * sizeof (uint32_t);
1460 
1461 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1462 			ipha = ip_pullup(mp, len_needed, ira);
1463 			if (ipha == NULL) {
1464 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1465 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1466 				    mp, ill);
1467 				freemsg(mp);
1468 				return (NULL);
1469 			}
1470 			/* Refresh following the pullup. */
1471 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1472 		}
1473 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1474 		/* Check db_ref to make sure we can modify the packet. */
1475 		if (mp->b_datap->db_ref > 1) {
1476 			mblk_t	*mp1;
1477 
1478 			mp1 = copymsg(mp);
1479 			freemsg(mp);
1480 			if (!mp1) {
1481 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1482 				return (NULL);
1483 			}
1484 			mp = mp1;
1485 			ipha = (ipha_t *)mp->b_rptr;
1486 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1487 		}
1488 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1489 		tsp = (uint32_t *)&icmph[1];
1490 		tsp++;		/* Skip past 'originate time' */
1491 		/* Compute # of milliseconds since midnight */
1492 		gethrestime(&now);
1493 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1494 		    now.tv_nsec / (NANOSEC / MILLISEC);
1495 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1496 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1497 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1498 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1499 		return (NULL);
1500 
1501 	case ICMP_TIME_STAMP_REPLY:
1502 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1503 		break;
1504 	case ICMP_INFO_REQUEST:
1505 		/* Per RFC 1122 3.2.2.7, ignore this. */
1506 	case ICMP_INFO_REPLY:
1507 		break;
1508 	case ICMP_ADDRESS_MASK_REQUEST:
1509 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1510 			interested =
1511 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1512 		} else {
1513 			interested = B_TRUE;
1514 		}
1515 		if (!interested) {
1516 			/* We never pass these to RAW sockets */
1517 			freemsg(mp);
1518 			return (NULL);
1519 		}
1520 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1521 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1522 			ipha = ip_pullup(mp, len_needed, ira);
1523 			if (ipha == NULL) {
1524 				BUMP_MIB(ill->ill_ip_mib,
1525 				    ipIfStatsInTruncatedPkts);
1526 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1527 				    ill);
1528 				freemsg(mp);
1529 				return (NULL);
1530 			}
1531 			/* Refresh following the pullup. */
1532 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1533 		}
1534 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1535 		/* Check db_ref to make sure we can modify the packet. */
1536 		if (mp->b_datap->db_ref > 1) {
1537 			mblk_t	*mp1;
1538 
1539 			mp1 = copymsg(mp);
1540 			freemsg(mp);
1541 			if (!mp1) {
1542 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1543 				return (NULL);
1544 			}
1545 			mp = mp1;
1546 			ipha = (ipha_t *)mp->b_rptr;
1547 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1548 		}
1549 		/*
1550 		 * Need the ipif with the mask be the same as the source
1551 		 * address of the mask reply. For unicast we have a specific
1552 		 * ipif. For multicast/broadcast we only handle onlink
1553 		 * senders, and use the source address to pick an ipif.
1554 		 */
1555 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1556 		if (ipif == NULL) {
1557 			/* Broadcast or multicast */
1558 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1559 			if (ipif == NULL) {
1560 				freemsg(mp);
1561 				return (NULL);
1562 			}
1563 		}
1564 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1565 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1566 		ipif_refrele(ipif);
1567 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1568 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1569 		return (NULL);
1570 
1571 	case ICMP_ADDRESS_MASK_REPLY:
1572 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1573 		break;
1574 	default:
1575 		interested = B_TRUE;	/* Pass up to transport */
1576 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1577 		break;
1578 	}
1579 	/*
1580 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1581 	 * if there isn't one.
1582 	 */
1583 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1584 		/* If there is an ICMP client and we want one too, copy it. */
1585 
1586 		if (!interested) {
1587 			/* Caller will deliver to RAW sockets */
1588 			return (mp);
1589 		}
1590 		mp_ret = copymsg(mp);
1591 		if (mp_ret == NULL) {
1592 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1593 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1594 		}
1595 	} else if (!interested) {
1596 		/* Neither we nor raw sockets are interested. Drop packet now */
1597 		freemsg(mp);
1598 		return (NULL);
1599 	}
1600 
1601 	/*
1602 	 * ICMP error or redirect packet. Make sure we have enough of
1603 	 * the header and that db_ref == 1 since we might end up modifying
1604 	 * the packet.
1605 	 */
1606 	if (mp->b_cont != NULL) {
1607 		if (ip_pullup(mp, -1, ira) == NULL) {
1608 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1609 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1610 			    mp, ill);
1611 			freemsg(mp);
1612 			return (mp_ret);
1613 		}
1614 	}
1615 
1616 	if (mp->b_datap->db_ref > 1) {
1617 		mblk_t	*mp1;
1618 
1619 		mp1 = copymsg(mp);
1620 		if (mp1 == NULL) {
1621 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1622 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1623 			freemsg(mp);
1624 			return (mp_ret);
1625 		}
1626 		freemsg(mp);
1627 		mp = mp1;
1628 	}
1629 
1630 	/*
1631 	 * In case mp has changed, verify the message before any further
1632 	 * processes.
1633 	 */
1634 	ipha = (ipha_t *)mp->b_rptr;
1635 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1636 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1637 		freemsg(mp);
1638 		return (mp_ret);
1639 	}
1640 
1641 	switch (icmph->icmph_type) {
1642 	case ICMP_REDIRECT:
1643 		icmp_redirect_v4(mp, ipha, icmph, ira);
1644 		break;
1645 	case ICMP_DEST_UNREACHABLE:
1646 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1647 			/* Update DCE and adjust MTU is icmp header if needed */
1648 			icmp_inbound_too_big_v4(icmph, ira);
1649 		}
1650 		/* FALLTHRU */
1651 	default:
1652 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1653 		break;
1654 	}
1655 	return (mp_ret);
1656 }
1657 
1658 /*
1659  * Send an ICMP echo, timestamp or address mask reply.
1660  * The caller has already updated the payload part of the packet.
1661  * We handle the ICMP checksum, IP source address selection and feed
1662  * the packet into ip_output_simple.
1663  */
1664 static void
1665 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1666     ip_recv_attr_t *ira)
1667 {
1668 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1669 	ill_t		*ill = ira->ira_ill;
1670 	ip_stack_t	*ipst = ill->ill_ipst;
1671 	ip_xmit_attr_t	ixas;
1672 
1673 	/* Send out an ICMP packet */
1674 	icmph->icmph_checksum = 0;
1675 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1676 	/* Reset time to live. */
1677 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1678 	{
1679 		/* Swap source and destination addresses */
1680 		ipaddr_t tmp;
1681 
1682 		tmp = ipha->ipha_src;
1683 		ipha->ipha_src = ipha->ipha_dst;
1684 		ipha->ipha_dst = tmp;
1685 	}
1686 	ipha->ipha_ident = 0;
1687 	if (!IS_SIMPLE_IPH(ipha))
1688 		icmp_options_update(ipha);
1689 
1690 	bzero(&ixas, sizeof (ixas));
1691 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1692 	ixas.ixa_zoneid = ira->ira_zoneid;
1693 	ixas.ixa_cred = kcred;
1694 	ixas.ixa_cpid = NOPID;
1695 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1696 	ixas.ixa_ifindex = 0;
1697 	ixas.ixa_ipst = ipst;
1698 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1699 
1700 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1701 		/*
1702 		 * This packet should go out the same way as it
1703 		 * came in i.e in clear, independent of the IPsec policy
1704 		 * for transmitting packets.
1705 		 */
1706 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1707 	} else {
1708 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1709 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1710 			/* Note: mp already consumed and ip_drop_packet done */
1711 			return;
1712 		}
1713 	}
1714 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1715 		/*
1716 		 * Not one or our addresses (IRE_LOCALs), thus we let
1717 		 * ip_output_simple pick the source.
1718 		 */
1719 		ipha->ipha_src = INADDR_ANY;
1720 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1721 	}
1722 	/* Should we send with DF and use dce_pmtu? */
1723 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1724 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1725 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1726 	}
1727 
1728 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1729 
1730 	(void) ip_output_simple(mp, &ixas);
1731 	ixa_cleanup(&ixas);
1732 }
1733 
1734 /*
1735  * Verify the ICMP messages for either for ICMP error or redirect packet.
1736  * The caller should have fully pulled up the message. If it's a redirect
1737  * packet, only basic checks on IP header will be done; otherwise, verify
1738  * the packet by looking at the included ULP header.
1739  *
1740  * Called before icmp_inbound_error_fanout_v4 is called.
1741  */
1742 static boolean_t
1743 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1744 {
1745 	ill_t		*ill = ira->ira_ill;
1746 	int		hdr_length;
1747 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1748 	conn_t		*connp;
1749 	ipha_t		*ipha;	/* Inner IP header */
1750 
1751 	ipha = (ipha_t *)&icmph[1];
1752 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1753 		goto truncated;
1754 
1755 	hdr_length = IPH_HDR_LENGTH(ipha);
1756 
1757 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1758 		goto discard_pkt;
1759 
1760 	if (hdr_length < sizeof (ipha_t))
1761 		goto truncated;
1762 
1763 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1764 		goto truncated;
1765 
1766 	/*
1767 	 * Stop here for ICMP_REDIRECT.
1768 	 */
1769 	if (icmph->icmph_type == ICMP_REDIRECT)
1770 		return (B_TRUE);
1771 
1772 	/*
1773 	 * ICMP errors only.
1774 	 */
1775 	switch (ipha->ipha_protocol) {
1776 	case IPPROTO_UDP:
1777 		/*
1778 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1779 		 * transport header.
1780 		 */
1781 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1782 		    mp->b_wptr)
1783 			goto truncated;
1784 		break;
1785 	case IPPROTO_TCP: {
1786 		tcpha_t		*tcpha;
1787 
1788 		/*
1789 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1790 		 * transport header.
1791 		 */
1792 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1793 		    mp->b_wptr)
1794 			goto truncated;
1795 
1796 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1797 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1798 		    ipst);
1799 		if (connp == NULL)
1800 			goto discard_pkt;
1801 
1802 		if ((connp->conn_verifyicmp != NULL) &&
1803 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1804 			CONN_DEC_REF(connp);
1805 			goto discard_pkt;
1806 		}
1807 		CONN_DEC_REF(connp);
1808 		break;
1809 	}
1810 	case IPPROTO_SCTP:
1811 		/*
1812 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1813 		 * transport header.
1814 		 */
1815 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1816 		    mp->b_wptr)
1817 			goto truncated;
1818 		break;
1819 	case IPPROTO_ESP:
1820 	case IPPROTO_AH:
1821 		break;
1822 	case IPPROTO_ENCAP:
1823 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1824 		    mp->b_wptr)
1825 			goto truncated;
1826 		break;
1827 	default:
1828 		break;
1829 	}
1830 
1831 	return (B_TRUE);
1832 
1833 discard_pkt:
1834 	/* Bogus ICMP error. */
1835 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1836 	return (B_FALSE);
1837 
1838 truncated:
1839 	/* We pulled up everthing already. Must be truncated */
1840 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1841 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1842 	return (B_FALSE);
1843 }
1844 
1845 /* Table from RFC 1191 */
1846 static int icmp_frag_size_table[] =
1847 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1848 
1849 /*
1850  * Process received ICMP Packet too big.
1851  * Just handles the DCE create/update, including using the above table of
1852  * PMTU guesses. The caller is responsible for validating the packet before
1853  * passing it in and also to fanout the ICMP error to any matching transport
1854  * conns. Assumes the message has been fully pulled up and verified.
1855  *
1856  * Before getting here, the caller has called icmp_inbound_verify_v4()
1857  * that should have verified with ULP to prevent undoing the changes we're
1858  * going to make to DCE. For example, TCP might have verified that the packet
1859  * which generated error is in the send window.
1860  *
1861  * In some cases modified this MTU in the ICMP header packet; the caller
1862  * should pass to the matching ULP after this returns.
1863  */
1864 static void
1865 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1866 {
1867 	dce_t		*dce;
1868 	int		old_mtu;
1869 	int		mtu, orig_mtu;
1870 	ipaddr_t	dst;
1871 	boolean_t	disable_pmtud;
1872 	ill_t		*ill = ira->ira_ill;
1873 	ip_stack_t	*ipst = ill->ill_ipst;
1874 	uint_t		hdr_length;
1875 	ipha_t		*ipha;
1876 
1877 	/* Caller already pulled up everything. */
1878 	ipha = (ipha_t *)&icmph[1];
1879 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1880 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1881 	ASSERT(ill != NULL);
1882 
1883 	hdr_length = IPH_HDR_LENGTH(ipha);
1884 
1885 	/*
1886 	 * We handle path MTU for source routed packets since the DCE
1887 	 * is looked up using the final destination.
1888 	 */
1889 	dst = ip_get_dst(ipha);
1890 
1891 	dce = dce_lookup_and_add_v4(dst, ipst);
1892 	if (dce == NULL) {
1893 		/* Couldn't add a unique one - ENOMEM */
1894 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1895 		    ntohl(dst)));
1896 		return;
1897 	}
1898 
1899 	/* Check for MTU discovery advice as described in RFC 1191 */
1900 	mtu = ntohs(icmph->icmph_du_mtu);
1901 	orig_mtu = mtu;
1902 	disable_pmtud = B_FALSE;
1903 
1904 	mutex_enter(&dce->dce_lock);
1905 	if (dce->dce_flags & DCEF_PMTU)
1906 		old_mtu = dce->dce_pmtu;
1907 	else
1908 		old_mtu = ill->ill_mtu;
1909 
1910 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1911 		uint32_t length;
1912 		int	i;
1913 
1914 		/*
1915 		 * Use the table from RFC 1191 to figure out
1916 		 * the next "plateau" based on the length in
1917 		 * the original IP packet.
1918 		 */
1919 		length = ntohs(ipha->ipha_length);
1920 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1921 		    uint32_t, length);
1922 		if (old_mtu <= length &&
1923 		    old_mtu >= length - hdr_length) {
1924 			/*
1925 			 * Handle broken BSD 4.2 systems that
1926 			 * return the wrong ipha_length in ICMP
1927 			 * errors.
1928 			 */
1929 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1930 			    length, old_mtu));
1931 			length -= hdr_length;
1932 		}
1933 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1934 			if (length > icmp_frag_size_table[i])
1935 				break;
1936 		}
1937 		if (i == A_CNT(icmp_frag_size_table)) {
1938 			/* Smaller than IP_MIN_MTU! */
1939 			ip1dbg(("Too big for packet size %d\n",
1940 			    length));
1941 			disable_pmtud = B_TRUE;
1942 			mtu = ipst->ips_ip_pmtu_min;
1943 		} else {
1944 			mtu = icmp_frag_size_table[i];
1945 			ip1dbg(("Calculated mtu %d, packet size %d, "
1946 			    "before %d\n", mtu, length, old_mtu));
1947 			if (mtu < ipst->ips_ip_pmtu_min) {
1948 				mtu = ipst->ips_ip_pmtu_min;
1949 				disable_pmtud = B_TRUE;
1950 			}
1951 		}
1952 	}
1953 	if (disable_pmtud)
1954 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1955 	else
1956 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1957 
1958 	dce->dce_pmtu = MIN(old_mtu, mtu);
1959 	/* Prepare to send the new max frag size for the ULP. */
1960 	icmph->icmph_du_zero = 0;
1961 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1962 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1963 	    dce, int, orig_mtu, int, mtu);
1964 
1965 	/* We now have a PMTU for sure */
1966 	dce->dce_flags |= DCEF_PMTU;
1967 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1968 	mutex_exit(&dce->dce_lock);
1969 	/*
1970 	 * After dropping the lock the new value is visible to everyone.
1971 	 * Then we bump the generation number so any cached values reinspect
1972 	 * the dce_t.
1973 	 */
1974 	dce_increment_generation(dce);
1975 	dce_refrele(dce);
1976 }
1977 
1978 /*
1979  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1980  * calls this function.
1981  */
1982 static mblk_t *
1983 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1984 {
1985 	int length;
1986 
1987 	ASSERT(mp->b_datap->db_type == M_DATA);
1988 
1989 	/* icmp_inbound_v4 has already pulled up the whole error packet */
1990 	ASSERT(mp->b_cont == NULL);
1991 
1992 	/*
1993 	 * The length that we want to overlay is the inner header
1994 	 * and what follows it.
1995 	 */
1996 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
1997 
1998 	/*
1999 	 * Overlay the inner header and whatever follows it over the
2000 	 * outer header.
2001 	 */
2002 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2003 
2004 	/* Adjust for what we removed */
2005 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2006 	return (mp);
2007 }
2008 
2009 /*
2010  * Try to pass the ICMP message upstream in case the ULP cares.
2011  *
2012  * If the packet that caused the ICMP error is secure, we send
2013  * it to AH/ESP to make sure that the attached packet has a
2014  * valid association. ipha in the code below points to the
2015  * IP header of the packet that caused the error.
2016  *
2017  * For IPsec cases, we let the next-layer-up (which has access to
2018  * cached policy on the conn_t, or can query the SPD directly)
2019  * subtract out any IPsec overhead if they must.  We therefore make no
2020  * adjustments here for IPsec overhead.
2021  *
2022  * IFN could have been generated locally or by some router.
2023  *
2024  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2025  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2026  *	    This happens because IP adjusted its value of MTU on an
2027  *	    earlier IFN message and could not tell the upper layer,
2028  *	    the new adjusted value of MTU e.g. Packet was encrypted
2029  *	    or there was not enough information to fanout to upper
2030  *	    layers. Thus on the next outbound datagram, ire_send_wire
2031  *	    generates the IFN, where IPsec processing has *not* been
2032  *	    done.
2033  *
2034  *	    Note that we retain ixa_fragsize across IPsec thus once
2035  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2036  *	    no change the fragsize even if the path MTU changes before
2037  *	    we reach ip_output_post_ipsec.
2038  *
2039  *	    In the local case, IRAF_LOOPBACK will be set indicating
2040  *	    that IFN was generated locally.
2041  *
2042  * ROUTER : IFN could be secure or non-secure.
2043  *
2044  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2045  *	      packet in error has AH/ESP headers to validate the AH/ESP
2046  *	      headers. AH/ESP will verify whether there is a valid SA or
2047  *	      not and send it back. We will fanout again if we have more
2048  *	      data in the packet.
2049  *
2050  *	      If the packet in error does not have AH/ESP, we handle it
2051  *	      like any other case.
2052  *
2053  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2054  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2055  *	      valid SA or not and send it back. We will fanout again if
2056  *	      we have more data in the packet.
2057  *
2058  *	      If the packet in error does not have AH/ESP, we handle it
2059  *	      like any other case.
2060  *
2061  * The caller must have called icmp_inbound_verify_v4.
2062  */
2063 static void
2064 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2065 {
2066 	uint16_t	*up;	/* Pointer to ports in ULP header */
2067 	uint32_t	ports;	/* reversed ports for fanout */
2068 	ipha_t		ripha;	/* With reversed addresses */
2069 	ipha_t		*ipha;  /* Inner IP header */
2070 	uint_t		hdr_length; /* Inner IP header length */
2071 	tcpha_t		*tcpha;
2072 	conn_t		*connp;
2073 	ill_t		*ill = ira->ira_ill;
2074 	ip_stack_t	*ipst = ill->ill_ipst;
2075 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2076 	ill_t		*rill = ira->ira_rill;
2077 
2078 	/* Caller already pulled up everything. */
2079 	ipha = (ipha_t *)&icmph[1];
2080 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2081 	ASSERT(mp->b_cont == NULL);
2082 
2083 	hdr_length = IPH_HDR_LENGTH(ipha);
2084 	ira->ira_protocol = ipha->ipha_protocol;
2085 
2086 	/*
2087 	 * We need a separate IP header with the source and destination
2088 	 * addresses reversed to do fanout/classification because the ipha in
2089 	 * the ICMP error is in the form we sent it out.
2090 	 */
2091 	ripha.ipha_src = ipha->ipha_dst;
2092 	ripha.ipha_dst = ipha->ipha_src;
2093 	ripha.ipha_protocol = ipha->ipha_protocol;
2094 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2095 
2096 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2097 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2098 	    ntohl(ipha->ipha_dst),
2099 	    icmph->icmph_type, icmph->icmph_code));
2100 
2101 	switch (ipha->ipha_protocol) {
2102 	case IPPROTO_UDP:
2103 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2104 
2105 		/* Attempt to find a client stream based on port. */
2106 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2107 		    ntohs(up[0]), ntohs(up[1])));
2108 
2109 		/* Note that we send error to all matches. */
2110 		ira->ira_flags |= IRAF_ICMP_ERROR;
2111 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2112 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2113 		return;
2114 
2115 	case IPPROTO_TCP:
2116 		/*
2117 		 * Find a TCP client stream for this packet.
2118 		 * Note that we do a reverse lookup since the header is
2119 		 * in the form we sent it out.
2120 		 */
2121 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2122 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2123 		    ipst);
2124 		if (connp == NULL)
2125 			goto discard_pkt;
2126 
2127 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2128 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2129 			mp = ipsec_check_inbound_policy(mp, connp,
2130 			    ipha, NULL, ira);
2131 			if (mp == NULL) {
2132 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2133 				/* Note that mp is NULL */
2134 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2135 				CONN_DEC_REF(connp);
2136 				return;
2137 			}
2138 		}
2139 
2140 		ira->ira_flags |= IRAF_ICMP_ERROR;
2141 		ira->ira_ill = ira->ira_rill = NULL;
2142 		if (IPCL_IS_TCP(connp)) {
2143 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2144 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2145 			    SQTAG_TCP_INPUT_ICMP_ERR);
2146 		} else {
2147 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2148 			(connp->conn_recv)(connp, mp, NULL, ira);
2149 			CONN_DEC_REF(connp);
2150 		}
2151 		ira->ira_ill = ill;
2152 		ira->ira_rill = rill;
2153 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2154 		return;
2155 
2156 	case IPPROTO_SCTP:
2157 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2158 		/* Find a SCTP client stream for this packet. */
2159 		((uint16_t *)&ports)[0] = up[1];
2160 		((uint16_t *)&ports)[1] = up[0];
2161 
2162 		ira->ira_flags |= IRAF_ICMP_ERROR;
2163 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2164 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2165 		return;
2166 
2167 	case IPPROTO_ESP:
2168 	case IPPROTO_AH:
2169 		if (!ipsec_loaded(ipss)) {
2170 			ip_proto_not_sup(mp, ira);
2171 			return;
2172 		}
2173 
2174 		if (ipha->ipha_protocol == IPPROTO_ESP)
2175 			mp = ipsecesp_icmp_error(mp, ira);
2176 		else
2177 			mp = ipsecah_icmp_error(mp, ira);
2178 		if (mp == NULL)
2179 			return;
2180 
2181 		/* Just in case ipsec didn't preserve the NULL b_cont */
2182 		if (mp->b_cont != NULL) {
2183 			if (!pullupmsg(mp, -1))
2184 				goto discard_pkt;
2185 		}
2186 
2187 		/*
2188 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2189 		 * correct, but we don't use them any more here.
2190 		 *
2191 		 * If succesful, the mp has been modified to not include
2192 		 * the ESP/AH header so we can fanout to the ULP's icmp
2193 		 * error handler.
2194 		 */
2195 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2196 			goto truncated;
2197 
2198 		/* Verify the modified message before any further processes. */
2199 		ipha = (ipha_t *)mp->b_rptr;
2200 		hdr_length = IPH_HDR_LENGTH(ipha);
2201 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2202 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2203 			freemsg(mp);
2204 			return;
2205 		}
2206 
2207 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2208 		return;
2209 
2210 	case IPPROTO_ENCAP: {
2211 		/* Look for self-encapsulated packets that caused an error */
2212 		ipha_t *in_ipha;
2213 
2214 		/*
2215 		 * Caller has verified that length has to be
2216 		 * at least the size of IP header.
2217 		 */
2218 		ASSERT(hdr_length >= sizeof (ipha_t));
2219 		/*
2220 		 * Check the sanity of the inner IP header like
2221 		 * we did for the outer header.
2222 		 */
2223 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2224 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2225 			goto discard_pkt;
2226 		}
2227 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2228 			goto discard_pkt;
2229 		}
2230 		/* Check for Self-encapsulated tunnels */
2231 		if (in_ipha->ipha_src == ipha->ipha_src &&
2232 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2233 
2234 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2235 			    in_ipha);
2236 			if (mp == NULL)
2237 				goto discard_pkt;
2238 
2239 			/*
2240 			 * Just in case self_encap didn't preserve the NULL
2241 			 * b_cont
2242 			 */
2243 			if (mp->b_cont != NULL) {
2244 				if (!pullupmsg(mp, -1))
2245 					goto discard_pkt;
2246 			}
2247 			/*
2248 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2249 			 * longer correct, but we don't use them any more here.
2250 			 */
2251 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2252 				goto truncated;
2253 
2254 			/*
2255 			 * Verify the modified message before any further
2256 			 * processes.
2257 			 */
2258 			ipha = (ipha_t *)mp->b_rptr;
2259 			hdr_length = IPH_HDR_LENGTH(ipha);
2260 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2261 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2262 				freemsg(mp);
2263 				return;
2264 			}
2265 
2266 			/*
2267 			 * The packet in error is self-encapsualted.
2268 			 * And we are finding it further encapsulated
2269 			 * which we could not have possibly generated.
2270 			 */
2271 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2272 				goto discard_pkt;
2273 			}
2274 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2275 			return;
2276 		}
2277 		/* No self-encapsulated */
2278 		/* FALLTHRU */
2279 	}
2280 	case IPPROTO_IPV6:
2281 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2282 		    &ripha.ipha_dst, ipst)) != NULL) {
2283 			ira->ira_flags |= IRAF_ICMP_ERROR;
2284 			connp->conn_recvicmp(connp, mp, NULL, ira);
2285 			CONN_DEC_REF(connp);
2286 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2287 			return;
2288 		}
2289 		/*
2290 		 * No IP tunnel is interested, fallthrough and see
2291 		 * if a raw socket will want it.
2292 		 */
2293 		/* FALLTHRU */
2294 	default:
2295 		ira->ira_flags |= IRAF_ICMP_ERROR;
2296 		ip_fanout_proto_v4(mp, &ripha, ira);
2297 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2298 		return;
2299 	}
2300 	/* NOTREACHED */
2301 discard_pkt:
2302 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2303 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2304 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2305 	freemsg(mp);
2306 	return;
2307 
2308 truncated:
2309 	/* We pulled up everthing already. Must be truncated */
2310 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2311 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2312 	freemsg(mp);
2313 }
2314 
2315 /*
2316  * Common IP options parser.
2317  *
2318  * Setup routine: fill in *optp with options-parsing state, then
2319  * tail-call ipoptp_next to return the first option.
2320  */
2321 uint8_t
2322 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2323 {
2324 	uint32_t totallen; /* total length of all options */
2325 
2326 	totallen = ipha->ipha_version_and_hdr_length -
2327 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2328 	totallen <<= 2;
2329 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2330 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2331 	optp->ipoptp_flags = 0;
2332 	return (ipoptp_next(optp));
2333 }
2334 
2335 /* Like above but without an ipha_t */
2336 uint8_t
2337 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2338 {
2339 	optp->ipoptp_next = opt;
2340 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2341 	optp->ipoptp_flags = 0;
2342 	return (ipoptp_next(optp));
2343 }
2344 
2345 /*
2346  * Common IP options parser: extract next option.
2347  */
2348 uint8_t
2349 ipoptp_next(ipoptp_t *optp)
2350 {
2351 	uint8_t *end = optp->ipoptp_end;
2352 	uint8_t *cur = optp->ipoptp_next;
2353 	uint8_t opt, len, pointer;
2354 
2355 	/*
2356 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2357 	 * has been corrupted.
2358 	 */
2359 	ASSERT(cur <= end);
2360 
2361 	if (cur == end)
2362 		return (IPOPT_EOL);
2363 
2364 	opt = cur[IPOPT_OPTVAL];
2365 
2366 	/*
2367 	 * Skip any NOP options.
2368 	 */
2369 	while (opt == IPOPT_NOP) {
2370 		cur++;
2371 		if (cur == end)
2372 			return (IPOPT_EOL);
2373 		opt = cur[IPOPT_OPTVAL];
2374 	}
2375 
2376 	if (opt == IPOPT_EOL)
2377 		return (IPOPT_EOL);
2378 
2379 	/*
2380 	 * Option requiring a length.
2381 	 */
2382 	if ((cur + 1) >= end) {
2383 		optp->ipoptp_flags |= IPOPTP_ERROR;
2384 		return (IPOPT_EOL);
2385 	}
2386 	len = cur[IPOPT_OLEN];
2387 	if (len < 2) {
2388 		optp->ipoptp_flags |= IPOPTP_ERROR;
2389 		return (IPOPT_EOL);
2390 	}
2391 	optp->ipoptp_cur = cur;
2392 	optp->ipoptp_len = len;
2393 	optp->ipoptp_next = cur + len;
2394 	if (cur + len > end) {
2395 		optp->ipoptp_flags |= IPOPTP_ERROR;
2396 		return (IPOPT_EOL);
2397 	}
2398 
2399 	/*
2400 	 * For the options which require a pointer field, make sure
2401 	 * its there, and make sure it points to either something
2402 	 * inside this option, or the end of the option.
2403 	 */
2404 	switch (opt) {
2405 	case IPOPT_RR:
2406 	case IPOPT_TS:
2407 	case IPOPT_LSRR:
2408 	case IPOPT_SSRR:
2409 		if (len <= IPOPT_OFFSET) {
2410 			optp->ipoptp_flags |= IPOPTP_ERROR;
2411 			return (opt);
2412 		}
2413 		pointer = cur[IPOPT_OFFSET];
2414 		if (pointer - 1 > len) {
2415 			optp->ipoptp_flags |= IPOPTP_ERROR;
2416 			return (opt);
2417 		}
2418 		break;
2419 	}
2420 
2421 	/*
2422 	 * Sanity check the pointer field based on the type of the
2423 	 * option.
2424 	 */
2425 	switch (opt) {
2426 	case IPOPT_RR:
2427 	case IPOPT_SSRR:
2428 	case IPOPT_LSRR:
2429 		if (pointer < IPOPT_MINOFF_SR)
2430 			optp->ipoptp_flags |= IPOPTP_ERROR;
2431 		break;
2432 	case IPOPT_TS:
2433 		if (pointer < IPOPT_MINOFF_IT)
2434 			optp->ipoptp_flags |= IPOPTP_ERROR;
2435 		/*
2436 		 * Note that the Internet Timestamp option also
2437 		 * contains two four bit fields (the Overflow field,
2438 		 * and the Flag field), which follow the pointer
2439 		 * field.  We don't need to check that these fields
2440 		 * fall within the length of the option because this
2441 		 * was implicitely done above.  We've checked that the
2442 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2443 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2444 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2445 		 */
2446 		ASSERT(len > IPOPT_POS_OV_FLG);
2447 		break;
2448 	}
2449 
2450 	return (opt);
2451 }
2452 
2453 /*
2454  * Use the outgoing IP header to create an IP_OPTIONS option the way
2455  * it was passed down from the application.
2456  *
2457  * This is compatible with BSD in that it returns
2458  * the reverse source route with the final destination
2459  * as the last entry. The first 4 bytes of the option
2460  * will contain the final destination.
2461  */
2462 int
2463 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2464 {
2465 	ipoptp_t	opts;
2466 	uchar_t		*opt;
2467 	uint8_t		optval;
2468 	uint8_t		optlen;
2469 	uint32_t	len = 0;
2470 	uchar_t		*buf1 = buf;
2471 	uint32_t	totallen;
2472 	ipaddr_t	dst;
2473 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2474 
2475 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2476 		return (0);
2477 
2478 	totallen = ipp->ipp_ipv4_options_len;
2479 	if (totallen & 0x3)
2480 		return (0);
2481 
2482 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2483 	len += IP_ADDR_LEN;
2484 	bzero(buf1, IP_ADDR_LEN);
2485 
2486 	dst = connp->conn_faddr_v4;
2487 
2488 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2489 	    optval != IPOPT_EOL;
2490 	    optval = ipoptp_next(&opts)) {
2491 		int	off;
2492 
2493 		opt = opts.ipoptp_cur;
2494 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2495 			break;
2496 		}
2497 		optlen = opts.ipoptp_len;
2498 
2499 		switch (optval) {
2500 		case IPOPT_SSRR:
2501 		case IPOPT_LSRR:
2502 
2503 			/*
2504 			 * Insert destination as the first entry in the source
2505 			 * route and move down the entries on step.
2506 			 * The last entry gets placed at buf1.
2507 			 */
2508 			buf[IPOPT_OPTVAL] = optval;
2509 			buf[IPOPT_OLEN] = optlen;
2510 			buf[IPOPT_OFFSET] = optlen;
2511 
2512 			off = optlen - IP_ADDR_LEN;
2513 			if (off < 0) {
2514 				/* No entries in source route */
2515 				break;
2516 			}
2517 			/* Last entry in source route if not already set */
2518 			if (dst == INADDR_ANY)
2519 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2520 			off -= IP_ADDR_LEN;
2521 
2522 			while (off > 0) {
2523 				bcopy(opt + off,
2524 				    buf + off + IP_ADDR_LEN,
2525 				    IP_ADDR_LEN);
2526 				off -= IP_ADDR_LEN;
2527 			}
2528 			/* ipha_dst into first slot */
2529 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2530 			    IP_ADDR_LEN);
2531 			buf += optlen;
2532 			len += optlen;
2533 			break;
2534 
2535 		default:
2536 			bcopy(opt, buf, optlen);
2537 			buf += optlen;
2538 			len += optlen;
2539 			break;
2540 		}
2541 	}
2542 done:
2543 	/* Pad the resulting options */
2544 	while (len & 0x3) {
2545 		*buf++ = IPOPT_EOL;
2546 		len++;
2547 	}
2548 	return (len);
2549 }
2550 
2551 /*
2552  * Update any record route or timestamp options to include this host.
2553  * Reverse any source route option.
2554  * This routine assumes that the options are well formed i.e. that they
2555  * have already been checked.
2556  */
2557 static void
2558 icmp_options_update(ipha_t *ipha)
2559 {
2560 	ipoptp_t	opts;
2561 	uchar_t		*opt;
2562 	uint8_t		optval;
2563 	ipaddr_t	src;		/* Our local address */
2564 	ipaddr_t	dst;
2565 
2566 	ip2dbg(("icmp_options_update\n"));
2567 	src = ipha->ipha_src;
2568 	dst = ipha->ipha_dst;
2569 
2570 	for (optval = ipoptp_first(&opts, ipha);
2571 	    optval != IPOPT_EOL;
2572 	    optval = ipoptp_next(&opts)) {
2573 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2574 		opt = opts.ipoptp_cur;
2575 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2576 		    optval, opts.ipoptp_len));
2577 		switch (optval) {
2578 			int off1, off2;
2579 		case IPOPT_SSRR:
2580 		case IPOPT_LSRR:
2581 			/*
2582 			 * Reverse the source route.  The first entry
2583 			 * should be the next to last one in the current
2584 			 * source route (the last entry is our address).
2585 			 * The last entry should be the final destination.
2586 			 */
2587 			off1 = IPOPT_MINOFF_SR - 1;
2588 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2589 			if (off2 < 0) {
2590 				/* No entries in source route */
2591 				ip1dbg((
2592 				    "icmp_options_update: bad src route\n"));
2593 				break;
2594 			}
2595 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2596 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2597 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2598 			off2 -= IP_ADDR_LEN;
2599 
2600 			while (off1 < off2) {
2601 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2602 				bcopy((char *)opt + off2, (char *)opt + off1,
2603 				    IP_ADDR_LEN);
2604 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2605 				off1 += IP_ADDR_LEN;
2606 				off2 -= IP_ADDR_LEN;
2607 			}
2608 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2609 			break;
2610 		}
2611 	}
2612 }
2613 
2614 /*
2615  * Process received ICMP Redirect messages.
2616  * Assumes the caller has verified that the headers are in the pulled up mblk.
2617  * Consumes mp.
2618  */
2619 static void
2620 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2621 {
2622 	ire_t		*ire, *nire;
2623 	ire_t		*prev_ire;
2624 	ipaddr_t  	src, dst, gateway;
2625 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2626 	ipha_t		*inner_ipha;	/* Inner IP header */
2627 
2628 	/* Caller already pulled up everything. */
2629 	inner_ipha = (ipha_t *)&icmph[1];
2630 	src = ipha->ipha_src;
2631 	dst = inner_ipha->ipha_dst;
2632 	gateway = icmph->icmph_rd_gateway;
2633 	/* Make sure the new gateway is reachable somehow. */
2634 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2635 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2636 	/*
2637 	 * Make sure we had a route for the dest in question and that
2638 	 * that route was pointing to the old gateway (the source of the
2639 	 * redirect packet.)
2640 	 * We do longest match and then compare ire_gateway_addr below.
2641 	 */
2642 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2643 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2644 	/*
2645 	 * Check that
2646 	 *	the redirect was not from ourselves
2647 	 *	the new gateway and the old gateway are directly reachable
2648 	 */
2649 	if (prev_ire == NULL || ire == NULL ||
2650 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2651 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2652 	    !(ire->ire_type & IRE_IF_ALL) ||
2653 	    prev_ire->ire_gateway_addr != src) {
2654 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2655 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2656 		freemsg(mp);
2657 		if (ire != NULL)
2658 			ire_refrele(ire);
2659 		if (prev_ire != NULL)
2660 			ire_refrele(prev_ire);
2661 		return;
2662 	}
2663 
2664 	ire_refrele(prev_ire);
2665 	ire_refrele(ire);
2666 
2667 	/*
2668 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2669 	 * require TOS routing
2670 	 */
2671 	switch (icmph->icmph_code) {
2672 	case 0:
2673 	case 1:
2674 		/* TODO: TOS specificity for cases 2 and 3 */
2675 	case 2:
2676 	case 3:
2677 		break;
2678 	default:
2679 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2680 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2681 		freemsg(mp);
2682 		return;
2683 	}
2684 	/*
2685 	 * Create a Route Association.  This will allow us to remember that
2686 	 * someone we believe told us to use the particular gateway.
2687 	 */
2688 	ire = ire_create(
2689 	    (uchar_t *)&dst,			/* dest addr */
2690 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2691 	    (uchar_t *)&gateway,		/* gateway addr */
2692 	    IRE_HOST,
2693 	    NULL,				/* ill */
2694 	    ALL_ZONES,
2695 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2696 	    NULL,				/* tsol_gc_t */
2697 	    ipst);
2698 
2699 	if (ire == NULL) {
2700 		freemsg(mp);
2701 		return;
2702 	}
2703 	nire = ire_add(ire);
2704 	/* Check if it was a duplicate entry */
2705 	if (nire != NULL && nire != ire) {
2706 		ASSERT(nire->ire_identical_ref > 1);
2707 		ire_delete(nire);
2708 		ire_refrele(nire);
2709 		nire = NULL;
2710 	}
2711 	ire = nire;
2712 	if (ire != NULL) {
2713 		ire_refrele(ire);		/* Held in ire_add */
2714 
2715 		/* tell routing sockets that we received a redirect */
2716 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2717 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2718 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2719 	}
2720 
2721 	/*
2722 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2723 	 * This together with the added IRE has the effect of
2724 	 * modifying an existing redirect.
2725 	 */
2726 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2727 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2728 	if (prev_ire != NULL) {
2729 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2730 			ire_delete(prev_ire);
2731 		ire_refrele(prev_ire);
2732 	}
2733 
2734 	freemsg(mp);
2735 }
2736 
2737 /*
2738  * Generate an ICMP parameter problem message.
2739  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2740  * constructed by the caller.
2741  */
2742 static void
2743 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2744 {
2745 	icmph_t	icmph;
2746 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2747 
2748 	mp = icmp_pkt_err_ok(mp, ira);
2749 	if (mp == NULL)
2750 		return;
2751 
2752 	bzero(&icmph, sizeof (icmph_t));
2753 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2754 	icmph.icmph_pp_ptr = ptr;
2755 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2756 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2757 }
2758 
2759 /*
2760  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2761  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2762  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2763  * an icmp error packet can be sent.
2764  * Assigns an appropriate source address to the packet. If ipha_dst is
2765  * one of our addresses use it for source. Otherwise let ip_output_simple
2766  * pick the source address.
2767  */
2768 static void
2769 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2770 {
2771 	ipaddr_t dst;
2772 	icmph_t	*icmph;
2773 	ipha_t	*ipha;
2774 	uint_t	len_needed;
2775 	size_t	msg_len;
2776 	mblk_t	*mp1;
2777 	ipaddr_t src;
2778 	ire_t	*ire;
2779 	ip_xmit_attr_t ixas;
2780 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2781 
2782 	ipha = (ipha_t *)mp->b_rptr;
2783 
2784 	bzero(&ixas, sizeof (ixas));
2785 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2786 	ixas.ixa_zoneid = ira->ira_zoneid;
2787 	ixas.ixa_ifindex = 0;
2788 	ixas.ixa_ipst = ipst;
2789 	ixas.ixa_cred = kcred;
2790 	ixas.ixa_cpid = NOPID;
2791 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2792 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2793 
2794 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2795 		/*
2796 		 * Apply IPsec based on how IPsec was applied to
2797 		 * the packet that had the error.
2798 		 *
2799 		 * If it was an outbound packet that caused the ICMP
2800 		 * error, then the caller will have setup the IRA
2801 		 * appropriately.
2802 		 */
2803 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2804 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2805 			/* Note: mp already consumed and ip_drop_packet done */
2806 			return;
2807 		}
2808 	} else {
2809 		/*
2810 		 * This is in clear. The icmp message we are building
2811 		 * here should go out in clear, independent of our policy.
2812 		 */
2813 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2814 	}
2815 
2816 	/* Remember our eventual destination */
2817 	dst = ipha->ipha_src;
2818 
2819 	/*
2820 	 * If the packet was for one of our unicast addresses, make
2821 	 * sure we respond with that as the source. Otherwise
2822 	 * have ip_output_simple pick the source address.
2823 	 */
2824 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2825 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2826 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2827 	if (ire != NULL) {
2828 		ire_refrele(ire);
2829 		src = ipha->ipha_dst;
2830 	} else {
2831 		src = INADDR_ANY;
2832 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2833 	}
2834 
2835 	/*
2836 	 * Check if we can send back more then 8 bytes in addition to
2837 	 * the IP header.  We try to send 64 bytes of data and the internal
2838 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2839 	 */
2840 	len_needed = IPH_HDR_LENGTH(ipha);
2841 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2842 	    ipha->ipha_protocol == IPPROTO_IPV6) {
2843 		if (!pullupmsg(mp, -1)) {
2844 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2845 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2846 			freemsg(mp);
2847 			return;
2848 		}
2849 		ipha = (ipha_t *)mp->b_rptr;
2850 
2851 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2852 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2853 			    len_needed));
2854 		} else {
2855 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2856 
2857 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2858 			len_needed += ip_hdr_length_v6(mp, ip6h);
2859 		}
2860 	}
2861 	len_needed += ipst->ips_ip_icmp_return;
2862 	msg_len = msgdsize(mp);
2863 	if (msg_len > len_needed) {
2864 		(void) adjmsg(mp, len_needed - msg_len);
2865 		msg_len = len_needed;
2866 	}
2867 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2868 	if (mp1 == NULL) {
2869 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2870 		freemsg(mp);
2871 		return;
2872 	}
2873 	mp1->b_cont = mp;
2874 	mp = mp1;
2875 
2876 	/*
2877 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2878 	 * node generates be accepted in peace by all on-host destinations.
2879 	 * If we do NOT assume that all on-host destinations trust
2880 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2881 	 * (Look for IXAF_TRUSTED_ICMP).
2882 	 */
2883 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2884 
2885 	ipha = (ipha_t *)mp->b_rptr;
2886 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2887 	*ipha = icmp_ipha;
2888 	ipha->ipha_src = src;
2889 	ipha->ipha_dst = dst;
2890 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2891 	msg_len += sizeof (icmp_ipha) + len;
2892 	if (msg_len > IP_MAXPACKET) {
2893 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
2894 		msg_len = IP_MAXPACKET;
2895 	}
2896 	ipha->ipha_length = htons((uint16_t)msg_len);
2897 	icmph = (icmph_t *)&ipha[1];
2898 	bcopy(stuff, icmph, len);
2899 	icmph->icmph_checksum = 0;
2900 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2901 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2902 
2903 	(void) ip_output_simple(mp, &ixas);
2904 	ixa_cleanup(&ixas);
2905 }
2906 
2907 /*
2908  * Determine if an ICMP error packet can be sent given the rate limit.
2909  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2910  * in milliseconds) and a burst size. Burst size number of packets can
2911  * be sent arbitrarely closely spaced.
2912  * The state is tracked using two variables to implement an approximate
2913  * token bucket filter:
2914  *	icmp_pkt_err_last - lbolt value when the last burst started
2915  *	icmp_pkt_err_sent - number of packets sent in current burst
2916  */
2917 boolean_t
2918 icmp_err_rate_limit(ip_stack_t *ipst)
2919 {
2920 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2921 	uint_t refilled; /* Number of packets refilled in tbf since last */
2922 	/* Guard against changes by loading into local variable */
2923 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2924 
2925 	if (err_interval == 0)
2926 		return (B_FALSE);
2927 
2928 	if (ipst->ips_icmp_pkt_err_last > now) {
2929 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2930 		ipst->ips_icmp_pkt_err_last = 0;
2931 		ipst->ips_icmp_pkt_err_sent = 0;
2932 	}
2933 	/*
2934 	 * If we are in a burst update the token bucket filter.
2935 	 * Update the "last" time to be close to "now" but make sure
2936 	 * we don't loose precision.
2937 	 */
2938 	if (ipst->ips_icmp_pkt_err_sent != 0) {
2939 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2940 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
2941 			ipst->ips_icmp_pkt_err_sent = 0;
2942 		} else {
2943 			ipst->ips_icmp_pkt_err_sent -= refilled;
2944 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2945 		}
2946 	}
2947 	if (ipst->ips_icmp_pkt_err_sent == 0) {
2948 		/* Start of new burst */
2949 		ipst->ips_icmp_pkt_err_last = now;
2950 	}
2951 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2952 		ipst->ips_icmp_pkt_err_sent++;
2953 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2954 		    ipst->ips_icmp_pkt_err_sent));
2955 		return (B_FALSE);
2956 	}
2957 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
2958 	return (B_TRUE);
2959 }
2960 
2961 /*
2962  * Check if it is ok to send an IPv4 ICMP error packet in
2963  * response to the IPv4 packet in mp.
2964  * Free the message and return null if no
2965  * ICMP error packet should be sent.
2966  */
2967 static mblk_t *
2968 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2969 {
2970 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2971 	icmph_t	*icmph;
2972 	ipha_t	*ipha;
2973 	uint_t	len_needed;
2974 
2975 	if (!mp)
2976 		return (NULL);
2977 	ipha = (ipha_t *)mp->b_rptr;
2978 	if (ip_csum_hdr(ipha)) {
2979 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2980 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2981 		freemsg(mp);
2982 		return (NULL);
2983 	}
2984 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2985 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2986 	    CLASSD(ipha->ipha_dst) ||
2987 	    CLASSD(ipha->ipha_src) ||
2988 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2989 		/* Note: only errors to the fragment with offset 0 */
2990 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2991 		freemsg(mp);
2992 		return (NULL);
2993 	}
2994 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
2995 		/*
2996 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
2997 		 * errors in response to any ICMP errors.
2998 		 */
2999 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3000 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3001 			if (!pullupmsg(mp, len_needed)) {
3002 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3003 				freemsg(mp);
3004 				return (NULL);
3005 			}
3006 			ipha = (ipha_t *)mp->b_rptr;
3007 		}
3008 		icmph = (icmph_t *)
3009 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3010 		switch (icmph->icmph_type) {
3011 		case ICMP_DEST_UNREACHABLE:
3012 		case ICMP_SOURCE_QUENCH:
3013 		case ICMP_TIME_EXCEEDED:
3014 		case ICMP_PARAM_PROBLEM:
3015 		case ICMP_REDIRECT:
3016 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3017 			freemsg(mp);
3018 			return (NULL);
3019 		default:
3020 			break;
3021 		}
3022 	}
3023 	/*
3024 	 * If this is a labeled system, then check to see if we're allowed to
3025 	 * send a response to this particular sender.  If not, then just drop.
3026 	 */
3027 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3028 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3029 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3030 		freemsg(mp);
3031 		return (NULL);
3032 	}
3033 	if (icmp_err_rate_limit(ipst)) {
3034 		/*
3035 		 * Only send ICMP error packets every so often.
3036 		 * This should be done on a per port/source basis,
3037 		 * but for now this will suffice.
3038 		 */
3039 		freemsg(mp);
3040 		return (NULL);
3041 	}
3042 	return (mp);
3043 }
3044 
3045 /*
3046  * Called when a packet was sent out the same link that it arrived on.
3047  * Check if it is ok to send a redirect and then send it.
3048  */
3049 void
3050 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3051     ip_recv_attr_t *ira)
3052 {
3053 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3054 	ipaddr_t	src, nhop;
3055 	mblk_t		*mp1;
3056 	ire_t		*nhop_ire;
3057 
3058 	/*
3059 	 * Check the source address to see if it originated
3060 	 * on the same logical subnet it is going back out on.
3061 	 * If so, we should be able to send it a redirect.
3062 	 * Avoid sending a redirect if the destination
3063 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3064 	 * or if the packet was source routed out this interface.
3065 	 *
3066 	 * We avoid sending a redirect if the
3067 	 * destination is directly connected
3068 	 * because it is possible that multiple
3069 	 * IP subnets may have been configured on
3070 	 * the link, and the source may not
3071 	 * be on the same subnet as ip destination,
3072 	 * even though they are on the same
3073 	 * physical link.
3074 	 */
3075 	if ((ire->ire_type & IRE_ONLINK) ||
3076 	    ip_source_routed(ipha, ipst))
3077 		return;
3078 
3079 	nhop_ire = ire_nexthop(ire);
3080 	if (nhop_ire == NULL)
3081 		return;
3082 
3083 	nhop = nhop_ire->ire_addr;
3084 
3085 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3086 		ire_t	*ire2;
3087 
3088 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3089 		mutex_enter(&nhop_ire->ire_lock);
3090 		ire2 = nhop_ire->ire_dep_parent;
3091 		if (ire2 != NULL)
3092 			ire_refhold(ire2);
3093 		mutex_exit(&nhop_ire->ire_lock);
3094 		ire_refrele(nhop_ire);
3095 		nhop_ire = ire2;
3096 	}
3097 	if (nhop_ire == NULL)
3098 		return;
3099 
3100 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3101 
3102 	src = ipha->ipha_src;
3103 
3104 	/*
3105 	 * We look at the interface ire for the nexthop,
3106 	 * to see if ipha_src is in the same subnet
3107 	 * as the nexthop.
3108 	 */
3109 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3110 		/*
3111 		 * The source is directly connected.
3112 		 */
3113 		mp1 = copymsg(mp);
3114 		if (mp1 != NULL) {
3115 			icmp_send_redirect(mp1, nhop, ira);
3116 		}
3117 	}
3118 	ire_refrele(nhop_ire);
3119 }
3120 
3121 /*
3122  * Generate an ICMP redirect message.
3123  */
3124 static void
3125 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3126 {
3127 	icmph_t	icmph;
3128 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3129 
3130 	mp = icmp_pkt_err_ok(mp, ira);
3131 	if (mp == NULL)
3132 		return;
3133 
3134 	bzero(&icmph, sizeof (icmph_t));
3135 	icmph.icmph_type = ICMP_REDIRECT;
3136 	icmph.icmph_code = 1;
3137 	icmph.icmph_rd_gateway = gateway;
3138 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3139 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3140 }
3141 
3142 /*
3143  * Generate an ICMP time exceeded message.
3144  */
3145 void
3146 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3147 {
3148 	icmph_t	icmph;
3149 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3150 
3151 	mp = icmp_pkt_err_ok(mp, ira);
3152 	if (mp == NULL)
3153 		return;
3154 
3155 	bzero(&icmph, sizeof (icmph_t));
3156 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3157 	icmph.icmph_code = code;
3158 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3159 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3160 }
3161 
3162 /*
3163  * Generate an ICMP unreachable message.
3164  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3165  * constructed by the caller.
3166  */
3167 void
3168 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3169 {
3170 	icmph_t	icmph;
3171 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3172 
3173 	mp = icmp_pkt_err_ok(mp, ira);
3174 	if (mp == NULL)
3175 		return;
3176 
3177 	bzero(&icmph, sizeof (icmph_t));
3178 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3179 	icmph.icmph_code = code;
3180 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3181 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3182 }
3183 
3184 /*
3185  * Latch in the IPsec state for a stream based the policy in the listener
3186  * and the actions in the ip_recv_attr_t.
3187  * Called directly from TCP and SCTP.
3188  */
3189 boolean_t
3190 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3191 {
3192 	ASSERT(lconnp->conn_policy != NULL);
3193 	ASSERT(connp->conn_policy == NULL);
3194 
3195 	IPPH_REFHOLD(lconnp->conn_policy);
3196 	connp->conn_policy = lconnp->conn_policy;
3197 
3198 	if (ira->ira_ipsec_action != NULL) {
3199 		if (connp->conn_latch == NULL) {
3200 			connp->conn_latch = iplatch_create();
3201 			if (connp->conn_latch == NULL)
3202 				return (B_FALSE);
3203 		}
3204 		ipsec_latch_inbound(connp, ira);
3205 	}
3206 	return (B_TRUE);
3207 }
3208 
3209 /*
3210  * Verify whether or not the IP address is a valid local address.
3211  * Could be a unicast, including one for a down interface.
3212  * If allow_mcbc then a multicast or broadcast address is also
3213  * acceptable.
3214  *
3215  * In the case of a broadcast/multicast address, however, the
3216  * upper protocol is expected to reset the src address
3217  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3218  * no packets are emitted with broadcast/multicast address as
3219  * source address (that violates hosts requirements RFC 1122)
3220  * The addresses valid for bind are:
3221  *	(1) - INADDR_ANY (0)
3222  *	(2) - IP address of an UP interface
3223  *	(3) - IP address of a DOWN interface
3224  *	(4) - valid local IP broadcast addresses. In this case
3225  *	the conn will only receive packets destined to
3226  *	the specified broadcast address.
3227  *	(5) - a multicast address. In this case
3228  *	the conn will only receive packets destined to
3229  *	the specified multicast address. Note: the
3230  *	application still has to issue an
3231  *	IP_ADD_MEMBERSHIP socket option.
3232  *
3233  * In all the above cases, the bound address must be valid in the current zone.
3234  * When the address is loopback, multicast or broadcast, there might be many
3235  * matching IREs so bind has to look up based on the zone.
3236  */
3237 ip_laddr_t
3238 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3239     ip_stack_t *ipst, boolean_t allow_mcbc)
3240 {
3241 	ire_t *src_ire;
3242 
3243 	ASSERT(src_addr != INADDR_ANY);
3244 
3245 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3246 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3247 
3248 	/*
3249 	 * If an address other than in6addr_any is requested,
3250 	 * we verify that it is a valid address for bind
3251 	 * Note: Following code is in if-else-if form for
3252 	 * readability compared to a condition check.
3253 	 */
3254 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3255 		/*
3256 		 * (2) Bind to address of local UP interface
3257 		 */
3258 		ire_refrele(src_ire);
3259 		return (IPVL_UNICAST_UP);
3260 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3261 		/*
3262 		 * (4) Bind to broadcast address
3263 		 */
3264 		ire_refrele(src_ire);
3265 		if (allow_mcbc)
3266 			return (IPVL_BCAST);
3267 		else
3268 			return (IPVL_BAD);
3269 	} else if (CLASSD(src_addr)) {
3270 		/* (5) bind to multicast address. */
3271 		if (src_ire != NULL)
3272 			ire_refrele(src_ire);
3273 
3274 		if (allow_mcbc)
3275 			return (IPVL_MCAST);
3276 		else
3277 			return (IPVL_BAD);
3278 	} else {
3279 		ipif_t *ipif;
3280 
3281 		/*
3282 		 * (3) Bind to address of local DOWN interface?
3283 		 * (ipif_lookup_addr() looks up all interfaces
3284 		 * but we do not get here for UP interfaces
3285 		 * - case (2) above)
3286 		 */
3287 		if (src_ire != NULL)
3288 			ire_refrele(src_ire);
3289 
3290 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3291 		if (ipif == NULL)
3292 			return (IPVL_BAD);
3293 
3294 		/* Not a useful source? */
3295 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3296 			ipif_refrele(ipif);
3297 			return (IPVL_BAD);
3298 		}
3299 		ipif_refrele(ipif);
3300 		return (IPVL_UNICAST_DOWN);
3301 	}
3302 }
3303 
3304 /*
3305  * Insert in the bind fanout for IPv4 and IPv6.
3306  * The caller should already have used ip_laddr_verify_v*() before calling
3307  * this.
3308  */
3309 int
3310 ip_laddr_fanout_insert(conn_t *connp)
3311 {
3312 	int		error;
3313 
3314 	/*
3315 	 * Allow setting new policies. For example, disconnects result
3316 	 * in us being called. As we would have set conn_policy_cached
3317 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3318 	 * can change after the disconnect.
3319 	 */
3320 	connp->conn_policy_cached = B_FALSE;
3321 
3322 	error = ipcl_bind_insert(connp);
3323 	if (error != 0) {
3324 		if (connp->conn_anon_port) {
3325 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3326 			    connp->conn_mlp_type, connp->conn_proto,
3327 			    ntohs(connp->conn_lport), B_FALSE);
3328 		}
3329 		connp->conn_mlp_type = mlptSingle;
3330 	}
3331 	return (error);
3332 }
3333 
3334 /*
3335  * Verify that both the source and destination addresses are valid. If
3336  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3337  * i.e. have no route to it.  Protocols like TCP want to verify destination
3338  * reachability, while tunnels do not.
3339  *
3340  * Determine the route, the interface, and (optionally) the source address
3341  * to use to reach a given destination.
3342  * Note that we allow connect to broadcast and multicast addresses when
3343  * IPDF_ALLOW_MCBC is set.
3344  * first_hop and dst_addr are normally the same, but if source routing
3345  * they will differ; in that case the first_hop is what we'll use for the
3346  * routing lookup but the dce and label checks will be done on dst_addr,
3347  *
3348  * If uinfo is set, then we fill in the best available information
3349  * we have for the destination. This is based on (in priority order) any
3350  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3351  * ill_mtu.
3352  *
3353  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3354  * always do the label check on dst_addr.
3355  */
3356 int
3357 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3358     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3359 {
3360 	ire_t		*ire = NULL;
3361 	int		error = 0;
3362 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3363 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3364 	ip_stack_t	*ipst = ixa->ixa_ipst;
3365 	dce_t		*dce;
3366 	uint_t		pmtu;
3367 	uint_t		generation;
3368 	nce_t		*nce;
3369 	ill_t		*ill = NULL;
3370 	boolean_t	multirt = B_FALSE;
3371 
3372 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3373 
3374 	/*
3375 	 * We never send to zero; the ULPs map it to the loopback address.
3376 	 * We can't allow it since we use zero to mean unitialized in some
3377 	 * places.
3378 	 */
3379 	ASSERT(dst_addr != INADDR_ANY);
3380 
3381 	if (is_system_labeled()) {
3382 		ts_label_t *tsl = NULL;
3383 
3384 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3385 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3386 		if (error != 0)
3387 			return (error);
3388 		if (tsl != NULL) {
3389 			/* Update the label */
3390 			ip_xmit_attr_replace_tsl(ixa, tsl);
3391 		}
3392 	}
3393 
3394 	setsrc = INADDR_ANY;
3395 	/*
3396 	 * Select a route; For IPMP interfaces, we would only select
3397 	 * a "hidden" route (i.e., going through a specific under_ill)
3398 	 * if ixa_ifindex has been specified.
3399 	 */
3400 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3401 	    &generation, &setsrc, &error, &multirt);
3402 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3403 	if (error != 0)
3404 		goto bad_addr;
3405 
3406 	/*
3407 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3408 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3409 	 * Otherwise the destination needn't be reachable.
3410 	 *
3411 	 * If we match on a reject or black hole, then we've got a
3412 	 * local failure.  May as well fail out the connect() attempt,
3413 	 * since it's never going to succeed.
3414 	 */
3415 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3416 		/*
3417 		 * If we're verifying destination reachability, we always want
3418 		 * to complain here.
3419 		 *
3420 		 * If we're not verifying destination reachability but the
3421 		 * destination has a route, we still want to fail on the
3422 		 * temporary address and broadcast address tests.
3423 		 *
3424 		 * In both cases do we let the code continue so some reasonable
3425 		 * information is returned to the caller. That enables the
3426 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3427 		 * use the generation mismatch path to check for the unreachable
3428 		 * case thereby avoiding any specific check in the main path.
3429 		 */
3430 		ASSERT(generation == IRE_GENERATION_VERIFY);
3431 		if (flags & IPDF_VERIFY_DST) {
3432 			/*
3433 			 * Set errno but continue to set up ixa_ire to be
3434 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3435 			 * That allows callers to use ip_output to get an
3436 			 * ICMP error back.
3437 			 */
3438 			if (!(ire->ire_type & IRE_HOST))
3439 				error = ENETUNREACH;
3440 			else
3441 				error = EHOSTUNREACH;
3442 		}
3443 	}
3444 
3445 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3446 	    !(flags & IPDF_ALLOW_MCBC)) {
3447 		ire_refrele(ire);
3448 		ire = ire_reject(ipst, B_FALSE);
3449 		generation = IRE_GENERATION_VERIFY;
3450 		error = ENETUNREACH;
3451 	}
3452 
3453 	/* Cache things */
3454 	if (ixa->ixa_ire != NULL)
3455 		ire_refrele_notr(ixa->ixa_ire);
3456 #ifdef DEBUG
3457 	ire_refhold_notr(ire);
3458 	ire_refrele(ire);
3459 #endif
3460 	ixa->ixa_ire = ire;
3461 	ixa->ixa_ire_generation = generation;
3462 
3463 	/*
3464 	 * Ensure that ixa_dce is always set any time that ixa_ire is set,
3465 	 * since some callers will send a packet to conn_ip_output() even if
3466 	 * there's an error.
3467 	 */
3468 	if (flags & IPDF_UNIQUE_DCE) {
3469 		/* Fallback to the default dce if allocation fails */
3470 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3471 		if (dce != NULL)
3472 			generation = dce->dce_generation;
3473 		else
3474 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3475 	} else {
3476 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3477 	}
3478 	ASSERT(dce != NULL);
3479 	if (ixa->ixa_dce != NULL)
3480 		dce_refrele_notr(ixa->ixa_dce);
3481 #ifdef DEBUG
3482 	dce_refhold_notr(dce);
3483 	dce_refrele(dce);
3484 #endif
3485 	ixa->ixa_dce = dce;
3486 	ixa->ixa_dce_generation = generation;
3487 
3488 	/*
3489 	 * For multicast with multirt we have a flag passed back from
3490 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3491 	 * possible multicast address.
3492 	 * We also need a flag for multicast since we can't check
3493 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3494 	 */
3495 	if (multirt) {
3496 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3497 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3498 	} else {
3499 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3500 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3501 	}
3502 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3503 		/* Get an nce to cache. */
3504 		nce = ire_to_nce(ire, firsthop, NULL);
3505 		if (nce == NULL) {
3506 			/* Allocation failure? */
3507 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3508 		} else {
3509 			if (ixa->ixa_nce != NULL)
3510 				nce_refrele(ixa->ixa_nce);
3511 			ixa->ixa_nce = nce;
3512 		}
3513 	}
3514 
3515 	/*
3516 	 * If the source address is a loopback address, the
3517 	 * destination had best be local or multicast.
3518 	 * If we are sending to an IRE_LOCAL using a loopback source then
3519 	 * it had better be the same zoneid.
3520 	 */
3521 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3522 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3523 			ire = NULL;	/* Stored in ixa_ire */
3524 			error = EADDRNOTAVAIL;
3525 			goto bad_addr;
3526 		}
3527 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3528 			ire = NULL;	/* Stored in ixa_ire */
3529 			error = EADDRNOTAVAIL;
3530 			goto bad_addr;
3531 		}
3532 	}
3533 	if (ire->ire_type & IRE_BROADCAST) {
3534 		/*
3535 		 * If the ULP didn't have a specified source, then we
3536 		 * make sure we reselect the source when sending
3537 		 * broadcasts out different interfaces.
3538 		 */
3539 		if (flags & IPDF_SELECT_SRC)
3540 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3541 		else
3542 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3543 	}
3544 
3545 	/*
3546 	 * Does the caller want us to pick a source address?
3547 	 */
3548 	if (flags & IPDF_SELECT_SRC) {
3549 		ipaddr_t	src_addr;
3550 
3551 		/*
3552 		 * We use use ire_nexthop_ill to avoid the under ipmp
3553 		 * interface for source address selection. Note that for ipmp
3554 		 * probe packets, ixa_ifindex would have been specified, and
3555 		 * the ip_select_route() invocation would have picked an ire
3556 		 * will ire_ill pointing at an under interface.
3557 		 */
3558 		ill = ire_nexthop_ill(ire);
3559 
3560 		/* If unreachable we have no ill but need some source */
3561 		if (ill == NULL) {
3562 			src_addr = htonl(INADDR_LOOPBACK);
3563 			/* Make sure we look for a better source address */
3564 			generation = SRC_GENERATION_VERIFY;
3565 		} else {
3566 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3567 			    ixa->ixa_multicast_ifaddr, zoneid,
3568 			    ipst, &src_addr, &generation, NULL);
3569 			if (error != 0) {
3570 				ire = NULL;	/* Stored in ixa_ire */
3571 				goto bad_addr;
3572 			}
3573 		}
3574 
3575 		/*
3576 		 * We allow the source address to to down.
3577 		 * However, we check that we don't use the loopback address
3578 		 * as a source when sending out on the wire.
3579 		 */
3580 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3581 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3582 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3583 			ire = NULL;	/* Stored in ixa_ire */
3584 			error = EADDRNOTAVAIL;
3585 			goto bad_addr;
3586 		}
3587 
3588 		*src_addrp = src_addr;
3589 		ixa->ixa_src_generation = generation;
3590 	}
3591 
3592 	/*
3593 	 * Make sure we don't leave an unreachable ixa_nce in place
3594 	 * since ip_select_route is used when we unplumb i.e., remove
3595 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3596 	 */
3597 	nce = ixa->ixa_nce;
3598 	if (nce != NULL && nce->nce_is_condemned) {
3599 		nce_refrele(nce);
3600 		ixa->ixa_nce = NULL;
3601 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3602 	}
3603 
3604 	/*
3605 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3606 	 * However, we can't do it for IPv4 multicast or broadcast.
3607 	 */
3608 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3609 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3610 
3611 	/*
3612 	 * Set initial value for fragmentation limit. Either conn_ip_output
3613 	 * or ULP might updates it when there are routing changes.
3614 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3615 	 */
3616 	pmtu = ip_get_pmtu(ixa);
3617 	ixa->ixa_fragsize = pmtu;
3618 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3619 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3620 		ixa->ixa_pmtu = pmtu;
3621 
3622 	/*
3623 	 * Extract information useful for some transports.
3624 	 * First we look for DCE metrics. Then we take what we have in
3625 	 * the metrics in the route, where the offlink is used if we have
3626 	 * one.
3627 	 */
3628 	if (uinfo != NULL) {
3629 		bzero(uinfo, sizeof (*uinfo));
3630 
3631 		if (dce->dce_flags & DCEF_UINFO)
3632 			*uinfo = dce->dce_uinfo;
3633 
3634 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3635 
3636 		/* Allow ire_metrics to decrease the path MTU from above */
3637 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3638 			uinfo->iulp_mtu = pmtu;
3639 
3640 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3641 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3642 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3643 	}
3644 
3645 	if (ill != NULL)
3646 		ill_refrele(ill);
3647 
3648 	return (error);
3649 
3650 bad_addr:
3651 	if (ire != NULL)
3652 		ire_refrele(ire);
3653 
3654 	if (ill != NULL)
3655 		ill_refrele(ill);
3656 
3657 	/*
3658 	 * Make sure we don't leave an unreachable ixa_nce in place
3659 	 * since ip_select_route is used when we unplumb i.e., remove
3660 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3661 	 */
3662 	nce = ixa->ixa_nce;
3663 	if (nce != NULL && nce->nce_is_condemned) {
3664 		nce_refrele(nce);
3665 		ixa->ixa_nce = NULL;
3666 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3667 	}
3668 
3669 	return (error);
3670 }
3671 
3672 
3673 /*
3674  * Get the base MTU for the case when path MTU discovery is not used.
3675  * Takes the MTU of the IRE into account.
3676  */
3677 uint_t
3678 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3679 {
3680 	uint_t mtu = ill->ill_mtu;
3681 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3682 
3683 	if (iremtu != 0 && iremtu < mtu)
3684 		mtu = iremtu;
3685 
3686 	return (mtu);
3687 }
3688 
3689 /*
3690  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3691  * Assumes that ixa_ire, dce, and nce have already been set up.
3692  *
3693  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3694  * We avoid path MTU discovery if it is disabled with ndd.
3695  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3696  *
3697  * NOTE: We also used to turn it off for source routed packets. That
3698  * is no longer required since the dce is per final destination.
3699  */
3700 uint_t
3701 ip_get_pmtu(ip_xmit_attr_t *ixa)
3702 {
3703 	ip_stack_t	*ipst = ixa->ixa_ipst;
3704 	dce_t		*dce;
3705 	nce_t		*nce;
3706 	ire_t		*ire;
3707 	uint_t		pmtu;
3708 
3709 	ire = ixa->ixa_ire;
3710 	dce = ixa->ixa_dce;
3711 	nce = ixa->ixa_nce;
3712 
3713 	/*
3714 	 * If path MTU discovery has been turned off by ndd, then we ignore
3715 	 * any dce_pmtu and for IPv4 we will not set DF.
3716 	 */
3717 	if (!ipst->ips_ip_path_mtu_discovery)
3718 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3719 
3720 	pmtu = IP_MAXPACKET;
3721 	/*
3722 	 * Decide whether whether IPv4 sets DF
3723 	 * For IPv6 "no DF" means to use the 1280 mtu
3724 	 */
3725 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3726 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3727 	} else {
3728 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3729 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3730 			pmtu = IPV6_MIN_MTU;
3731 	}
3732 
3733 	/* Check if the PMTU is to old before we use it */
3734 	if ((dce->dce_flags & DCEF_PMTU) &&
3735 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3736 	    ipst->ips_ip_pathmtu_interval) {
3737 		/*
3738 		 * Older than 20 minutes. Drop the path MTU information.
3739 		 */
3740 		mutex_enter(&dce->dce_lock);
3741 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3742 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3743 		mutex_exit(&dce->dce_lock);
3744 		dce_increment_generation(dce);
3745 	}
3746 
3747 	/* The metrics on the route can lower the path MTU */
3748 	if (ire->ire_metrics.iulp_mtu != 0 &&
3749 	    ire->ire_metrics.iulp_mtu < pmtu)
3750 		pmtu = ire->ire_metrics.iulp_mtu;
3751 
3752 	/*
3753 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3754 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3755 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3756 	 */
3757 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3758 		if (dce->dce_flags & DCEF_PMTU) {
3759 			if (dce->dce_pmtu < pmtu)
3760 				pmtu = dce->dce_pmtu;
3761 
3762 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3763 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3764 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3765 			} else {
3766 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3767 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3768 			}
3769 		} else {
3770 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3771 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3772 		}
3773 	}
3774 
3775 	/*
3776 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3777 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3778 	 * mtu as IRE_LOOPBACK.
3779 	 */
3780 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3781 		uint_t loopback_mtu;
3782 
3783 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3784 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3785 
3786 		if (loopback_mtu < pmtu)
3787 			pmtu = loopback_mtu;
3788 	} else if (nce != NULL) {
3789 		/*
3790 		 * Make sure we don't exceed the interface MTU.
3791 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3792 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3793 		 * to tell the transport something larger than zero.
3794 		 */
3795 		if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3796 			pmtu = nce->nce_common->ncec_ill->ill_mtu;
3797 		if (nce->nce_common->ncec_ill != nce->nce_ill &&
3798 		    nce->nce_ill->ill_mtu < pmtu) {
3799 			/*
3800 			 * for interfaces in an IPMP group, the mtu of
3801 			 * the nce_ill (under_ill) could be different
3802 			 * from the mtu of the ncec_ill, so we take the
3803 			 * min of the two.
3804 			 */
3805 			pmtu = nce->nce_ill->ill_mtu;
3806 		}
3807 	}
3808 
3809 	/*
3810 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3811 	 * Only applies to IPv6.
3812 	 */
3813 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3814 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3815 			switch (ixa->ixa_use_min_mtu) {
3816 			case IPV6_USE_MIN_MTU_MULTICAST:
3817 				if (ire->ire_type & IRE_MULTICAST)
3818 					pmtu = IPV6_MIN_MTU;
3819 				break;
3820 			case IPV6_USE_MIN_MTU_ALWAYS:
3821 				pmtu = IPV6_MIN_MTU;
3822 				break;
3823 			case IPV6_USE_MIN_MTU_NEVER:
3824 				break;
3825 			}
3826 		} else {
3827 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3828 			if (ire->ire_type & IRE_MULTICAST)
3829 				pmtu = IPV6_MIN_MTU;
3830 		}
3831 	}
3832 
3833 	/*
3834 	 * After receiving an ICMPv6 "packet too big" message with a
3835 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3836 	 * will insert a 8-byte fragment header in every packet. We compensate
3837 	 * for those cases by returning a smaller path MTU to the ULP.
3838 	 *
3839 	 * In the case of CGTP then ip_output will add a fragment header.
3840 	 * Make sure there is room for it by telling a smaller number
3841 	 * to the transport.
3842 	 *
3843 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3844 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3845 	 * which is the size of the packets it can send.
3846 	 */
3847 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3848 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
3849 		    (ire->ire_flags & RTF_MULTIRT) ||
3850 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3851 			pmtu -= sizeof (ip6_frag_t);
3852 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3853 		}
3854 	}
3855 
3856 	return (pmtu);
3857 }
3858 
3859 /*
3860  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3861  * the final piece where we don't.  Return a pointer to the first mblk in the
3862  * result, and update the pointer to the next mblk to chew on.  If anything
3863  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3864  * NULL pointer.
3865  */
3866 mblk_t *
3867 ip_carve_mp(mblk_t **mpp, ssize_t len)
3868 {
3869 	mblk_t	*mp0;
3870 	mblk_t	*mp1;
3871 	mblk_t	*mp2;
3872 
3873 	if (!len || !mpp || !(mp0 = *mpp))
3874 		return (NULL);
3875 	/* If we aren't going to consume the first mblk, we need a dup. */
3876 	if (mp0->b_wptr - mp0->b_rptr > len) {
3877 		mp1 = dupb(mp0);
3878 		if (mp1) {
3879 			/* Partition the data between the two mblks. */
3880 			mp1->b_wptr = mp1->b_rptr + len;
3881 			mp0->b_rptr = mp1->b_wptr;
3882 			/*
3883 			 * after adjustments if mblk not consumed is now
3884 			 * unaligned, try to align it. If this fails free
3885 			 * all messages and let upper layer recover.
3886 			 */
3887 			if (!OK_32PTR(mp0->b_rptr)) {
3888 				if (!pullupmsg(mp0, -1)) {
3889 					freemsg(mp0);
3890 					freemsg(mp1);
3891 					*mpp = NULL;
3892 					return (NULL);
3893 				}
3894 			}
3895 		}
3896 		return (mp1);
3897 	}
3898 	/* Eat through as many mblks as we need to get len bytes. */
3899 	len -= mp0->b_wptr - mp0->b_rptr;
3900 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3901 		if (mp2->b_wptr - mp2->b_rptr > len) {
3902 			/*
3903 			 * We won't consume the entire last mblk.  Like
3904 			 * above, dup and partition it.
3905 			 */
3906 			mp1->b_cont = dupb(mp2);
3907 			mp1 = mp1->b_cont;
3908 			if (!mp1) {
3909 				/*
3910 				 * Trouble.  Rather than go to a lot of
3911 				 * trouble to clean up, we free the messages.
3912 				 * This won't be any worse than losing it on
3913 				 * the wire.
3914 				 */
3915 				freemsg(mp0);
3916 				freemsg(mp2);
3917 				*mpp = NULL;
3918 				return (NULL);
3919 			}
3920 			mp1->b_wptr = mp1->b_rptr + len;
3921 			mp2->b_rptr = mp1->b_wptr;
3922 			/*
3923 			 * after adjustments if mblk not consumed is now
3924 			 * unaligned, try to align it. If this fails free
3925 			 * all messages and let upper layer recover.
3926 			 */
3927 			if (!OK_32PTR(mp2->b_rptr)) {
3928 				if (!pullupmsg(mp2, -1)) {
3929 					freemsg(mp0);
3930 					freemsg(mp2);
3931 					*mpp = NULL;
3932 					return (NULL);
3933 				}
3934 			}
3935 			*mpp = mp2;
3936 			return (mp0);
3937 		}
3938 		/* Decrement len by the amount we just got. */
3939 		len -= mp2->b_wptr - mp2->b_rptr;
3940 	}
3941 	/*
3942 	 * len should be reduced to zero now.  If not our caller has
3943 	 * screwed up.
3944 	 */
3945 	if (len) {
3946 		/* Shouldn't happen! */
3947 		freemsg(mp0);
3948 		*mpp = NULL;
3949 		return (NULL);
3950 	}
3951 	/*
3952 	 * We consumed up to exactly the end of an mblk.  Detach the part
3953 	 * we are returning from the rest of the chain.
3954 	 */
3955 	mp1->b_cont = NULL;
3956 	*mpp = mp2;
3957 	return (mp0);
3958 }
3959 
3960 /* The ill stream is being unplumbed. Called from ip_close */
3961 int
3962 ip_modclose(ill_t *ill)
3963 {
3964 	boolean_t success;
3965 	ipsq_t	*ipsq;
3966 	ipif_t	*ipif;
3967 	queue_t	*q = ill->ill_rq;
3968 	ip_stack_t	*ipst = ill->ill_ipst;
3969 	int	i;
3970 	arl_ill_common_t *ai = ill->ill_common;
3971 
3972 	/*
3973 	 * The punlink prior to this may have initiated a capability
3974 	 * negotiation. But ipsq_enter will block until that finishes or
3975 	 * times out.
3976 	 */
3977 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
3978 
3979 	/*
3980 	 * Open/close/push/pop is guaranteed to be single threaded
3981 	 * per stream by STREAMS. FS guarantees that all references
3982 	 * from top are gone before close is called. So there can't
3983 	 * be another close thread that has set CONDEMNED on this ill.
3984 	 * and cause ipsq_enter to return failure.
3985 	 */
3986 	ASSERT(success);
3987 	ipsq = ill->ill_phyint->phyint_ipsq;
3988 
3989 	/*
3990 	 * Mark it condemned. No new reference will be made to this ill.
3991 	 * Lookup functions will return an error. Threads that try to
3992 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
3993 	 * that the refcnt will drop down to zero.
3994 	 */
3995 	mutex_enter(&ill->ill_lock);
3996 	ill->ill_state_flags |= ILL_CONDEMNED;
3997 	for (ipif = ill->ill_ipif; ipif != NULL;
3998 	    ipif = ipif->ipif_next) {
3999 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4000 	}
4001 	/*
4002 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4003 	 * returns  error if ILL_CONDEMNED is set
4004 	 */
4005 	cv_broadcast(&ill->ill_cv);
4006 	mutex_exit(&ill->ill_lock);
4007 
4008 	/*
4009 	 * Send all the deferred DLPI messages downstream which came in
4010 	 * during the small window right before ipsq_enter(). We do this
4011 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4012 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4013 	 */
4014 	ill_dlpi_send_deferred(ill);
4015 
4016 	/*
4017 	 * Shut down fragmentation reassembly.
4018 	 * ill_frag_timer won't start a timer again.
4019 	 * Now cancel any existing timer
4020 	 */
4021 	(void) untimeout(ill->ill_frag_timer_id);
4022 	(void) ill_frag_timeout(ill, 0);
4023 
4024 	/*
4025 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4026 	 * this ill. Then wait for the refcnts to drop to zero.
4027 	 * ill_is_freeable checks whether the ill is really quiescent.
4028 	 * Then make sure that threads that are waiting to enter the
4029 	 * ipsq have seen the error returned by ipsq_enter and have
4030 	 * gone away. Then we call ill_delete_tail which does the
4031 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4032 	 */
4033 	ill_delete(ill);
4034 	mutex_enter(&ill->ill_lock);
4035 	while (!ill_is_freeable(ill))
4036 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4037 
4038 	while (ill->ill_waiters)
4039 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4040 
4041 	mutex_exit(&ill->ill_lock);
4042 
4043 	/*
4044 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4045 	 * it held until the end of the function since the cleanup
4046 	 * below needs to be able to use the ip_stack_t.
4047 	 */
4048 	netstack_hold(ipst->ips_netstack);
4049 
4050 	/* qprocsoff is done via ill_delete_tail */
4051 	ill_delete_tail(ill);
4052 	/*
4053 	 * synchronously wait for arp stream to unbind. After this, we
4054 	 * cannot get any data packets up from the driver.
4055 	 */
4056 	arp_unbind_complete(ill);
4057 	ASSERT(ill->ill_ipst == NULL);
4058 
4059 	/*
4060 	 * Walk through all conns and qenable those that have queued data.
4061 	 * Close synchronization needs this to
4062 	 * be done to ensure that all upper layers blocked
4063 	 * due to flow control to the closing device
4064 	 * get unblocked.
4065 	 */
4066 	ip1dbg(("ip_wsrv: walking\n"));
4067 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4068 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4069 	}
4070 
4071 	/*
4072 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4073 	 * stream is being torn down before ARP was plumbed (e.g.,
4074 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4075 	 * an error
4076 	 */
4077 	if (ai != NULL) {
4078 		ASSERT(!ill->ill_isv6);
4079 		mutex_enter(&ai->ai_lock);
4080 		ai->ai_ill = NULL;
4081 		if (ai->ai_arl == NULL) {
4082 			mutex_destroy(&ai->ai_lock);
4083 			kmem_free(ai, sizeof (*ai));
4084 		} else {
4085 			cv_signal(&ai->ai_ill_unplumb_done);
4086 			mutex_exit(&ai->ai_lock);
4087 		}
4088 	}
4089 
4090 	mutex_enter(&ipst->ips_ip_mi_lock);
4091 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4092 	mutex_exit(&ipst->ips_ip_mi_lock);
4093 
4094 	/*
4095 	 * credp could be null if the open didn't succeed and ip_modopen
4096 	 * itself calls ip_close.
4097 	 */
4098 	if (ill->ill_credp != NULL)
4099 		crfree(ill->ill_credp);
4100 
4101 	mutex_destroy(&ill->ill_saved_ire_lock);
4102 	mutex_destroy(&ill->ill_lock);
4103 	rw_destroy(&ill->ill_mcast_lock);
4104 	mutex_destroy(&ill->ill_mcast_serializer);
4105 	list_destroy(&ill->ill_nce);
4106 
4107 	/*
4108 	 * Now we are done with the module close pieces that
4109 	 * need the netstack_t.
4110 	 */
4111 	netstack_rele(ipst->ips_netstack);
4112 
4113 	mi_close_free((IDP)ill);
4114 	q->q_ptr = WR(q)->q_ptr = NULL;
4115 
4116 	ipsq_exit(ipsq);
4117 
4118 	return (0);
4119 }
4120 
4121 /*
4122  * This is called as part of close() for IP, UDP, ICMP, and RTS
4123  * in order to quiesce the conn.
4124  */
4125 void
4126 ip_quiesce_conn(conn_t *connp)
4127 {
4128 	boolean_t	drain_cleanup_reqd = B_FALSE;
4129 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4130 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4131 	ip_stack_t	*ipst;
4132 
4133 	ASSERT(!IPCL_IS_TCP(connp));
4134 	ipst = connp->conn_netstack->netstack_ip;
4135 
4136 	/*
4137 	 * Mark the conn as closing, and this conn must not be
4138 	 * inserted in future into any list. Eg. conn_drain_insert(),
4139 	 * won't insert this conn into the conn_drain_list.
4140 	 *
4141 	 * conn_idl, and conn_ilg cannot get set henceforth.
4142 	 */
4143 	mutex_enter(&connp->conn_lock);
4144 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4145 	connp->conn_state_flags |= CONN_CLOSING;
4146 	if (connp->conn_idl != NULL)
4147 		drain_cleanup_reqd = B_TRUE;
4148 	if (connp->conn_oper_pending_ill != NULL)
4149 		conn_ioctl_cleanup_reqd = B_TRUE;
4150 	if (connp->conn_dhcpinit_ill != NULL) {
4151 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4152 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4153 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4154 		connp->conn_dhcpinit_ill = NULL;
4155 	}
4156 	if (connp->conn_ilg != NULL)
4157 		ilg_cleanup_reqd = B_TRUE;
4158 	mutex_exit(&connp->conn_lock);
4159 
4160 	if (conn_ioctl_cleanup_reqd)
4161 		conn_ioctl_cleanup(connp);
4162 
4163 	if (is_system_labeled() && connp->conn_anon_port) {
4164 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4165 		    connp->conn_mlp_type, connp->conn_proto,
4166 		    ntohs(connp->conn_lport), B_FALSE);
4167 		connp->conn_anon_port = 0;
4168 	}
4169 	connp->conn_mlp_type = mlptSingle;
4170 
4171 	/*
4172 	 * Remove this conn from any fanout list it is on.
4173 	 * and then wait for any threads currently operating
4174 	 * on this endpoint to finish
4175 	 */
4176 	ipcl_hash_remove(connp);
4177 
4178 	/*
4179 	 * Remove this conn from the drain list, and do any other cleanup that
4180 	 * may be required.  (TCP conns are never flow controlled, and
4181 	 * conn_idl will be NULL.)
4182 	 */
4183 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4184 		idl_t *idl = connp->conn_idl;
4185 
4186 		mutex_enter(&idl->idl_lock);
4187 		conn_drain(connp, B_TRUE);
4188 		mutex_exit(&idl->idl_lock);
4189 	}
4190 
4191 	if (connp == ipst->ips_ip_g_mrouter)
4192 		(void) ip_mrouter_done(ipst);
4193 
4194 	if (ilg_cleanup_reqd)
4195 		ilg_delete_all(connp);
4196 
4197 	/*
4198 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4199 	 * callers from write side can't be there now because close
4200 	 * is in progress. The only other caller is ipcl_walk
4201 	 * which checks for the condemned flag.
4202 	 */
4203 	mutex_enter(&connp->conn_lock);
4204 	connp->conn_state_flags |= CONN_CONDEMNED;
4205 	while (connp->conn_ref != 1)
4206 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4207 	connp->conn_state_flags |= CONN_QUIESCED;
4208 	mutex_exit(&connp->conn_lock);
4209 }
4210 
4211 /* ARGSUSED */
4212 int
4213 ip_close(queue_t *q, int flags)
4214 {
4215 	conn_t		*connp;
4216 
4217 	/*
4218 	 * Call the appropriate delete routine depending on whether this is
4219 	 * a module or device.
4220 	 */
4221 	if (WR(q)->q_next != NULL) {
4222 		/* This is a module close */
4223 		return (ip_modclose((ill_t *)q->q_ptr));
4224 	}
4225 
4226 	connp = q->q_ptr;
4227 	ip_quiesce_conn(connp);
4228 
4229 	qprocsoff(q);
4230 
4231 	/*
4232 	 * Now we are truly single threaded on this stream, and can
4233 	 * delete the things hanging off the connp, and finally the connp.
4234 	 * We removed this connp from the fanout list, it cannot be
4235 	 * accessed thru the fanouts, and we already waited for the
4236 	 * conn_ref to drop to 0. We are already in close, so
4237 	 * there cannot be any other thread from the top. qprocsoff
4238 	 * has completed, and service has completed or won't run in
4239 	 * future.
4240 	 */
4241 	ASSERT(connp->conn_ref == 1);
4242 
4243 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4244 
4245 	connp->conn_ref--;
4246 	ipcl_conn_destroy(connp);
4247 
4248 	q->q_ptr = WR(q)->q_ptr = NULL;
4249 	return (0);
4250 }
4251 
4252 /*
4253  * Wapper around putnext() so that ip_rts_request can merely use
4254  * conn_recv.
4255  */
4256 /*ARGSUSED2*/
4257 static void
4258 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4259 {
4260 	conn_t *connp = (conn_t *)arg1;
4261 
4262 	putnext(connp->conn_rq, mp);
4263 }
4264 
4265 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4266 /* ARGSUSED */
4267 static void
4268 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4269 {
4270 	freemsg(mp);
4271 }
4272 
4273 /*
4274  * Called when the module is about to be unloaded
4275  */
4276 void
4277 ip_ddi_destroy(void)
4278 {
4279 	/* This needs to be called before destroying any transports. */
4280 	mutex_enter(&cpu_lock);
4281 	unregister_cpu_setup_func(ip_tp_cpu_update, NULL);
4282 	mutex_exit(&cpu_lock);
4283 
4284 	tnet_fini();
4285 
4286 	icmp_ddi_g_destroy();
4287 	rts_ddi_g_destroy();
4288 	udp_ddi_g_destroy();
4289 	sctp_ddi_g_destroy();
4290 	tcp_ddi_g_destroy();
4291 	ilb_ddi_g_destroy();
4292 	dce_g_destroy();
4293 	ipsec_policy_g_destroy();
4294 	ipcl_g_destroy();
4295 	ip_net_g_destroy();
4296 	ip_ire_g_fini();
4297 	inet_minor_destroy(ip_minor_arena_sa);
4298 #if defined(_LP64)
4299 	inet_minor_destroy(ip_minor_arena_la);
4300 #endif
4301 
4302 #ifdef DEBUG
4303 	list_destroy(&ip_thread_list);
4304 	rw_destroy(&ip_thread_rwlock);
4305 	tsd_destroy(&ip_thread_data);
4306 #endif
4307 
4308 	netstack_unregister(NS_IP);
4309 }
4310 
4311 /*
4312  * First step in cleanup.
4313  */
4314 /* ARGSUSED */
4315 static void
4316 ip_stack_shutdown(netstackid_t stackid, void *arg)
4317 {
4318 	ip_stack_t *ipst = (ip_stack_t *)arg;
4319 
4320 #ifdef NS_DEBUG
4321 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4322 #endif
4323 
4324 	/*
4325 	 * Perform cleanup for special interfaces (loopback and IPMP).
4326 	 */
4327 	ip_interface_cleanup(ipst);
4328 
4329 	/*
4330 	 * The *_hook_shutdown()s start the process of notifying any
4331 	 * consumers that things are going away.... nothing is destroyed.
4332 	 */
4333 	ipv4_hook_shutdown(ipst);
4334 	ipv6_hook_shutdown(ipst);
4335 	arp_hook_shutdown(ipst);
4336 
4337 	mutex_enter(&ipst->ips_capab_taskq_lock);
4338 	ipst->ips_capab_taskq_quit = B_TRUE;
4339 	cv_signal(&ipst->ips_capab_taskq_cv);
4340 	mutex_exit(&ipst->ips_capab_taskq_lock);
4341 }
4342 
4343 /*
4344  * Free the IP stack instance.
4345  */
4346 static void
4347 ip_stack_fini(netstackid_t stackid, void *arg)
4348 {
4349 	ip_stack_t *ipst = (ip_stack_t *)arg;
4350 	int ret;
4351 
4352 #ifdef NS_DEBUG
4353 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4354 #endif
4355 	/*
4356 	 * At this point, all of the notifications that the events and
4357 	 * protocols are going away have been run, meaning that we can
4358 	 * now set about starting to clean things up.
4359 	 */
4360 	ipobs_fini(ipst);
4361 	ipv4_hook_destroy(ipst);
4362 	ipv6_hook_destroy(ipst);
4363 	arp_hook_destroy(ipst);
4364 	ip_net_destroy(ipst);
4365 
4366 	ipmp_destroy(ipst);
4367 
4368 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4369 	ipst->ips_ip_mibkp = NULL;
4370 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4371 	ipst->ips_icmp_mibkp = NULL;
4372 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4373 	ipst->ips_ip_kstat = NULL;
4374 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4375 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4376 	ipst->ips_ip6_kstat = NULL;
4377 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4378 
4379 	kmem_free(ipst->ips_propinfo_tbl,
4380 	    ip_propinfo_count * sizeof (mod_prop_info_t));
4381 	ipst->ips_propinfo_tbl = NULL;
4382 
4383 	dce_stack_destroy(ipst);
4384 	ip_mrouter_stack_destroy(ipst);
4385 
4386 	ret = untimeout(ipst->ips_igmp_timeout_id);
4387 	if (ret == -1) {
4388 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4389 	} else {
4390 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4391 		ipst->ips_igmp_timeout_id = 0;
4392 	}
4393 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4394 	if (ret == -1) {
4395 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4396 	} else {
4397 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4398 		ipst->ips_igmp_slowtimeout_id = 0;
4399 	}
4400 	ret = untimeout(ipst->ips_mld_timeout_id);
4401 	if (ret == -1) {
4402 		ASSERT(ipst->ips_mld_timeout_id == 0);
4403 	} else {
4404 		ASSERT(ipst->ips_mld_timeout_id != 0);
4405 		ipst->ips_mld_timeout_id = 0;
4406 	}
4407 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4408 	if (ret == -1) {
4409 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4410 	} else {
4411 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4412 		ipst->ips_mld_slowtimeout_id = 0;
4413 	}
4414 
4415 	ip_ire_fini(ipst);
4416 	ip6_asp_free(ipst);
4417 	conn_drain_fini(ipst);
4418 	ipcl_destroy(ipst);
4419 
4420 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4421 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4422 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4423 	ipst->ips_ndp4 = NULL;
4424 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4425 	ipst->ips_ndp6 = NULL;
4426 
4427 	if (ipst->ips_loopback_ksp != NULL) {
4428 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4429 		ipst->ips_loopback_ksp = NULL;
4430 	}
4431 
4432 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4433 	cv_destroy(&ipst->ips_capab_taskq_cv);
4434 
4435 	rw_destroy(&ipst->ips_srcid_lock);
4436 
4437 	mutex_destroy(&ipst->ips_ip_mi_lock);
4438 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4439 
4440 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4441 	mutex_destroy(&ipst->ips_mld_timer_lock);
4442 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4443 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4444 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4445 	rw_destroy(&ipst->ips_ill_g_lock);
4446 
4447 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4448 	ipst->ips_phyint_g_list = NULL;
4449 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4450 	ipst->ips_ill_g_heads = NULL;
4451 
4452 	ldi_ident_release(ipst->ips_ldi_ident);
4453 	kmem_free(ipst, sizeof (*ipst));
4454 }
4455 
4456 /*
4457  * This function is called from the TSD destructor, and is used to debug
4458  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4459  * details.
4460  */
4461 static void
4462 ip_thread_exit(void *phash)
4463 {
4464 	th_hash_t *thh = phash;
4465 
4466 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4467 	list_remove(&ip_thread_list, thh);
4468 	rw_exit(&ip_thread_rwlock);
4469 	mod_hash_destroy_hash(thh->thh_hash);
4470 	kmem_free(thh, sizeof (*thh));
4471 }
4472 
4473 /*
4474  * Called when the IP kernel module is loaded into the kernel
4475  */
4476 void
4477 ip_ddi_init(void)
4478 {
4479 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4480 
4481 	/*
4482 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4483 	 * initial devices: ip, ip6, tcp, tcp6.
4484 	 */
4485 	/*
4486 	 * If this is a 64-bit kernel, then create two separate arenas -
4487 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4488 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4489 	 */
4490 	ip_minor_arena_la = NULL;
4491 	ip_minor_arena_sa = NULL;
4492 #if defined(_LP64)
4493 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4494 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4495 		cmn_err(CE_PANIC,
4496 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4497 	}
4498 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4499 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4500 		cmn_err(CE_PANIC,
4501 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4502 	}
4503 #else
4504 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4505 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4506 		cmn_err(CE_PANIC,
4507 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4508 	}
4509 #endif
4510 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4511 
4512 	ipcl_g_init();
4513 	ip_ire_g_init();
4514 	ip_net_g_init();
4515 
4516 #ifdef DEBUG
4517 	tsd_create(&ip_thread_data, ip_thread_exit);
4518 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4519 	list_create(&ip_thread_list, sizeof (th_hash_t),
4520 	    offsetof(th_hash_t, thh_link));
4521 #endif
4522 	ipsec_policy_g_init();
4523 	tcp_ddi_g_init();
4524 	sctp_ddi_g_init();
4525 	dce_g_init();
4526 
4527 	/*
4528 	 * We want to be informed each time a stack is created or
4529 	 * destroyed in the kernel, so we can maintain the
4530 	 * set of udp_stack_t's.
4531 	 */
4532 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4533 	    ip_stack_fini);
4534 
4535 	tnet_init();
4536 
4537 	udp_ddi_g_init();
4538 	rts_ddi_g_init();
4539 	icmp_ddi_g_init();
4540 	ilb_ddi_g_init();
4541 
4542 	/* This needs to be called after all transports are initialized. */
4543 	mutex_enter(&cpu_lock);
4544 	register_cpu_setup_func(ip_tp_cpu_update, NULL);
4545 	mutex_exit(&cpu_lock);
4546 }
4547 
4548 /*
4549  * Initialize the IP stack instance.
4550  */
4551 static void *
4552 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4553 {
4554 	ip_stack_t	*ipst;
4555 	size_t		arrsz;
4556 	major_t		major;
4557 
4558 #ifdef NS_DEBUG
4559 	printf("ip_stack_init(stack %d)\n", stackid);
4560 #endif
4561 
4562 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4563 	ipst->ips_netstack = ns;
4564 
4565 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4566 	    KM_SLEEP);
4567 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4568 	    KM_SLEEP);
4569 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4570 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4571 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4572 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4573 
4574 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4575 	ipst->ips_igmp_deferred_next = INFINITY;
4576 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4577 	ipst->ips_mld_deferred_next = INFINITY;
4578 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4579 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4580 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4581 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4582 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4583 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4584 
4585 	ipcl_init(ipst);
4586 	ip_ire_init(ipst);
4587 	ip6_asp_init(ipst);
4588 	ipif_init(ipst);
4589 	conn_drain_init(ipst);
4590 	ip_mrouter_stack_init(ipst);
4591 	dce_stack_init(ipst);
4592 
4593 	ipst->ips_ip_multirt_log_interval = 1000;
4594 
4595 	ipst->ips_ill_index = 1;
4596 
4597 	ipst->ips_saved_ip_forwarding = -1;
4598 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4599 
4600 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4601 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4602 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4603 
4604 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4605 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4606 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4607 	ipst->ips_ip6_kstat =
4608 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4609 
4610 	ipst->ips_ip_src_id = 1;
4611 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4612 
4613 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4614 
4615 	ip_net_init(ipst, ns);
4616 	ipv4_hook_init(ipst);
4617 	ipv6_hook_init(ipst);
4618 	arp_hook_init(ipst);
4619 	ipmp_init(ipst);
4620 	ipobs_init(ipst);
4621 
4622 	/*
4623 	 * Create the taskq dispatcher thread and initialize related stuff.
4624 	 */
4625 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4626 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4627 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4628 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4629 
4630 	major = mod_name_to_major(INET_NAME);
4631 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4632 	return (ipst);
4633 }
4634 
4635 /*
4636  * Allocate and initialize a DLPI template of the specified length.  (May be
4637  * called as writer.)
4638  */
4639 mblk_t *
4640 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4641 {
4642 	mblk_t	*mp;
4643 
4644 	mp = allocb(len, BPRI_MED);
4645 	if (!mp)
4646 		return (NULL);
4647 
4648 	/*
4649 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4650 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4651 	 * that other DLPI are M_PROTO.
4652 	 */
4653 	if (prim == DL_INFO_REQ) {
4654 		mp->b_datap->db_type = M_PCPROTO;
4655 	} else {
4656 		mp->b_datap->db_type = M_PROTO;
4657 	}
4658 
4659 	mp->b_wptr = mp->b_rptr + len;
4660 	bzero(mp->b_rptr, len);
4661 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4662 	return (mp);
4663 }
4664 
4665 /*
4666  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4667  */
4668 mblk_t *
4669 ip_dlnotify_alloc(uint_t notification, uint_t data)
4670 {
4671 	dl_notify_ind_t	*notifyp;
4672 	mblk_t		*mp;
4673 
4674 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4675 		return (NULL);
4676 
4677 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4678 	notifyp->dl_notification = notification;
4679 	notifyp->dl_data = data;
4680 	return (mp);
4681 }
4682 
4683 /*
4684  * Debug formatting routine.  Returns a character string representation of the
4685  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4686  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4687  *
4688  * Once the ndd table-printing interfaces are removed, this can be changed to
4689  * standard dotted-decimal form.
4690  */
4691 char *
4692 ip_dot_addr(ipaddr_t addr, char *buf)
4693 {
4694 	uint8_t *ap = (uint8_t *)&addr;
4695 
4696 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4697 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4698 	return (buf);
4699 }
4700 
4701 /*
4702  * Write the given MAC address as a printable string in the usual colon-
4703  * separated format.
4704  */
4705 const char *
4706 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4707 {
4708 	char *bp;
4709 
4710 	if (alen == 0 || buflen < 4)
4711 		return ("?");
4712 	bp = buf;
4713 	for (;;) {
4714 		/*
4715 		 * If there are more MAC address bytes available, but we won't
4716 		 * have any room to print them, then add "..." to the string
4717 		 * instead.  See below for the 'magic number' explanation.
4718 		 */
4719 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4720 			(void) strcpy(bp, "...");
4721 			break;
4722 		}
4723 		(void) sprintf(bp, "%02x", *addr++);
4724 		bp += 2;
4725 		if (--alen == 0)
4726 			break;
4727 		*bp++ = ':';
4728 		buflen -= 3;
4729 		/*
4730 		 * At this point, based on the first 'if' statement above,
4731 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4732 		 * buflen >= 4.  The first case leaves room for the final "xx"
4733 		 * number and trailing NUL byte.  The second leaves room for at
4734 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4735 		 * that statement.
4736 		 */
4737 	}
4738 	return (buf);
4739 }
4740 
4741 /*
4742  * Called when it is conceptually a ULP that would sent the packet
4743  * e.g., port unreachable and protocol unreachable. Check that the packet
4744  * would have passed the IPsec global policy before sending the error.
4745  *
4746  * Send an ICMP error after patching up the packet appropriately.
4747  * Uses ip_drop_input and bumps the appropriate MIB.
4748  */
4749 void
4750 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4751     ip_recv_attr_t *ira)
4752 {
4753 	ipha_t		*ipha;
4754 	boolean_t	secure;
4755 	ill_t		*ill = ira->ira_ill;
4756 	ip_stack_t	*ipst = ill->ill_ipst;
4757 	netstack_t	*ns = ipst->ips_netstack;
4758 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4759 
4760 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4761 
4762 	/*
4763 	 * We are generating an icmp error for some inbound packet.
4764 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4765 	 * Before we generate an error, check with global policy
4766 	 * to see whether this is allowed to enter the system. As
4767 	 * there is no "conn", we are checking with global policy.
4768 	 */
4769 	ipha = (ipha_t *)mp->b_rptr;
4770 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4771 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4772 		if (mp == NULL)
4773 			return;
4774 	}
4775 
4776 	/* We never send errors for protocols that we do implement */
4777 	if (ira->ira_protocol == IPPROTO_ICMP ||
4778 	    ira->ira_protocol == IPPROTO_IGMP) {
4779 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4780 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4781 		freemsg(mp);
4782 		return;
4783 	}
4784 	/*
4785 	 * Have to correct checksum since
4786 	 * the packet might have been
4787 	 * fragmented and the reassembly code in ip_rput
4788 	 * does not restore the IP checksum.
4789 	 */
4790 	ipha->ipha_hdr_checksum = 0;
4791 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4792 
4793 	switch (icmp_type) {
4794 	case ICMP_DEST_UNREACHABLE:
4795 		switch (icmp_code) {
4796 		case ICMP_PROTOCOL_UNREACHABLE:
4797 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4798 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4799 			break;
4800 		case ICMP_PORT_UNREACHABLE:
4801 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4802 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4803 			break;
4804 		}
4805 
4806 		icmp_unreachable(mp, icmp_code, ira);
4807 		break;
4808 	default:
4809 #ifdef DEBUG
4810 		panic("ip_fanout_send_icmp_v4: wrong type");
4811 		/*NOTREACHED*/
4812 #else
4813 		freemsg(mp);
4814 		break;
4815 #endif
4816 	}
4817 }
4818 
4819 /*
4820  * Used to send an ICMP error message when a packet is received for
4821  * a protocol that is not supported. The mblk passed as argument
4822  * is consumed by this function.
4823  */
4824 void
4825 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4826 {
4827 	ipha_t		*ipha;
4828 
4829 	ipha = (ipha_t *)mp->b_rptr;
4830 	if (ira->ira_flags & IRAF_IS_IPV4) {
4831 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4832 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4833 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4834 	} else {
4835 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4836 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4837 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4838 	}
4839 }
4840 
4841 /*
4842  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4843  * Handles IPv4 and IPv6.
4844  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4845  * Caller is responsible for dropping references to the conn.
4846  */
4847 void
4848 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4849     ip_recv_attr_t *ira)
4850 {
4851 	ill_t		*ill = ira->ira_ill;
4852 	ip_stack_t	*ipst = ill->ill_ipst;
4853 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4854 	boolean_t	secure;
4855 	uint_t		protocol = ira->ira_protocol;
4856 	iaflags_t	iraflags = ira->ira_flags;
4857 	queue_t		*rq;
4858 
4859 	secure = iraflags & IRAF_IPSEC_SECURE;
4860 
4861 	rq = connp->conn_rq;
4862 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4863 		switch (protocol) {
4864 		case IPPROTO_ICMPV6:
4865 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4866 			break;
4867 		case IPPROTO_ICMP:
4868 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4869 			break;
4870 		default:
4871 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4872 			break;
4873 		}
4874 		freemsg(mp);
4875 		return;
4876 	}
4877 
4878 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4879 
4880 	if (((iraflags & IRAF_IS_IPV4) ?
4881 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4882 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4883 	    secure) {
4884 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4885 		    ip6h, ira);
4886 		if (mp == NULL) {
4887 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4888 			/* Note that mp is NULL */
4889 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4890 			return;
4891 		}
4892 	}
4893 
4894 	if (iraflags & IRAF_ICMP_ERROR) {
4895 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4896 	} else {
4897 		ill_t *rill = ira->ira_rill;
4898 
4899 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4900 		ira->ira_ill = ira->ira_rill = NULL;
4901 		/* Send it upstream */
4902 		(connp->conn_recv)(connp, mp, NULL, ira);
4903 		ira->ira_ill = ill;
4904 		ira->ira_rill = rill;
4905 	}
4906 }
4907 
4908 /*
4909  * Handle protocols with which IP is less intimate.  There
4910  * can be more than one stream bound to a particular
4911  * protocol.  When this is the case, normally each one gets a copy
4912  * of any incoming packets.
4913  *
4914  * IPsec NOTE :
4915  *
4916  * Don't allow a secure packet going up a non-secure connection.
4917  * We don't allow this because
4918  *
4919  * 1) Reply might go out in clear which will be dropped at
4920  *    the sending side.
4921  * 2) If the reply goes out in clear it will give the
4922  *    adversary enough information for getting the key in
4923  *    most of the cases.
4924  *
4925  * Moreover getting a secure packet when we expect clear
4926  * implies that SA's were added without checking for
4927  * policy on both ends. This should not happen once ISAKMP
4928  * is used to negotiate SAs as SAs will be added only after
4929  * verifying the policy.
4930  *
4931  * Zones notes:
4932  * Earlier in ip_input on a system with multiple shared-IP zones we
4933  * duplicate the multicast and broadcast packets and send them up
4934  * with each explicit zoneid that exists on that ill.
4935  * This means that here we can match the zoneid with SO_ALLZONES being special.
4936  */
4937 void
4938 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
4939 {
4940 	mblk_t		*mp1;
4941 	ipaddr_t	laddr;
4942 	conn_t		*connp, *first_connp, *next_connp;
4943 	connf_t		*connfp;
4944 	ill_t		*ill = ira->ira_ill;
4945 	ip_stack_t	*ipst = ill->ill_ipst;
4946 
4947 	laddr = ipha->ipha_dst;
4948 
4949 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
4950 	mutex_enter(&connfp->connf_lock);
4951 	connp = connfp->connf_head;
4952 	for (connp = connfp->connf_head; connp != NULL;
4953 	    connp = connp->conn_next) {
4954 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4955 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4956 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4957 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
4958 			break;
4959 		}
4960 	}
4961 
4962 	if (connp == NULL) {
4963 		/*
4964 		 * No one bound to these addresses.  Is
4965 		 * there a client that wants all
4966 		 * unclaimed datagrams?
4967 		 */
4968 		mutex_exit(&connfp->connf_lock);
4969 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4970 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4971 		return;
4972 	}
4973 
4974 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
4975 
4976 	CONN_INC_REF(connp);
4977 	first_connp = connp;
4978 	connp = connp->conn_next;
4979 
4980 	for (;;) {
4981 		while (connp != NULL) {
4982 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4983 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4984 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4985 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
4986 			    ira, connp)))
4987 				break;
4988 			connp = connp->conn_next;
4989 		}
4990 
4991 		if (connp == NULL) {
4992 			/* No more interested clients */
4993 			connp = first_connp;
4994 			break;
4995 		}
4996 		if (((mp1 = dupmsg(mp)) == NULL) &&
4997 		    ((mp1 = copymsg(mp)) == NULL)) {
4998 			/* Memory allocation failed */
4999 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5000 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5001 			connp = first_connp;
5002 			break;
5003 		}
5004 
5005 		CONN_INC_REF(connp);
5006 		mutex_exit(&connfp->connf_lock);
5007 
5008 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5009 		    ira);
5010 
5011 		mutex_enter(&connfp->connf_lock);
5012 		/* Follow the next pointer before releasing the conn. */
5013 		next_connp = connp->conn_next;
5014 		CONN_DEC_REF(connp);
5015 		connp = next_connp;
5016 	}
5017 
5018 	/* Last one.  Send it upstream. */
5019 	mutex_exit(&connfp->connf_lock);
5020 
5021 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5022 
5023 	CONN_DEC_REF(connp);
5024 }
5025 
5026 /*
5027  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5028  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5029  * is not consumed.
5030  *
5031  * One of three things can happen, all of which affect the passed-in mblk:
5032  *
5033  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5034  *
5035  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5036  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5037  *
5038  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5039  */
5040 mblk_t *
5041 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5042 {
5043 	int shift, plen, iph_len;
5044 	ipha_t *ipha;
5045 	udpha_t *udpha;
5046 	uint32_t *spi;
5047 	uint32_t esp_ports;
5048 	uint8_t *orptr;
5049 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5050 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5051 
5052 	ipha = (ipha_t *)mp->b_rptr;
5053 	iph_len = ira->ira_ip_hdr_length;
5054 	plen = ira->ira_pktlen;
5055 
5056 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5057 		/*
5058 		 * Most likely a keepalive for the benefit of an intervening
5059 		 * NAT.  These aren't for us, per se, so drop it.
5060 		 *
5061 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5062 		 * byte packets (keepalives are 1-byte), but we'll drop them
5063 		 * also.
5064 		 */
5065 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5066 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5067 		return (NULL);
5068 	}
5069 
5070 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5071 		/* might as well pull it all up - it might be ESP. */
5072 		if (!pullupmsg(mp, -1)) {
5073 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5074 			    DROPPER(ipss, ipds_esp_nomem),
5075 			    &ipss->ipsec_dropper);
5076 			return (NULL);
5077 		}
5078 
5079 		ipha = (ipha_t *)mp->b_rptr;
5080 	}
5081 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5082 	if (*spi == 0) {
5083 		/* UDP packet - remove 0-spi. */
5084 		shift = sizeof (uint32_t);
5085 	} else {
5086 		/* ESP-in-UDP packet - reduce to ESP. */
5087 		ipha->ipha_protocol = IPPROTO_ESP;
5088 		shift = sizeof (udpha_t);
5089 	}
5090 
5091 	/* Fix IP header */
5092 	ira->ira_pktlen = (plen - shift);
5093 	ipha->ipha_length = htons(ira->ira_pktlen);
5094 	ipha->ipha_hdr_checksum = 0;
5095 
5096 	orptr = mp->b_rptr;
5097 	mp->b_rptr += shift;
5098 
5099 	udpha = (udpha_t *)(orptr + iph_len);
5100 	if (*spi == 0) {
5101 		ASSERT((uint8_t *)ipha == orptr);
5102 		udpha->uha_length = htons(plen - shift - iph_len);
5103 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5104 		esp_ports = 0;
5105 	} else {
5106 		esp_ports = *((uint32_t *)udpha);
5107 		ASSERT(esp_ports != 0);
5108 	}
5109 	ovbcopy(orptr, orptr + shift, iph_len);
5110 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5111 		ipha = (ipha_t *)(orptr + shift);
5112 
5113 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5114 		ira->ira_esp_udp_ports = esp_ports;
5115 		ip_fanout_v4(mp, ipha, ira);
5116 		return (NULL);
5117 	}
5118 	return (mp);
5119 }
5120 
5121 /*
5122  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5123  * Handles IPv4 and IPv6.
5124  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5125  * Caller is responsible for dropping references to the conn.
5126  */
5127 void
5128 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5129     ip_recv_attr_t *ira)
5130 {
5131 	ill_t		*ill = ira->ira_ill;
5132 	ip_stack_t	*ipst = ill->ill_ipst;
5133 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5134 	boolean_t	secure;
5135 	iaflags_t	iraflags = ira->ira_flags;
5136 
5137 	secure = iraflags & IRAF_IPSEC_SECURE;
5138 
5139 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5140 	    !canputnext(connp->conn_rq)) {
5141 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5142 		freemsg(mp);
5143 		return;
5144 	}
5145 
5146 	if (((iraflags & IRAF_IS_IPV4) ?
5147 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5148 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5149 	    secure) {
5150 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5151 		    ip6h, ira);
5152 		if (mp == NULL) {
5153 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5154 			/* Note that mp is NULL */
5155 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5156 			return;
5157 		}
5158 	}
5159 
5160 	/*
5161 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5162 	 * check. Only ip_fanout_v4 has that check.
5163 	 */
5164 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5165 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5166 	} else {
5167 		ill_t *rill = ira->ira_rill;
5168 
5169 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5170 		ira->ira_ill = ira->ira_rill = NULL;
5171 		/* Send it upstream */
5172 		(connp->conn_recv)(connp, mp, NULL, ira);
5173 		ira->ira_ill = ill;
5174 		ira->ira_rill = rill;
5175 	}
5176 }
5177 
5178 /*
5179  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5180  * (Unicast fanout is handled in ip_input_v4.)
5181  *
5182  * If SO_REUSEADDR is set all multicast and broadcast packets
5183  * will be delivered to all conns bound to the same port.
5184  *
5185  * If there is at least one matching AF_INET receiver, then we will
5186  * ignore any AF_INET6 receivers.
5187  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5188  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5189  * packets.
5190  *
5191  * Zones notes:
5192  * Earlier in ip_input on a system with multiple shared-IP zones we
5193  * duplicate the multicast and broadcast packets and send them up
5194  * with each explicit zoneid that exists on that ill.
5195  * This means that here we can match the zoneid with SO_ALLZONES being special.
5196  */
5197 void
5198 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5199     ip_recv_attr_t *ira)
5200 {
5201 	ipaddr_t	laddr;
5202 	in6_addr_t	v6faddr;
5203 	conn_t		*connp;
5204 	connf_t		*connfp;
5205 	ipaddr_t	faddr;
5206 	ill_t		*ill = ira->ira_ill;
5207 	ip_stack_t	*ipst = ill->ill_ipst;
5208 
5209 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5210 
5211 	laddr = ipha->ipha_dst;
5212 	faddr = ipha->ipha_src;
5213 
5214 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5215 	mutex_enter(&connfp->connf_lock);
5216 	connp = connfp->connf_head;
5217 
5218 	/*
5219 	 * If SO_REUSEADDR has been set on the first we send the
5220 	 * packet to all clients that have joined the group and
5221 	 * match the port.
5222 	 */
5223 	while (connp != NULL) {
5224 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5225 		    conn_wantpacket(connp, ira, ipha) &&
5226 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5227 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5228 			break;
5229 		connp = connp->conn_next;
5230 	}
5231 
5232 	if (connp == NULL)
5233 		goto notfound;
5234 
5235 	CONN_INC_REF(connp);
5236 
5237 	if (connp->conn_reuseaddr) {
5238 		conn_t		*first_connp = connp;
5239 		conn_t		*next_connp;
5240 		mblk_t		*mp1;
5241 
5242 		connp = connp->conn_next;
5243 		for (;;) {
5244 			while (connp != NULL) {
5245 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5246 				    fport, faddr) &&
5247 				    conn_wantpacket(connp, ira, ipha) &&
5248 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5249 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5250 				    ira, connp)))
5251 					break;
5252 				connp = connp->conn_next;
5253 			}
5254 			if (connp == NULL) {
5255 				/* No more interested clients */
5256 				connp = first_connp;
5257 				break;
5258 			}
5259 			if (((mp1 = dupmsg(mp)) == NULL) &&
5260 			    ((mp1 = copymsg(mp)) == NULL)) {
5261 				/* Memory allocation failed */
5262 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5263 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5264 				connp = first_connp;
5265 				break;
5266 			}
5267 			CONN_INC_REF(connp);
5268 			mutex_exit(&connfp->connf_lock);
5269 
5270 			IP_STAT(ipst, ip_udp_fanmb);
5271 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5272 			    NULL, ira);
5273 			mutex_enter(&connfp->connf_lock);
5274 			/* Follow the next pointer before releasing the conn */
5275 			next_connp = connp->conn_next;
5276 			CONN_DEC_REF(connp);
5277 			connp = next_connp;
5278 		}
5279 	}
5280 
5281 	/* Last one.  Send it upstream. */
5282 	mutex_exit(&connfp->connf_lock);
5283 	IP_STAT(ipst, ip_udp_fanmb);
5284 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5285 	CONN_DEC_REF(connp);
5286 	return;
5287 
5288 notfound:
5289 	mutex_exit(&connfp->connf_lock);
5290 	/*
5291 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5292 	 * have already been matched above, since they live in the IPv4
5293 	 * fanout tables. This implies we only need to
5294 	 * check for IPv6 in6addr_any endpoints here.
5295 	 * Thus we compare using ipv6_all_zeros instead of the destination
5296 	 * address, except for the multicast group membership lookup which
5297 	 * uses the IPv4 destination.
5298 	 */
5299 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5300 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5301 	mutex_enter(&connfp->connf_lock);
5302 	connp = connfp->connf_head;
5303 	/*
5304 	 * IPv4 multicast packet being delivered to an AF_INET6
5305 	 * in6addr_any endpoint.
5306 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5307 	 * and not conn_wantpacket_v6() since any multicast membership is
5308 	 * for an IPv4-mapped multicast address.
5309 	 */
5310 	while (connp != NULL) {
5311 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5312 		    fport, v6faddr) &&
5313 		    conn_wantpacket(connp, ira, ipha) &&
5314 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5315 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5316 			break;
5317 		connp = connp->conn_next;
5318 	}
5319 
5320 	if (connp == NULL) {
5321 		/*
5322 		 * No one bound to this port.  Is
5323 		 * there a client that wants all
5324 		 * unclaimed datagrams?
5325 		 */
5326 		mutex_exit(&connfp->connf_lock);
5327 
5328 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5329 		    NULL) {
5330 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5331 			ip_fanout_proto_v4(mp, ipha, ira);
5332 		} else {
5333 			/*
5334 			 * We used to attempt to send an icmp error here, but
5335 			 * since this is known to be a multicast packet
5336 			 * and we don't send icmp errors in response to
5337 			 * multicast, just drop the packet and give up sooner.
5338 			 */
5339 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5340 			freemsg(mp);
5341 		}
5342 		return;
5343 	}
5344 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5345 
5346 	/*
5347 	 * If SO_REUSEADDR has been set on the first we send the
5348 	 * packet to all clients that have joined the group and
5349 	 * match the port.
5350 	 */
5351 	if (connp->conn_reuseaddr) {
5352 		conn_t		*first_connp = connp;
5353 		conn_t		*next_connp;
5354 		mblk_t		*mp1;
5355 
5356 		CONN_INC_REF(connp);
5357 		connp = connp->conn_next;
5358 		for (;;) {
5359 			while (connp != NULL) {
5360 				if (IPCL_UDP_MATCH_V6(connp, lport,
5361 				    ipv6_all_zeros, fport, v6faddr) &&
5362 				    conn_wantpacket(connp, ira, ipha) &&
5363 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5364 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5365 				    ira, connp)))
5366 					break;
5367 				connp = connp->conn_next;
5368 			}
5369 			if (connp == NULL) {
5370 				/* No more interested clients */
5371 				connp = first_connp;
5372 				break;
5373 			}
5374 			if (((mp1 = dupmsg(mp)) == NULL) &&
5375 			    ((mp1 = copymsg(mp)) == NULL)) {
5376 				/* Memory allocation failed */
5377 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5378 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5379 				connp = first_connp;
5380 				break;
5381 			}
5382 			CONN_INC_REF(connp);
5383 			mutex_exit(&connfp->connf_lock);
5384 
5385 			IP_STAT(ipst, ip_udp_fanmb);
5386 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5387 			    NULL, ira);
5388 			mutex_enter(&connfp->connf_lock);
5389 			/* Follow the next pointer before releasing the conn */
5390 			next_connp = connp->conn_next;
5391 			CONN_DEC_REF(connp);
5392 			connp = next_connp;
5393 		}
5394 	}
5395 
5396 	/* Last one.  Send it upstream. */
5397 	mutex_exit(&connfp->connf_lock);
5398 	IP_STAT(ipst, ip_udp_fanmb);
5399 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5400 	CONN_DEC_REF(connp);
5401 }
5402 
5403 /*
5404  * Split an incoming packet's IPv4 options into the label and the other options.
5405  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5406  * clearing out any leftover label or options.
5407  * Otherwise it just makes ipp point into the packet.
5408  *
5409  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5410  */
5411 int
5412 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5413 {
5414 	uchar_t		*opt;
5415 	uint32_t	totallen;
5416 	uint32_t	optval;
5417 	uint32_t	optlen;
5418 
5419 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5420 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5421 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5422 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5423 
5424 	/*
5425 	 * Get length (in 4 byte octets) of IP header options.
5426 	 */
5427 	totallen = ipha->ipha_version_and_hdr_length -
5428 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5429 
5430 	if (totallen == 0) {
5431 		if (!allocate)
5432 			return (0);
5433 
5434 		/* Clear out anything from a previous packet */
5435 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5436 			kmem_free(ipp->ipp_ipv4_options,
5437 			    ipp->ipp_ipv4_options_len);
5438 			ipp->ipp_ipv4_options = NULL;
5439 			ipp->ipp_ipv4_options_len = 0;
5440 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5441 		}
5442 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5443 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5444 			ipp->ipp_label_v4 = NULL;
5445 			ipp->ipp_label_len_v4 = 0;
5446 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5447 		}
5448 		return (0);
5449 	}
5450 
5451 	totallen <<= 2;
5452 	opt = (uchar_t *)&ipha[1];
5453 	if (!is_system_labeled()) {
5454 
5455 	copyall:
5456 		if (!allocate) {
5457 			if (totallen != 0) {
5458 				ipp->ipp_ipv4_options = opt;
5459 				ipp->ipp_ipv4_options_len = totallen;
5460 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5461 			}
5462 			return (0);
5463 		}
5464 		/* Just copy all of options */
5465 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5466 			if (totallen == ipp->ipp_ipv4_options_len) {
5467 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5468 				return (0);
5469 			}
5470 			kmem_free(ipp->ipp_ipv4_options,
5471 			    ipp->ipp_ipv4_options_len);
5472 			ipp->ipp_ipv4_options = NULL;
5473 			ipp->ipp_ipv4_options_len = 0;
5474 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5475 		}
5476 		if (totallen == 0)
5477 			return (0);
5478 
5479 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5480 		if (ipp->ipp_ipv4_options == NULL)
5481 			return (ENOMEM);
5482 		ipp->ipp_ipv4_options_len = totallen;
5483 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5484 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5485 		return (0);
5486 	}
5487 
5488 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5489 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5490 		ipp->ipp_label_v4 = NULL;
5491 		ipp->ipp_label_len_v4 = 0;
5492 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5493 	}
5494 
5495 	/*
5496 	 * Search for CIPSO option.
5497 	 * We assume CIPSO is first in options if it is present.
5498 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5499 	 * prior to the CIPSO option.
5500 	 */
5501 	while (totallen != 0) {
5502 		switch (optval = opt[IPOPT_OPTVAL]) {
5503 		case IPOPT_EOL:
5504 			return (0);
5505 		case IPOPT_NOP:
5506 			optlen = 1;
5507 			break;
5508 		default:
5509 			if (totallen <= IPOPT_OLEN)
5510 				return (EINVAL);
5511 			optlen = opt[IPOPT_OLEN];
5512 			if (optlen < 2)
5513 				return (EINVAL);
5514 		}
5515 		if (optlen > totallen)
5516 			return (EINVAL);
5517 
5518 		switch (optval) {
5519 		case IPOPT_COMSEC:
5520 			if (!allocate) {
5521 				ipp->ipp_label_v4 = opt;
5522 				ipp->ipp_label_len_v4 = optlen;
5523 				ipp->ipp_fields |= IPPF_LABEL_V4;
5524 			} else {
5525 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5526 				    KM_NOSLEEP);
5527 				if (ipp->ipp_label_v4 == NULL)
5528 					return (ENOMEM);
5529 				ipp->ipp_label_len_v4 = optlen;
5530 				ipp->ipp_fields |= IPPF_LABEL_V4;
5531 				bcopy(opt, ipp->ipp_label_v4, optlen);
5532 			}
5533 			totallen -= optlen;
5534 			opt += optlen;
5535 
5536 			/* Skip padding bytes until we get to a multiple of 4 */
5537 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5538 				totallen--;
5539 				opt++;
5540 			}
5541 			/* Remaining as ipp_ipv4_options */
5542 			goto copyall;
5543 		}
5544 		totallen -= optlen;
5545 		opt += optlen;
5546 	}
5547 	/* No CIPSO found; return everything as ipp_ipv4_options */
5548 	totallen = ipha->ipha_version_and_hdr_length -
5549 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5550 	totallen <<= 2;
5551 	opt = (uchar_t *)&ipha[1];
5552 	goto copyall;
5553 }
5554 
5555 /*
5556  * Efficient versions of lookup for an IRE when we only
5557  * match the address.
5558  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5559  * Does not handle multicast addresses.
5560  */
5561 uint_t
5562 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5563 {
5564 	ire_t *ire;
5565 	uint_t result;
5566 
5567 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5568 	ASSERT(ire != NULL);
5569 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5570 		result = IRE_NOROUTE;
5571 	else
5572 		result = ire->ire_type;
5573 	ire_refrele(ire);
5574 	return (result);
5575 }
5576 
5577 /*
5578  * Efficient versions of lookup for an IRE when we only
5579  * match the address.
5580  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5581  * Does not handle multicast addresses.
5582  */
5583 uint_t
5584 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5585 {
5586 	ire_t *ire;
5587 	uint_t result;
5588 
5589 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5590 	ASSERT(ire != NULL);
5591 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5592 		result = IRE_NOROUTE;
5593 	else
5594 		result = ire->ire_type;
5595 	ire_refrele(ire);
5596 	return (result);
5597 }
5598 
5599 /*
5600  * Nobody should be sending
5601  * packets up this stream
5602  */
5603 static void
5604 ip_lrput(queue_t *q, mblk_t *mp)
5605 {
5606 	switch (mp->b_datap->db_type) {
5607 	case M_FLUSH:
5608 		/* Turn around */
5609 		if (*mp->b_rptr & FLUSHW) {
5610 			*mp->b_rptr &= ~FLUSHR;
5611 			qreply(q, mp);
5612 			return;
5613 		}
5614 		break;
5615 	}
5616 	freemsg(mp);
5617 }
5618 
5619 /* Nobody should be sending packets down this stream */
5620 /* ARGSUSED */
5621 void
5622 ip_lwput(queue_t *q, mblk_t *mp)
5623 {
5624 	freemsg(mp);
5625 }
5626 
5627 /*
5628  * Move the first hop in any source route to ipha_dst and remove that part of
5629  * the source route.  Called by other protocols.  Errors in option formatting
5630  * are ignored - will be handled by ip_output_options. Return the final
5631  * destination (either ipha_dst or the last entry in a source route.)
5632  */
5633 ipaddr_t
5634 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5635 {
5636 	ipoptp_t	opts;
5637 	uchar_t		*opt;
5638 	uint8_t		optval;
5639 	uint8_t		optlen;
5640 	ipaddr_t	dst;
5641 	int		i;
5642 	ip_stack_t	*ipst = ns->netstack_ip;
5643 
5644 	ip2dbg(("ip_massage_options\n"));
5645 	dst = ipha->ipha_dst;
5646 	for (optval = ipoptp_first(&opts, ipha);
5647 	    optval != IPOPT_EOL;
5648 	    optval = ipoptp_next(&opts)) {
5649 		opt = opts.ipoptp_cur;
5650 		switch (optval) {
5651 			uint8_t off;
5652 		case IPOPT_SSRR:
5653 		case IPOPT_LSRR:
5654 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5655 				ip1dbg(("ip_massage_options: bad src route\n"));
5656 				break;
5657 			}
5658 			optlen = opts.ipoptp_len;
5659 			off = opt[IPOPT_OFFSET];
5660 			off--;
5661 		redo_srr:
5662 			if (optlen < IP_ADDR_LEN ||
5663 			    off > optlen - IP_ADDR_LEN) {
5664 				/* End of source route */
5665 				ip1dbg(("ip_massage_options: end of SR\n"));
5666 				break;
5667 			}
5668 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5669 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5670 			    ntohl(dst)));
5671 			/*
5672 			 * Check if our address is present more than
5673 			 * once as consecutive hops in source route.
5674 			 * XXX verify per-interface ip_forwarding
5675 			 * for source route?
5676 			 */
5677 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5678 				off += IP_ADDR_LEN;
5679 				goto redo_srr;
5680 			}
5681 			if (dst == htonl(INADDR_LOOPBACK)) {
5682 				ip1dbg(("ip_massage_options: loopback addr in "
5683 				    "source route!\n"));
5684 				break;
5685 			}
5686 			/*
5687 			 * Update ipha_dst to be the first hop and remove the
5688 			 * first hop from the source route (by overwriting
5689 			 * part of the option with NOP options).
5690 			 */
5691 			ipha->ipha_dst = dst;
5692 			/* Put the last entry in dst */
5693 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5694 			    3;
5695 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5696 
5697 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5698 			    ntohl(dst)));
5699 			/* Move down and overwrite */
5700 			opt[IP_ADDR_LEN] = opt[0];
5701 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5702 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5703 			for (i = 0; i < IP_ADDR_LEN; i++)
5704 				opt[i] = IPOPT_NOP;
5705 			break;
5706 		}
5707 	}
5708 	return (dst);
5709 }
5710 
5711 /*
5712  * Return the network mask
5713  * associated with the specified address.
5714  */
5715 ipaddr_t
5716 ip_net_mask(ipaddr_t addr)
5717 {
5718 	uchar_t	*up = (uchar_t *)&addr;
5719 	ipaddr_t mask = 0;
5720 	uchar_t	*maskp = (uchar_t *)&mask;
5721 
5722 #if defined(__i386) || defined(__amd64)
5723 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5724 #endif
5725 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5726 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5727 #endif
5728 	if (CLASSD(addr)) {
5729 		maskp[0] = 0xF0;
5730 		return (mask);
5731 	}
5732 
5733 	/* We assume Class E default netmask to be 32 */
5734 	if (CLASSE(addr))
5735 		return (0xffffffffU);
5736 
5737 	if (addr == 0)
5738 		return (0);
5739 	maskp[0] = 0xFF;
5740 	if ((up[0] & 0x80) == 0)
5741 		return (mask);
5742 
5743 	maskp[1] = 0xFF;
5744 	if ((up[0] & 0xC0) == 0x80)
5745 		return (mask);
5746 
5747 	maskp[2] = 0xFF;
5748 	if ((up[0] & 0xE0) == 0xC0)
5749 		return (mask);
5750 
5751 	/* Otherwise return no mask */
5752 	return ((ipaddr_t)0);
5753 }
5754 
5755 /* Name/Value Table Lookup Routine */
5756 char *
5757 ip_nv_lookup(nv_t *nv, int value)
5758 {
5759 	if (!nv)
5760 		return (NULL);
5761 	for (; nv->nv_name; nv++) {
5762 		if (nv->nv_value == value)
5763 			return (nv->nv_name);
5764 	}
5765 	return ("unknown");
5766 }
5767 
5768 static int
5769 ip_wait_for_info_ack(ill_t *ill)
5770 {
5771 	int err;
5772 
5773 	mutex_enter(&ill->ill_lock);
5774 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5775 		/*
5776 		 * Return value of 0 indicates a pending signal.
5777 		 */
5778 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5779 		if (err == 0) {
5780 			mutex_exit(&ill->ill_lock);
5781 			return (EINTR);
5782 		}
5783 	}
5784 	mutex_exit(&ill->ill_lock);
5785 	/*
5786 	 * ip_rput_other could have set an error  in ill_error on
5787 	 * receipt of M_ERROR.
5788 	 */
5789 	return (ill->ill_error);
5790 }
5791 
5792 /*
5793  * This is a module open, i.e. this is a control stream for access
5794  * to a DLPI device.  We allocate an ill_t as the instance data in
5795  * this case.
5796  */
5797 static int
5798 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5799 {
5800 	ill_t	*ill;
5801 	int	err;
5802 	zoneid_t zoneid;
5803 	netstack_t *ns;
5804 	ip_stack_t *ipst;
5805 
5806 	/*
5807 	 * Prevent unprivileged processes from pushing IP so that
5808 	 * they can't send raw IP.
5809 	 */
5810 	if (secpolicy_net_rawaccess(credp) != 0)
5811 		return (EPERM);
5812 
5813 	ns = netstack_find_by_cred(credp);
5814 	ASSERT(ns != NULL);
5815 	ipst = ns->netstack_ip;
5816 	ASSERT(ipst != NULL);
5817 
5818 	/*
5819 	 * For exclusive stacks we set the zoneid to zero
5820 	 * to make IP operate as if in the global zone.
5821 	 */
5822 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5823 		zoneid = GLOBAL_ZONEID;
5824 	else
5825 		zoneid = crgetzoneid(credp);
5826 
5827 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5828 	q->q_ptr = WR(q)->q_ptr = ill;
5829 	ill->ill_ipst = ipst;
5830 	ill->ill_zoneid = zoneid;
5831 
5832 	/*
5833 	 * ill_init initializes the ill fields and then sends down
5834 	 * down a DL_INFO_REQ after calling qprocson.
5835 	 */
5836 	err = ill_init(q, ill);
5837 
5838 	if (err != 0) {
5839 		mi_free(ill);
5840 		netstack_rele(ipst->ips_netstack);
5841 		q->q_ptr = NULL;
5842 		WR(q)->q_ptr = NULL;
5843 		return (err);
5844 	}
5845 
5846 	/*
5847 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5848 	 *
5849 	 * ill_init initializes the ipsq marking this thread as
5850 	 * writer
5851 	 */
5852 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5853 	err = ip_wait_for_info_ack(ill);
5854 	if (err == 0)
5855 		ill->ill_credp = credp;
5856 	else
5857 		goto fail;
5858 
5859 	crhold(credp);
5860 
5861 	mutex_enter(&ipst->ips_ip_mi_lock);
5862 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5863 	    sflag, credp);
5864 	mutex_exit(&ipst->ips_ip_mi_lock);
5865 fail:
5866 	if (err) {
5867 		(void) ip_close(q, 0);
5868 		return (err);
5869 	}
5870 	return (0);
5871 }
5872 
5873 /* For /dev/ip aka AF_INET open */
5874 int
5875 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5876 {
5877 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5878 }
5879 
5880 /* For /dev/ip6 aka AF_INET6 open */
5881 int
5882 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5883 {
5884 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5885 }
5886 
5887 /* IP open routine. */
5888 int
5889 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5890     boolean_t isv6)
5891 {
5892 	conn_t 		*connp;
5893 	major_t		maj;
5894 	zoneid_t	zoneid;
5895 	netstack_t	*ns;
5896 	ip_stack_t	*ipst;
5897 
5898 	/* Allow reopen. */
5899 	if (q->q_ptr != NULL)
5900 		return (0);
5901 
5902 	if (sflag & MODOPEN) {
5903 		/* This is a module open */
5904 		return (ip_modopen(q, devp, flag, sflag, credp));
5905 	}
5906 
5907 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5908 		/*
5909 		 * Non streams based socket looking for a stream
5910 		 * to access IP
5911 		 */
5912 		return (ip_helper_stream_setup(q, devp, flag, sflag,
5913 		    credp, isv6));
5914 	}
5915 
5916 	ns = netstack_find_by_cred(credp);
5917 	ASSERT(ns != NULL);
5918 	ipst = ns->netstack_ip;
5919 	ASSERT(ipst != NULL);
5920 
5921 	/*
5922 	 * For exclusive stacks we set the zoneid to zero
5923 	 * to make IP operate as if in the global zone.
5924 	 */
5925 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5926 		zoneid = GLOBAL_ZONEID;
5927 	else
5928 		zoneid = crgetzoneid(credp);
5929 
5930 	/*
5931 	 * We are opening as a device. This is an IP client stream, and we
5932 	 * allocate an conn_t as the instance data.
5933 	 */
5934 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
5935 
5936 	/*
5937 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
5938 	 * done by netstack_find_by_cred()
5939 	 */
5940 	netstack_rele(ipst->ips_netstack);
5941 
5942 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
5943 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
5944 	connp->conn_ixa->ixa_zoneid = zoneid;
5945 	connp->conn_zoneid = zoneid;
5946 
5947 	connp->conn_rq = q;
5948 	q->q_ptr = WR(q)->q_ptr = connp;
5949 
5950 	/* Minor tells us which /dev entry was opened */
5951 	if (isv6) {
5952 		connp->conn_family = AF_INET6;
5953 		connp->conn_ipversion = IPV6_VERSION;
5954 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
5955 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
5956 	} else {
5957 		connp->conn_family = AF_INET;
5958 		connp->conn_ipversion = IPV4_VERSION;
5959 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
5960 	}
5961 
5962 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
5963 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
5964 		connp->conn_minor_arena = ip_minor_arena_la;
5965 	} else {
5966 		/*
5967 		 * Either minor numbers in the large arena were exhausted
5968 		 * or a non socket application is doing the open.
5969 		 * Try to allocate from the small arena.
5970 		 */
5971 		if ((connp->conn_dev =
5972 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
5973 			/* CONN_DEC_REF takes care of netstack_rele() */
5974 			q->q_ptr = WR(q)->q_ptr = NULL;
5975 			CONN_DEC_REF(connp);
5976 			return (EBUSY);
5977 		}
5978 		connp->conn_minor_arena = ip_minor_arena_sa;
5979 	}
5980 
5981 	maj = getemajor(*devp);
5982 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
5983 
5984 	/*
5985 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
5986 	 */
5987 	connp->conn_cred = credp;
5988 	connp->conn_cpid = curproc->p_pid;
5989 	/* Cache things in ixa without an extra refhold */
5990 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
5991 	connp->conn_ixa->ixa_cred = connp->conn_cred;
5992 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
5993 	if (is_system_labeled())
5994 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
5995 
5996 	/*
5997 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
5998 	 */
5999 	connp->conn_recv = ip_conn_input;
6000 	connp->conn_recvicmp = ip_conn_input_icmp;
6001 
6002 	crhold(connp->conn_cred);
6003 
6004 	/*
6005 	 * If the caller has the process-wide flag set, then default to MAC
6006 	 * exempt mode.  This allows read-down to unlabeled hosts.
6007 	 */
6008 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6009 		connp->conn_mac_mode = CONN_MAC_AWARE;
6010 
6011 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6012 
6013 	connp->conn_rq = q;
6014 	connp->conn_wq = WR(q);
6015 
6016 	/* Non-zero default values */
6017 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6018 
6019 	/*
6020 	 * Make the conn globally visible to walkers
6021 	 */
6022 	ASSERT(connp->conn_ref == 1);
6023 	mutex_enter(&connp->conn_lock);
6024 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6025 	mutex_exit(&connp->conn_lock);
6026 
6027 	qprocson(q);
6028 
6029 	return (0);
6030 }
6031 
6032 /*
6033  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6034  * all of them are copied to the conn_t. If the req is "zero", the policy is
6035  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6036  * fields.
6037  * We keep only the latest setting of the policy and thus policy setting
6038  * is not incremental/cumulative.
6039  *
6040  * Requests to set policies with multiple alternative actions will
6041  * go through a different API.
6042  */
6043 int
6044 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6045 {
6046 	uint_t ah_req = 0;
6047 	uint_t esp_req = 0;
6048 	uint_t se_req = 0;
6049 	ipsec_act_t *actp = NULL;
6050 	uint_t nact;
6051 	ipsec_policy_head_t *ph;
6052 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6053 	int error = 0;
6054 	netstack_t	*ns = connp->conn_netstack;
6055 	ip_stack_t	*ipst = ns->netstack_ip;
6056 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6057 
6058 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6059 
6060 	/*
6061 	 * The IP_SEC_OPT option does not allow variable length parameters,
6062 	 * hence a request cannot be NULL.
6063 	 */
6064 	if (req == NULL)
6065 		return (EINVAL);
6066 
6067 	ah_req = req->ipsr_ah_req;
6068 	esp_req = req->ipsr_esp_req;
6069 	se_req = req->ipsr_self_encap_req;
6070 
6071 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6072 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6073 		return (EINVAL);
6074 
6075 	/*
6076 	 * Are we dealing with a request to reset the policy (i.e.
6077 	 * zero requests).
6078 	 */
6079 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6080 	    (esp_req & REQ_MASK) == 0 &&
6081 	    (se_req & REQ_MASK) == 0);
6082 
6083 	if (!is_pol_reset) {
6084 		/*
6085 		 * If we couldn't load IPsec, fail with "protocol
6086 		 * not supported".
6087 		 * IPsec may not have been loaded for a request with zero
6088 		 * policies, so we don't fail in this case.
6089 		 */
6090 		mutex_enter(&ipss->ipsec_loader_lock);
6091 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6092 			mutex_exit(&ipss->ipsec_loader_lock);
6093 			return (EPROTONOSUPPORT);
6094 		}
6095 		mutex_exit(&ipss->ipsec_loader_lock);
6096 
6097 		/*
6098 		 * Test for valid requests. Invalid algorithms
6099 		 * need to be tested by IPsec code because new
6100 		 * algorithms can be added dynamically.
6101 		 */
6102 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6103 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6104 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6105 			return (EINVAL);
6106 		}
6107 
6108 		/*
6109 		 * Only privileged users can issue these
6110 		 * requests.
6111 		 */
6112 		if (((ah_req & IPSEC_PREF_NEVER) ||
6113 		    (esp_req & IPSEC_PREF_NEVER) ||
6114 		    (se_req & IPSEC_PREF_NEVER)) &&
6115 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6116 			return (EPERM);
6117 		}
6118 
6119 		/*
6120 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6121 		 * are mutually exclusive.
6122 		 */
6123 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6124 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6125 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6126 			/* Both of them are set */
6127 			return (EINVAL);
6128 		}
6129 	}
6130 
6131 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6132 
6133 	/*
6134 	 * If we have already cached policies in conn_connect(), don't
6135 	 * let them change now. We cache policies for connections
6136 	 * whose src,dst [addr, port] is known.
6137 	 */
6138 	if (connp->conn_policy_cached) {
6139 		return (EINVAL);
6140 	}
6141 
6142 	/*
6143 	 * We have a zero policies, reset the connection policy if already
6144 	 * set. This will cause the connection to inherit the
6145 	 * global policy, if any.
6146 	 */
6147 	if (is_pol_reset) {
6148 		if (connp->conn_policy != NULL) {
6149 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6150 			connp->conn_policy = NULL;
6151 		}
6152 		connp->conn_in_enforce_policy = B_FALSE;
6153 		connp->conn_out_enforce_policy = B_FALSE;
6154 		return (0);
6155 	}
6156 
6157 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6158 	    ipst->ips_netstack);
6159 	if (ph == NULL)
6160 		goto enomem;
6161 
6162 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6163 	if (actp == NULL)
6164 		goto enomem;
6165 
6166 	/*
6167 	 * Always insert IPv4 policy entries, since they can also apply to
6168 	 * ipv6 sockets being used in ipv4-compat mode.
6169 	 */
6170 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6171 	    IPSEC_TYPE_INBOUND, ns))
6172 		goto enomem;
6173 	is_pol_inserted = B_TRUE;
6174 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6175 	    IPSEC_TYPE_OUTBOUND, ns))
6176 		goto enomem;
6177 
6178 	/*
6179 	 * We're looking at a v6 socket, also insert the v6-specific
6180 	 * entries.
6181 	 */
6182 	if (connp->conn_family == AF_INET6) {
6183 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6184 		    IPSEC_TYPE_INBOUND, ns))
6185 			goto enomem;
6186 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6187 		    IPSEC_TYPE_OUTBOUND, ns))
6188 			goto enomem;
6189 	}
6190 
6191 	ipsec_actvec_free(actp, nact);
6192 
6193 	/*
6194 	 * If the requests need security, set enforce_policy.
6195 	 * If the requests are IPSEC_PREF_NEVER, one should
6196 	 * still set conn_out_enforce_policy so that ip_set_destination
6197 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6198 	 * for connections that we don't cache policy in at connect time,
6199 	 * if global policy matches in ip_output_attach_policy, we
6200 	 * don't wrongly inherit global policy. Similarly, we need
6201 	 * to set conn_in_enforce_policy also so that we don't verify
6202 	 * policy wrongly.
6203 	 */
6204 	if ((ah_req & REQ_MASK) != 0 ||
6205 	    (esp_req & REQ_MASK) != 0 ||
6206 	    (se_req & REQ_MASK) != 0) {
6207 		connp->conn_in_enforce_policy = B_TRUE;
6208 		connp->conn_out_enforce_policy = B_TRUE;
6209 	}
6210 
6211 	return (error);
6212 #undef REQ_MASK
6213 
6214 	/*
6215 	 * Common memory-allocation-failure exit path.
6216 	 */
6217 enomem:
6218 	if (actp != NULL)
6219 		ipsec_actvec_free(actp, nact);
6220 	if (is_pol_inserted)
6221 		ipsec_polhead_flush(ph, ns);
6222 	return (ENOMEM);
6223 }
6224 
6225 /*
6226  * Set socket options for joining and leaving multicast groups.
6227  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6228  * The caller has already check that the option name is consistent with
6229  * the address family of the socket.
6230  */
6231 int
6232 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6233     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6234 {
6235 	int		*i1 = (int *)invalp;
6236 	int		error = 0;
6237 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6238 	struct ip_mreq	*v4_mreqp;
6239 	struct ipv6_mreq *v6_mreqp;
6240 	struct group_req *greqp;
6241 	ire_t *ire;
6242 	boolean_t done = B_FALSE;
6243 	ipaddr_t ifaddr;
6244 	in6_addr_t v6group;
6245 	uint_t ifindex;
6246 	boolean_t mcast_opt = B_TRUE;
6247 	mcast_record_t fmode;
6248 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6249 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6250 
6251 	switch (name) {
6252 	case IP_ADD_MEMBERSHIP:
6253 	case IPV6_JOIN_GROUP:
6254 		mcast_opt = B_FALSE;
6255 		/* FALLTHRU */
6256 	case MCAST_JOIN_GROUP:
6257 		fmode = MODE_IS_EXCLUDE;
6258 		optfn = ip_opt_add_group;
6259 		break;
6260 
6261 	case IP_DROP_MEMBERSHIP:
6262 	case IPV6_LEAVE_GROUP:
6263 		mcast_opt = B_FALSE;
6264 		/* FALLTHRU */
6265 	case MCAST_LEAVE_GROUP:
6266 		fmode = MODE_IS_INCLUDE;
6267 		optfn = ip_opt_delete_group;
6268 		break;
6269 	default:
6270 		ASSERT(0);
6271 	}
6272 
6273 	if (mcast_opt) {
6274 		struct sockaddr_in *sin;
6275 		struct sockaddr_in6 *sin6;
6276 
6277 		greqp = (struct group_req *)i1;
6278 		if (greqp->gr_group.ss_family == AF_INET) {
6279 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6280 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6281 		} else {
6282 			if (!inet6)
6283 				return (EINVAL);	/* Not on INET socket */
6284 
6285 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6286 			v6group = sin6->sin6_addr;
6287 		}
6288 		ifaddr = INADDR_ANY;
6289 		ifindex = greqp->gr_interface;
6290 	} else if (inet6) {
6291 		v6_mreqp = (struct ipv6_mreq *)i1;
6292 		v6group = v6_mreqp->ipv6mr_multiaddr;
6293 		ifaddr = INADDR_ANY;
6294 		ifindex = v6_mreqp->ipv6mr_interface;
6295 	} else {
6296 		v4_mreqp = (struct ip_mreq *)i1;
6297 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6298 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6299 		ifindex = 0;
6300 	}
6301 
6302 	/*
6303 	 * In the multirouting case, we need to replicate
6304 	 * the request on all interfaces that will take part
6305 	 * in replication.  We do so because multirouting is
6306 	 * reflective, thus we will probably receive multi-
6307 	 * casts on those interfaces.
6308 	 * The ip_multirt_apply_membership() succeeds if
6309 	 * the operation succeeds on at least one interface.
6310 	 */
6311 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6312 		ipaddr_t group;
6313 
6314 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6315 
6316 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6317 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6318 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6319 	} else {
6320 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6321 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6322 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6323 	}
6324 	if (ire != NULL) {
6325 		if (ire->ire_flags & RTF_MULTIRT) {
6326 			error = ip_multirt_apply_membership(optfn, ire, connp,
6327 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6328 			done = B_TRUE;
6329 		}
6330 		ire_refrele(ire);
6331 	}
6332 
6333 	if (!done) {
6334 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6335 		    fmode, &ipv6_all_zeros);
6336 	}
6337 	return (error);
6338 }
6339 
6340 /*
6341  * Set socket options for joining and leaving multicast groups
6342  * for specific sources.
6343  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6344  * The caller has already check that the option name is consistent with
6345  * the address family of the socket.
6346  */
6347 int
6348 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6349     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6350 {
6351 	int		*i1 = (int *)invalp;
6352 	int		error = 0;
6353 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6354 	struct ip_mreq_source *imreqp;
6355 	struct group_source_req *gsreqp;
6356 	in6_addr_t v6group, v6src;
6357 	uint32_t ifindex;
6358 	ipaddr_t ifaddr;
6359 	boolean_t mcast_opt = B_TRUE;
6360 	mcast_record_t fmode;
6361 	ire_t *ire;
6362 	boolean_t done = B_FALSE;
6363 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6364 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6365 
6366 	switch (name) {
6367 	case IP_BLOCK_SOURCE:
6368 		mcast_opt = B_FALSE;
6369 		/* FALLTHRU */
6370 	case MCAST_BLOCK_SOURCE:
6371 		fmode = MODE_IS_EXCLUDE;
6372 		optfn = ip_opt_add_group;
6373 		break;
6374 
6375 	case IP_UNBLOCK_SOURCE:
6376 		mcast_opt = B_FALSE;
6377 		/* FALLTHRU */
6378 	case MCAST_UNBLOCK_SOURCE:
6379 		fmode = MODE_IS_EXCLUDE;
6380 		optfn = ip_opt_delete_group;
6381 		break;
6382 
6383 	case IP_ADD_SOURCE_MEMBERSHIP:
6384 		mcast_opt = B_FALSE;
6385 		/* FALLTHRU */
6386 	case MCAST_JOIN_SOURCE_GROUP:
6387 		fmode = MODE_IS_INCLUDE;
6388 		optfn = ip_opt_add_group;
6389 		break;
6390 
6391 	case IP_DROP_SOURCE_MEMBERSHIP:
6392 		mcast_opt = B_FALSE;
6393 		/* FALLTHRU */
6394 	case MCAST_LEAVE_SOURCE_GROUP:
6395 		fmode = MODE_IS_INCLUDE;
6396 		optfn = ip_opt_delete_group;
6397 		break;
6398 	default:
6399 		ASSERT(0);
6400 	}
6401 
6402 	if (mcast_opt) {
6403 		gsreqp = (struct group_source_req *)i1;
6404 		ifindex = gsreqp->gsr_interface;
6405 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6406 			struct sockaddr_in *s;
6407 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6408 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6409 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6410 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6411 		} else {
6412 			struct sockaddr_in6 *s6;
6413 
6414 			if (!inet6)
6415 				return (EINVAL);	/* Not on INET socket */
6416 
6417 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6418 			v6group = s6->sin6_addr;
6419 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6420 			v6src = s6->sin6_addr;
6421 		}
6422 		ifaddr = INADDR_ANY;
6423 	} else {
6424 		imreqp = (struct ip_mreq_source *)i1;
6425 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6426 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6427 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6428 		ifindex = 0;
6429 	}
6430 
6431 	/*
6432 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6433 	 */
6434 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6435 		v6src = ipv6_all_zeros;
6436 
6437 	/*
6438 	 * In the multirouting case, we need to replicate
6439 	 * the request as noted in the mcast cases above.
6440 	 */
6441 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6442 		ipaddr_t group;
6443 
6444 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6445 
6446 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6447 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6448 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6449 	} else {
6450 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6451 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6452 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6453 	}
6454 	if (ire != NULL) {
6455 		if (ire->ire_flags & RTF_MULTIRT) {
6456 			error = ip_multirt_apply_membership(optfn, ire, connp,
6457 			    checkonly, &v6group, fmode, &v6src);
6458 			done = B_TRUE;
6459 		}
6460 		ire_refrele(ire);
6461 	}
6462 	if (!done) {
6463 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6464 		    fmode, &v6src);
6465 	}
6466 	return (error);
6467 }
6468 
6469 /*
6470  * Given a destination address and a pointer to where to put the information
6471  * this routine fills in the mtuinfo.
6472  * The socket must be connected.
6473  * For sctp conn_faddr is the primary address.
6474  */
6475 int
6476 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6477 {
6478 	uint32_t	pmtu = IP_MAXPACKET;
6479 	uint_t		scopeid;
6480 
6481 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6482 		return (-1);
6483 
6484 	/* In case we never sent or called ip_set_destination_v4/v6 */
6485 	if (ixa->ixa_ire != NULL)
6486 		pmtu = ip_get_pmtu(ixa);
6487 
6488 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6489 		scopeid = ixa->ixa_scopeid;
6490 	else
6491 		scopeid = 0;
6492 
6493 	bzero(mtuinfo, sizeof (*mtuinfo));
6494 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6495 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6496 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6497 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6498 	mtuinfo->ip6m_mtu = pmtu;
6499 
6500 	return (sizeof (struct ip6_mtuinfo));
6501 }
6502 
6503 /*
6504  * When the src multihoming is changed from weak to [strong, preferred]
6505  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6506  * and identify routes that were created by user-applications in the
6507  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6508  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6509  * is selected by finding an interface route for the gateway.
6510  */
6511 /* ARGSUSED */
6512 void
6513 ip_ire_rebind_walker(ire_t *ire, void *notused)
6514 {
6515 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6516 		return;
6517 	ire_rebind(ire);
6518 	ire_delete(ire);
6519 }
6520 
6521 /*
6522  * When the src multihoming is changed from  [strong, preferred] to weak,
6523  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6524  * set any entries that were created by user-applications in the unbound state
6525  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6526  */
6527 /* ARGSUSED */
6528 void
6529 ip_ire_unbind_walker(ire_t *ire, void *notused)
6530 {
6531 	ire_t *new_ire;
6532 
6533 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6534 		return;
6535 	if (ire->ire_ipversion == IPV6_VERSION) {
6536 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6537 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6538 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6539 	} else {
6540 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6541 		    (uchar_t *)&ire->ire_mask,
6542 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6543 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6544 	}
6545 	if (new_ire == NULL)
6546 		return;
6547 	new_ire->ire_unbound = B_TRUE;
6548 	/*
6549 	 * The bound ire must first be deleted so that we don't return
6550 	 * the existing one on the attempt to add the unbound new_ire.
6551 	 */
6552 	ire_delete(ire);
6553 	new_ire = ire_add(new_ire);
6554 	if (new_ire != NULL)
6555 		ire_refrele(new_ire);
6556 }
6557 
6558 /*
6559  * When the settings of ip*_strict_src_multihoming tunables are changed,
6560  * all cached routes need to be recomputed. This recomputation needs to be
6561  * done when going from weaker to stronger modes so that the cached ire
6562  * for the connection does not violate the current ip*_strict_src_multihoming
6563  * setting. It also needs to be done when going from stronger to weaker modes,
6564  * so that we fall back to matching on the longest-matching-route (as opposed
6565  * to a shorter match that may have been selected in the strong mode
6566  * to satisfy src_multihoming settings).
6567  *
6568  * The cached ixa_ire entires for all conn_t entries are marked as
6569  * "verify" so that they will be recomputed for the next packet.
6570  */
6571 void
6572 conn_ire_revalidate(conn_t *connp, void *arg)
6573 {
6574 	boolean_t isv6 = (boolean_t)arg;
6575 
6576 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6577 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6578 		return;
6579 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6580 }
6581 
6582 /*
6583  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6584  * When an ipf is passed here for the first time, if
6585  * we already have in-order fragments on the queue, we convert from the fast-
6586  * path reassembly scheme to the hard-case scheme.  From then on, additional
6587  * fragments are reassembled here.  We keep track of the start and end offsets
6588  * of each piece, and the number of holes in the chain.  When the hole count
6589  * goes to zero, we are done!
6590  *
6591  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6592  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6593  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6594  * after the call to ip_reassemble().
6595  */
6596 int
6597 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6598     size_t msg_len)
6599 {
6600 	uint_t	end;
6601 	mblk_t	*next_mp;
6602 	mblk_t	*mp1;
6603 	uint_t	offset;
6604 	boolean_t incr_dups = B_TRUE;
6605 	boolean_t offset_zero_seen = B_FALSE;
6606 	boolean_t pkt_boundary_checked = B_FALSE;
6607 
6608 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6609 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6610 
6611 	/* Add in byte count */
6612 	ipf->ipf_count += msg_len;
6613 	if (ipf->ipf_end) {
6614 		/*
6615 		 * We were part way through in-order reassembly, but now there
6616 		 * is a hole.  We walk through messages already queued, and
6617 		 * mark them for hard case reassembly.  We know that up till
6618 		 * now they were in order starting from offset zero.
6619 		 */
6620 		offset = 0;
6621 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6622 			IP_REASS_SET_START(mp1, offset);
6623 			if (offset == 0) {
6624 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6625 				offset = -ipf->ipf_nf_hdr_len;
6626 			}
6627 			offset += mp1->b_wptr - mp1->b_rptr;
6628 			IP_REASS_SET_END(mp1, offset);
6629 		}
6630 		/* One hole at the end. */
6631 		ipf->ipf_hole_cnt = 1;
6632 		/* Brand it as a hard case, forever. */
6633 		ipf->ipf_end = 0;
6634 	}
6635 	/* Walk through all the new pieces. */
6636 	do {
6637 		end = start + (mp->b_wptr - mp->b_rptr);
6638 		/*
6639 		 * If start is 0, decrease 'end' only for the first mblk of
6640 		 * the fragment. Otherwise 'end' can get wrong value in the
6641 		 * second pass of the loop if first mblk is exactly the
6642 		 * size of ipf_nf_hdr_len.
6643 		 */
6644 		if (start == 0 && !offset_zero_seen) {
6645 			/* First segment */
6646 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6647 			end -= ipf->ipf_nf_hdr_len;
6648 			offset_zero_seen = B_TRUE;
6649 		}
6650 		next_mp = mp->b_cont;
6651 		/*
6652 		 * We are checking to see if there is any interesing data
6653 		 * to process.  If there isn't and the mblk isn't the
6654 		 * one which carries the unfragmentable header then we
6655 		 * drop it.  It's possible to have just the unfragmentable
6656 		 * header come through without any data.  That needs to be
6657 		 * saved.
6658 		 *
6659 		 * If the assert at the top of this function holds then the
6660 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6661 		 * is infrequently traveled enough that the test is left in
6662 		 * to protect against future code changes which break that
6663 		 * invariant.
6664 		 */
6665 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6666 			/* Empty.  Blast it. */
6667 			IP_REASS_SET_START(mp, 0);
6668 			IP_REASS_SET_END(mp, 0);
6669 			/*
6670 			 * If the ipf points to the mblk we are about to free,
6671 			 * update ipf to point to the next mblk (or NULL
6672 			 * if none).
6673 			 */
6674 			if (ipf->ipf_mp->b_cont == mp)
6675 				ipf->ipf_mp->b_cont = next_mp;
6676 			freeb(mp);
6677 			continue;
6678 		}
6679 		mp->b_cont = NULL;
6680 		IP_REASS_SET_START(mp, start);
6681 		IP_REASS_SET_END(mp, end);
6682 		if (!ipf->ipf_tail_mp) {
6683 			ipf->ipf_tail_mp = mp;
6684 			ipf->ipf_mp->b_cont = mp;
6685 			if (start == 0 || !more) {
6686 				ipf->ipf_hole_cnt = 1;
6687 				/*
6688 				 * if the first fragment comes in more than one
6689 				 * mblk, this loop will be executed for each
6690 				 * mblk. Need to adjust hole count so exiting
6691 				 * this routine will leave hole count at 1.
6692 				 */
6693 				if (next_mp)
6694 					ipf->ipf_hole_cnt++;
6695 			} else
6696 				ipf->ipf_hole_cnt = 2;
6697 			continue;
6698 		} else if (ipf->ipf_last_frag_seen && !more &&
6699 		    !pkt_boundary_checked) {
6700 			/*
6701 			 * We check datagram boundary only if this fragment
6702 			 * claims to be the last fragment and we have seen a
6703 			 * last fragment in the past too. We do this only
6704 			 * once for a given fragment.
6705 			 *
6706 			 * start cannot be 0 here as fragments with start=0
6707 			 * and MF=0 gets handled as a complete packet. These
6708 			 * fragments should not reach here.
6709 			 */
6710 
6711 			if (start + msgdsize(mp) !=
6712 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6713 				/*
6714 				 * We have two fragments both of which claim
6715 				 * to be the last fragment but gives conflicting
6716 				 * information about the whole datagram size.
6717 				 * Something fishy is going on. Drop the
6718 				 * fragment and free up the reassembly list.
6719 				 */
6720 				return (IP_REASS_FAILED);
6721 			}
6722 
6723 			/*
6724 			 * We shouldn't come to this code block again for this
6725 			 * particular fragment.
6726 			 */
6727 			pkt_boundary_checked = B_TRUE;
6728 		}
6729 
6730 		/* New stuff at or beyond tail? */
6731 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6732 		if (start >= offset) {
6733 			if (ipf->ipf_last_frag_seen) {
6734 				/* current fragment is beyond last fragment */
6735 				return (IP_REASS_FAILED);
6736 			}
6737 			/* Link it on end. */
6738 			ipf->ipf_tail_mp->b_cont = mp;
6739 			ipf->ipf_tail_mp = mp;
6740 			if (more) {
6741 				if (start != offset)
6742 					ipf->ipf_hole_cnt++;
6743 			} else if (start == offset && next_mp == NULL)
6744 					ipf->ipf_hole_cnt--;
6745 			continue;
6746 		}
6747 		mp1 = ipf->ipf_mp->b_cont;
6748 		offset = IP_REASS_START(mp1);
6749 		/* New stuff at the front? */
6750 		if (start < offset) {
6751 			if (start == 0) {
6752 				if (end >= offset) {
6753 					/* Nailed the hole at the begining. */
6754 					ipf->ipf_hole_cnt--;
6755 				}
6756 			} else if (end < offset) {
6757 				/*
6758 				 * A hole, stuff, and a hole where there used
6759 				 * to be just a hole.
6760 				 */
6761 				ipf->ipf_hole_cnt++;
6762 			}
6763 			mp->b_cont = mp1;
6764 			/* Check for overlap. */
6765 			while (end > offset) {
6766 				if (end < IP_REASS_END(mp1)) {
6767 					mp->b_wptr -= end - offset;
6768 					IP_REASS_SET_END(mp, offset);
6769 					BUMP_MIB(ill->ill_ip_mib,
6770 					    ipIfStatsReasmPartDups);
6771 					break;
6772 				}
6773 				/* Did we cover another hole? */
6774 				if ((mp1->b_cont &&
6775 				    IP_REASS_END(mp1) !=
6776 				    IP_REASS_START(mp1->b_cont) &&
6777 				    end >= IP_REASS_START(mp1->b_cont)) ||
6778 				    (!ipf->ipf_last_frag_seen && !more)) {
6779 					ipf->ipf_hole_cnt--;
6780 				}
6781 				/* Clip out mp1. */
6782 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6783 					/*
6784 					 * After clipping out mp1, this guy
6785 					 * is now hanging off the end.
6786 					 */
6787 					ipf->ipf_tail_mp = mp;
6788 				}
6789 				IP_REASS_SET_START(mp1, 0);
6790 				IP_REASS_SET_END(mp1, 0);
6791 				/* Subtract byte count */
6792 				ipf->ipf_count -= mp1->b_datap->db_lim -
6793 				    mp1->b_datap->db_base;
6794 				freeb(mp1);
6795 				BUMP_MIB(ill->ill_ip_mib,
6796 				    ipIfStatsReasmPartDups);
6797 				mp1 = mp->b_cont;
6798 				if (!mp1)
6799 					break;
6800 				offset = IP_REASS_START(mp1);
6801 			}
6802 			ipf->ipf_mp->b_cont = mp;
6803 			continue;
6804 		}
6805 		/*
6806 		 * The new piece starts somewhere between the start of the head
6807 		 * and before the end of the tail.
6808 		 */
6809 		for (; mp1; mp1 = mp1->b_cont) {
6810 			offset = IP_REASS_END(mp1);
6811 			if (start < offset) {
6812 				if (end <= offset) {
6813 					/* Nothing new. */
6814 					IP_REASS_SET_START(mp, 0);
6815 					IP_REASS_SET_END(mp, 0);
6816 					/* Subtract byte count */
6817 					ipf->ipf_count -= mp->b_datap->db_lim -
6818 					    mp->b_datap->db_base;
6819 					if (incr_dups) {
6820 						ipf->ipf_num_dups++;
6821 						incr_dups = B_FALSE;
6822 					}
6823 					freeb(mp);
6824 					BUMP_MIB(ill->ill_ip_mib,
6825 					    ipIfStatsReasmDuplicates);
6826 					break;
6827 				}
6828 				/*
6829 				 * Trim redundant stuff off beginning of new
6830 				 * piece.
6831 				 */
6832 				IP_REASS_SET_START(mp, offset);
6833 				mp->b_rptr += offset - start;
6834 				BUMP_MIB(ill->ill_ip_mib,
6835 				    ipIfStatsReasmPartDups);
6836 				start = offset;
6837 				if (!mp1->b_cont) {
6838 					/*
6839 					 * After trimming, this guy is now
6840 					 * hanging off the end.
6841 					 */
6842 					mp1->b_cont = mp;
6843 					ipf->ipf_tail_mp = mp;
6844 					if (!more) {
6845 						ipf->ipf_hole_cnt--;
6846 					}
6847 					break;
6848 				}
6849 			}
6850 			if (start >= IP_REASS_START(mp1->b_cont))
6851 				continue;
6852 			/* Fill a hole */
6853 			if (start > offset)
6854 				ipf->ipf_hole_cnt++;
6855 			mp->b_cont = mp1->b_cont;
6856 			mp1->b_cont = mp;
6857 			mp1 = mp->b_cont;
6858 			offset = IP_REASS_START(mp1);
6859 			if (end >= offset) {
6860 				ipf->ipf_hole_cnt--;
6861 				/* Check for overlap. */
6862 				while (end > offset) {
6863 					if (end < IP_REASS_END(mp1)) {
6864 						mp->b_wptr -= end - offset;
6865 						IP_REASS_SET_END(mp, offset);
6866 						/*
6867 						 * TODO we might bump
6868 						 * this up twice if there is
6869 						 * overlap at both ends.
6870 						 */
6871 						BUMP_MIB(ill->ill_ip_mib,
6872 						    ipIfStatsReasmPartDups);
6873 						break;
6874 					}
6875 					/* Did we cover another hole? */
6876 					if ((mp1->b_cont &&
6877 					    IP_REASS_END(mp1)
6878 					    != IP_REASS_START(mp1->b_cont) &&
6879 					    end >=
6880 					    IP_REASS_START(mp1->b_cont)) ||
6881 					    (!ipf->ipf_last_frag_seen &&
6882 					    !more)) {
6883 						ipf->ipf_hole_cnt--;
6884 					}
6885 					/* Clip out mp1. */
6886 					if ((mp->b_cont = mp1->b_cont) ==
6887 					    NULL) {
6888 						/*
6889 						 * After clipping out mp1,
6890 						 * this guy is now hanging
6891 						 * off the end.
6892 						 */
6893 						ipf->ipf_tail_mp = mp;
6894 					}
6895 					IP_REASS_SET_START(mp1, 0);
6896 					IP_REASS_SET_END(mp1, 0);
6897 					/* Subtract byte count */
6898 					ipf->ipf_count -=
6899 					    mp1->b_datap->db_lim -
6900 					    mp1->b_datap->db_base;
6901 					freeb(mp1);
6902 					BUMP_MIB(ill->ill_ip_mib,
6903 					    ipIfStatsReasmPartDups);
6904 					mp1 = mp->b_cont;
6905 					if (!mp1)
6906 						break;
6907 					offset = IP_REASS_START(mp1);
6908 				}
6909 			}
6910 			break;
6911 		}
6912 	} while (start = end, mp = next_mp);
6913 
6914 	/* Fragment just processed could be the last one. Remember this fact */
6915 	if (!more)
6916 		ipf->ipf_last_frag_seen = B_TRUE;
6917 
6918 	/* Still got holes? */
6919 	if (ipf->ipf_hole_cnt)
6920 		return (IP_REASS_PARTIAL);
6921 	/* Clean up overloaded fields to avoid upstream disasters. */
6922 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6923 		IP_REASS_SET_START(mp1, 0);
6924 		IP_REASS_SET_END(mp1, 0);
6925 	}
6926 	return (IP_REASS_COMPLETE);
6927 }
6928 
6929 /*
6930  * Fragmentation reassembly.  Each ILL has a hash table for
6931  * queuing packets undergoing reassembly for all IPIFs
6932  * associated with the ILL.  The hash is based on the packet
6933  * IP ident field.  The ILL frag hash table was allocated
6934  * as a timer block at the time the ILL was created.  Whenever
6935  * there is anything on the reassembly queue, the timer will
6936  * be running.  Returns the reassembled packet if reassembly completes.
6937  */
6938 mblk_t *
6939 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
6940 {
6941 	uint32_t	frag_offset_flags;
6942 	mblk_t		*t_mp;
6943 	ipaddr_t	dst;
6944 	uint8_t		proto = ipha->ipha_protocol;
6945 	uint32_t	sum_val;
6946 	uint16_t	sum_flags;
6947 	ipf_t		*ipf;
6948 	ipf_t		**ipfp;
6949 	ipfb_t		*ipfb;
6950 	uint16_t	ident;
6951 	uint32_t	offset;
6952 	ipaddr_t	src;
6953 	uint_t		hdr_length;
6954 	uint32_t	end;
6955 	mblk_t		*mp1;
6956 	mblk_t		*tail_mp;
6957 	size_t		count;
6958 	size_t		msg_len;
6959 	uint8_t		ecn_info = 0;
6960 	uint32_t	packet_size;
6961 	boolean_t	pruned = B_FALSE;
6962 	ill_t		*ill = ira->ira_ill;
6963 	ip_stack_t	*ipst = ill->ill_ipst;
6964 
6965 	/*
6966 	 * Drop the fragmented as early as possible, if
6967 	 * we don't have resource(s) to re-assemble.
6968 	 */
6969 	if (ipst->ips_ip_reass_queue_bytes == 0) {
6970 		freemsg(mp);
6971 		return (NULL);
6972 	}
6973 
6974 	/* Check for fragmentation offset; return if there's none */
6975 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
6976 	    (IPH_MF | IPH_OFFSET)) == 0)
6977 		return (mp);
6978 
6979 	/*
6980 	 * We utilize hardware computed checksum info only for UDP since
6981 	 * IP fragmentation is a normal occurrence for the protocol.  In
6982 	 * addition, checksum offload support for IP fragments carrying
6983 	 * UDP payload is commonly implemented across network adapters.
6984 	 */
6985 	ASSERT(ira->ira_rill != NULL);
6986 	if (proto == IPPROTO_UDP && dohwcksum &&
6987 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
6988 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
6989 		mblk_t *mp1 = mp->b_cont;
6990 		int32_t len;
6991 
6992 		/* Record checksum information from the packet */
6993 		sum_val = (uint32_t)DB_CKSUM16(mp);
6994 		sum_flags = DB_CKSUMFLAGS(mp);
6995 
6996 		/* IP payload offset from beginning of mblk */
6997 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
6998 
6999 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7000 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7001 		    offset >= DB_CKSUMSTART(mp) &&
7002 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7003 			uint32_t adj;
7004 			/*
7005 			 * Partial checksum has been calculated by hardware
7006 			 * and attached to the packet; in addition, any
7007 			 * prepended extraneous data is even byte aligned.
7008 			 * If any such data exists, we adjust the checksum;
7009 			 * this would also handle any postpended data.
7010 			 */
7011 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7012 			    mp, mp1, len, adj);
7013 
7014 			/* One's complement subtract extraneous checksum */
7015 			if (adj >= sum_val)
7016 				sum_val = ~(adj - sum_val) & 0xFFFF;
7017 			else
7018 				sum_val -= adj;
7019 		}
7020 	} else {
7021 		sum_val = 0;
7022 		sum_flags = 0;
7023 	}
7024 
7025 	/* Clear hardware checksumming flag */
7026 	DB_CKSUMFLAGS(mp) = 0;
7027 
7028 	ident = ipha->ipha_ident;
7029 	offset = (frag_offset_flags << 3) & 0xFFFF;
7030 	src = ipha->ipha_src;
7031 	dst = ipha->ipha_dst;
7032 	hdr_length = IPH_HDR_LENGTH(ipha);
7033 	end = ntohs(ipha->ipha_length) - hdr_length;
7034 
7035 	/* If end == 0 then we have a packet with no data, so just free it */
7036 	if (end == 0) {
7037 		freemsg(mp);
7038 		return (NULL);
7039 	}
7040 
7041 	/* Record the ECN field info. */
7042 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7043 	if (offset != 0) {
7044 		/*
7045 		 * If this isn't the first piece, strip the header, and
7046 		 * add the offset to the end value.
7047 		 */
7048 		mp->b_rptr += hdr_length;
7049 		end += offset;
7050 	}
7051 
7052 	/* Handle vnic loopback of fragments */
7053 	if (mp->b_datap->db_ref > 2)
7054 		msg_len = 0;
7055 	else
7056 		msg_len = MBLKSIZE(mp);
7057 
7058 	tail_mp = mp;
7059 	while (tail_mp->b_cont != NULL) {
7060 		tail_mp = tail_mp->b_cont;
7061 		if (tail_mp->b_datap->db_ref <= 2)
7062 			msg_len += MBLKSIZE(tail_mp);
7063 	}
7064 
7065 	/* If the reassembly list for this ILL will get too big, prune it */
7066 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7067 	    ipst->ips_ip_reass_queue_bytes) {
7068 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7069 		    uint_t, ill->ill_frag_count,
7070 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7071 		ill_frag_prune(ill,
7072 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7073 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7074 		pruned = B_TRUE;
7075 	}
7076 
7077 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7078 	mutex_enter(&ipfb->ipfb_lock);
7079 
7080 	ipfp = &ipfb->ipfb_ipf;
7081 	/* Try to find an existing fragment queue for this packet. */
7082 	for (;;) {
7083 		ipf = ipfp[0];
7084 		if (ipf != NULL) {
7085 			/*
7086 			 * It has to match on ident and src/dst address.
7087 			 */
7088 			if (ipf->ipf_ident == ident &&
7089 			    ipf->ipf_src == src &&
7090 			    ipf->ipf_dst == dst &&
7091 			    ipf->ipf_protocol == proto) {
7092 				/*
7093 				 * If we have received too many
7094 				 * duplicate fragments for this packet
7095 				 * free it.
7096 				 */
7097 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7098 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7099 					freemsg(mp);
7100 					mutex_exit(&ipfb->ipfb_lock);
7101 					return (NULL);
7102 				}
7103 				/* Found it. */
7104 				break;
7105 			}
7106 			ipfp = &ipf->ipf_hash_next;
7107 			continue;
7108 		}
7109 
7110 		/*
7111 		 * If we pruned the list, do we want to store this new
7112 		 * fragment?. We apply an optimization here based on the
7113 		 * fact that most fragments will be received in order.
7114 		 * So if the offset of this incoming fragment is zero,
7115 		 * it is the first fragment of a new packet. We will
7116 		 * keep it.  Otherwise drop the fragment, as we have
7117 		 * probably pruned the packet already (since the
7118 		 * packet cannot be found).
7119 		 */
7120 		if (pruned && offset != 0) {
7121 			mutex_exit(&ipfb->ipfb_lock);
7122 			freemsg(mp);
7123 			return (NULL);
7124 		}
7125 
7126 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7127 			/*
7128 			 * Too many fragmented packets in this hash
7129 			 * bucket. Free the oldest.
7130 			 */
7131 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7132 		}
7133 
7134 		/* New guy.  Allocate a frag message. */
7135 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7136 		if (mp1 == NULL) {
7137 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7138 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7139 			freemsg(mp);
7140 reass_done:
7141 			mutex_exit(&ipfb->ipfb_lock);
7142 			return (NULL);
7143 		}
7144 
7145 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7146 		mp1->b_cont = mp;
7147 
7148 		/* Initialize the fragment header. */
7149 		ipf = (ipf_t *)mp1->b_rptr;
7150 		ipf->ipf_mp = mp1;
7151 		ipf->ipf_ptphn = ipfp;
7152 		ipfp[0] = ipf;
7153 		ipf->ipf_hash_next = NULL;
7154 		ipf->ipf_ident = ident;
7155 		ipf->ipf_protocol = proto;
7156 		ipf->ipf_src = src;
7157 		ipf->ipf_dst = dst;
7158 		ipf->ipf_nf_hdr_len = 0;
7159 		/* Record reassembly start time. */
7160 		ipf->ipf_timestamp = gethrestime_sec();
7161 		/* Record ipf generation and account for frag header */
7162 		ipf->ipf_gen = ill->ill_ipf_gen++;
7163 		ipf->ipf_count = MBLKSIZE(mp1);
7164 		ipf->ipf_last_frag_seen = B_FALSE;
7165 		ipf->ipf_ecn = ecn_info;
7166 		ipf->ipf_num_dups = 0;
7167 		ipfb->ipfb_frag_pkts++;
7168 		ipf->ipf_checksum = 0;
7169 		ipf->ipf_checksum_flags = 0;
7170 
7171 		/* Store checksum value in fragment header */
7172 		if (sum_flags != 0) {
7173 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7174 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7175 			ipf->ipf_checksum = sum_val;
7176 			ipf->ipf_checksum_flags = sum_flags;
7177 		}
7178 
7179 		/*
7180 		 * We handle reassembly two ways.  In the easy case,
7181 		 * where all the fragments show up in order, we do
7182 		 * minimal bookkeeping, and just clip new pieces on
7183 		 * the end.  If we ever see a hole, then we go off
7184 		 * to ip_reassemble which has to mark the pieces and
7185 		 * keep track of the number of holes, etc.  Obviously,
7186 		 * the point of having both mechanisms is so we can
7187 		 * handle the easy case as efficiently as possible.
7188 		 */
7189 		if (offset == 0) {
7190 			/* Easy case, in-order reassembly so far. */
7191 			ipf->ipf_count += msg_len;
7192 			ipf->ipf_tail_mp = tail_mp;
7193 			/*
7194 			 * Keep track of next expected offset in
7195 			 * ipf_end.
7196 			 */
7197 			ipf->ipf_end = end;
7198 			ipf->ipf_nf_hdr_len = hdr_length;
7199 		} else {
7200 			/* Hard case, hole at the beginning. */
7201 			ipf->ipf_tail_mp = NULL;
7202 			/*
7203 			 * ipf_end == 0 means that we have given up
7204 			 * on easy reassembly.
7205 			 */
7206 			ipf->ipf_end = 0;
7207 
7208 			/* Forget checksum offload from now on */
7209 			ipf->ipf_checksum_flags = 0;
7210 
7211 			/*
7212 			 * ipf_hole_cnt is set by ip_reassemble.
7213 			 * ipf_count is updated by ip_reassemble.
7214 			 * No need to check for return value here
7215 			 * as we don't expect reassembly to complete
7216 			 * or fail for the first fragment itself.
7217 			 */
7218 			(void) ip_reassemble(mp, ipf,
7219 			    (frag_offset_flags & IPH_OFFSET) << 3,
7220 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7221 		}
7222 		/* Update per ipfb and ill byte counts */
7223 		ipfb->ipfb_count += ipf->ipf_count;
7224 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7225 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7226 		/* If the frag timer wasn't already going, start it. */
7227 		mutex_enter(&ill->ill_lock);
7228 		ill_frag_timer_start(ill);
7229 		mutex_exit(&ill->ill_lock);
7230 		goto reass_done;
7231 	}
7232 
7233 	/*
7234 	 * If the packet's flag has changed (it could be coming up
7235 	 * from an interface different than the previous, therefore
7236 	 * possibly different checksum capability), then forget about
7237 	 * any stored checksum states.  Otherwise add the value to
7238 	 * the existing one stored in the fragment header.
7239 	 */
7240 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7241 		sum_val += ipf->ipf_checksum;
7242 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7243 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7244 		ipf->ipf_checksum = sum_val;
7245 	} else if (ipf->ipf_checksum_flags != 0) {
7246 		/* Forget checksum offload from now on */
7247 		ipf->ipf_checksum_flags = 0;
7248 	}
7249 
7250 	/*
7251 	 * We have a new piece of a datagram which is already being
7252 	 * reassembled.  Update the ECN info if all IP fragments
7253 	 * are ECN capable.  If there is one which is not, clear
7254 	 * all the info.  If there is at least one which has CE
7255 	 * code point, IP needs to report that up to transport.
7256 	 */
7257 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7258 		if (ecn_info == IPH_ECN_CE)
7259 			ipf->ipf_ecn = IPH_ECN_CE;
7260 	} else {
7261 		ipf->ipf_ecn = IPH_ECN_NECT;
7262 	}
7263 	if (offset && ipf->ipf_end == offset) {
7264 		/* The new fragment fits at the end */
7265 		ipf->ipf_tail_mp->b_cont = mp;
7266 		/* Update the byte count */
7267 		ipf->ipf_count += msg_len;
7268 		/* Update per ipfb and ill byte counts */
7269 		ipfb->ipfb_count += msg_len;
7270 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7271 		atomic_add_32(&ill->ill_frag_count, msg_len);
7272 		if (frag_offset_flags & IPH_MF) {
7273 			/* More to come. */
7274 			ipf->ipf_end = end;
7275 			ipf->ipf_tail_mp = tail_mp;
7276 			goto reass_done;
7277 		}
7278 	} else {
7279 		/* Go do the hard cases. */
7280 		int ret;
7281 
7282 		if (offset == 0)
7283 			ipf->ipf_nf_hdr_len = hdr_length;
7284 
7285 		/* Save current byte count */
7286 		count = ipf->ipf_count;
7287 		ret = ip_reassemble(mp, ipf,
7288 		    (frag_offset_flags & IPH_OFFSET) << 3,
7289 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7290 		/* Count of bytes added and subtracted (freeb()ed) */
7291 		count = ipf->ipf_count - count;
7292 		if (count) {
7293 			/* Update per ipfb and ill byte counts */
7294 			ipfb->ipfb_count += count;
7295 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7296 			atomic_add_32(&ill->ill_frag_count, count);
7297 		}
7298 		if (ret == IP_REASS_PARTIAL) {
7299 			goto reass_done;
7300 		} else if (ret == IP_REASS_FAILED) {
7301 			/* Reassembly failed. Free up all resources */
7302 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7303 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7304 				IP_REASS_SET_START(t_mp, 0);
7305 				IP_REASS_SET_END(t_mp, 0);
7306 			}
7307 			freemsg(mp);
7308 			goto reass_done;
7309 		}
7310 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7311 	}
7312 	/*
7313 	 * We have completed reassembly.  Unhook the frag header from
7314 	 * the reassembly list.
7315 	 *
7316 	 * Before we free the frag header, record the ECN info
7317 	 * to report back to the transport.
7318 	 */
7319 	ecn_info = ipf->ipf_ecn;
7320 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7321 	ipfp = ipf->ipf_ptphn;
7322 
7323 	/* We need to supply these to caller */
7324 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7325 		sum_val = ipf->ipf_checksum;
7326 	else
7327 		sum_val = 0;
7328 
7329 	mp1 = ipf->ipf_mp;
7330 	count = ipf->ipf_count;
7331 	ipf = ipf->ipf_hash_next;
7332 	if (ipf != NULL)
7333 		ipf->ipf_ptphn = ipfp;
7334 	ipfp[0] = ipf;
7335 	atomic_add_32(&ill->ill_frag_count, -count);
7336 	ASSERT(ipfb->ipfb_count >= count);
7337 	ipfb->ipfb_count -= count;
7338 	ipfb->ipfb_frag_pkts--;
7339 	mutex_exit(&ipfb->ipfb_lock);
7340 	/* Ditch the frag header. */
7341 	mp = mp1->b_cont;
7342 
7343 	freeb(mp1);
7344 
7345 	/* Restore original IP length in header. */
7346 	packet_size = (uint32_t)msgdsize(mp);
7347 	if (packet_size > IP_MAXPACKET) {
7348 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7349 		ip_drop_input("Reassembled packet too large", mp, ill);
7350 		freemsg(mp);
7351 		return (NULL);
7352 	}
7353 
7354 	if (DB_REF(mp) > 1) {
7355 		mblk_t *mp2 = copymsg(mp);
7356 
7357 		if (mp2 == NULL) {
7358 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7359 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7360 			freemsg(mp);
7361 			return (NULL);
7362 		}
7363 		freemsg(mp);
7364 		mp = mp2;
7365 	}
7366 	ipha = (ipha_t *)mp->b_rptr;
7367 
7368 	ipha->ipha_length = htons((uint16_t)packet_size);
7369 	/* We're now complete, zip the frag state */
7370 	ipha->ipha_fragment_offset_and_flags = 0;
7371 	/* Record the ECN info. */
7372 	ipha->ipha_type_of_service &= 0xFC;
7373 	ipha->ipha_type_of_service |= ecn_info;
7374 
7375 	/* Update the receive attributes */
7376 	ira->ira_pktlen = packet_size;
7377 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7378 
7379 	/* Reassembly is successful; set checksum information in packet */
7380 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7381 	DB_CKSUMFLAGS(mp) = sum_flags;
7382 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7383 
7384 	return (mp);
7385 }
7386 
7387 /*
7388  * Pullup function that should be used for IP input in order to
7389  * ensure we do not loose the L2 source address; we need the l2 source
7390  * address for IP_RECVSLLA and for ndp_input.
7391  *
7392  * We return either NULL or b_rptr.
7393  */
7394 void *
7395 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7396 {
7397 	ill_t		*ill = ira->ira_ill;
7398 
7399 	if (ip_rput_pullups++ == 0) {
7400 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7401 		    "ip_pullup: %s forced us to "
7402 		    " pullup pkt, hdr len %ld, hdr addr %p",
7403 		    ill->ill_name, len, (void *)mp->b_rptr);
7404 	}
7405 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7406 		ip_setl2src(mp, ira, ira->ira_rill);
7407 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7408 	if (!pullupmsg(mp, len))
7409 		return (NULL);
7410 	else
7411 		return (mp->b_rptr);
7412 }
7413 
7414 /*
7415  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7416  * When called from the ULP ira_rill will be NULL hence the caller has to
7417  * pass in the ill.
7418  */
7419 /* ARGSUSED */
7420 void
7421 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7422 {
7423 	const uchar_t *addr;
7424 	int alen;
7425 
7426 	if (ira->ira_flags & IRAF_L2SRC_SET)
7427 		return;
7428 
7429 	ASSERT(ill != NULL);
7430 	alen = ill->ill_phys_addr_length;
7431 	ASSERT(alen <= sizeof (ira->ira_l2src));
7432 	if (ira->ira_mhip != NULL &&
7433 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7434 		bcopy(addr, ira->ira_l2src, alen);
7435 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7436 	    (addr = ill->ill_phys_addr) != NULL) {
7437 		bcopy(addr, ira->ira_l2src, alen);
7438 	} else {
7439 		bzero(ira->ira_l2src, alen);
7440 	}
7441 	ira->ira_flags |= IRAF_L2SRC_SET;
7442 }
7443 
7444 /*
7445  * check ip header length and align it.
7446  */
7447 mblk_t *
7448 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7449 {
7450 	ill_t	*ill = ira->ira_ill;
7451 	ssize_t len;
7452 
7453 	len = MBLKL(mp);
7454 
7455 	if (!OK_32PTR(mp->b_rptr))
7456 		IP_STAT(ill->ill_ipst, ip_notaligned);
7457 	else
7458 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7459 
7460 	/* Guard against bogus device drivers */
7461 	if (len < 0) {
7462 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7463 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7464 		freemsg(mp);
7465 		return (NULL);
7466 	}
7467 
7468 	if (len == 0) {
7469 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7470 		mblk_t *mp1 = mp->b_cont;
7471 
7472 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7473 			ip_setl2src(mp, ira, ira->ira_rill);
7474 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7475 
7476 		freeb(mp);
7477 		mp = mp1;
7478 		if (mp == NULL)
7479 			return (NULL);
7480 
7481 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7482 			return (mp);
7483 	}
7484 	if (ip_pullup(mp, min_size, ira) == NULL) {
7485 		if (msgdsize(mp) < min_size) {
7486 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7487 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7488 		} else {
7489 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7490 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7491 		}
7492 		freemsg(mp);
7493 		return (NULL);
7494 	}
7495 	return (mp);
7496 }
7497 
7498 /*
7499  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7500  */
7501 mblk_t *
7502 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7503     uint_t min_size, ip_recv_attr_t *ira)
7504 {
7505 	ill_t	*ill = ira->ira_ill;
7506 
7507 	/*
7508 	 * Make sure we have data length consistent
7509 	 * with the IP header.
7510 	 */
7511 	if (mp->b_cont == NULL) {
7512 		/* pkt_len is based on ipha_len, not the mblk length */
7513 		if (pkt_len < min_size) {
7514 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7515 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7516 			freemsg(mp);
7517 			return (NULL);
7518 		}
7519 		if (len < 0) {
7520 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7521 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7522 			freemsg(mp);
7523 			return (NULL);
7524 		}
7525 		/* Drop any pad */
7526 		mp->b_wptr = rptr + pkt_len;
7527 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7528 		ASSERT(pkt_len >= min_size);
7529 		if (pkt_len < min_size) {
7530 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7531 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7532 			freemsg(mp);
7533 			return (NULL);
7534 		}
7535 		if (len < 0) {
7536 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7537 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7538 			freemsg(mp);
7539 			return (NULL);
7540 		}
7541 		/* Drop any pad */
7542 		(void) adjmsg(mp, -len);
7543 		/*
7544 		 * adjmsg may have freed an mblk from the chain, hence
7545 		 * invalidate any hw checksum here. This will force IP to
7546 		 * calculate the checksum in sw, but only for this packet.
7547 		 */
7548 		DB_CKSUMFLAGS(mp) = 0;
7549 		IP_STAT(ill->ill_ipst, ip_multimblk);
7550 	}
7551 	return (mp);
7552 }
7553 
7554 /*
7555  * Check that the IPv4 opt_len is consistent with the packet and pullup
7556  * the options.
7557  */
7558 mblk_t *
7559 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7560     ip_recv_attr_t *ira)
7561 {
7562 	ill_t	*ill = ira->ira_ill;
7563 	ssize_t len;
7564 
7565 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7566 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7567 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7568 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7569 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7570 		freemsg(mp);
7571 		return (NULL);
7572 	}
7573 
7574 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7575 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7576 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7577 		freemsg(mp);
7578 		return (NULL);
7579 	}
7580 	/*
7581 	 * Recompute complete header length and make sure we
7582 	 * have access to all of it.
7583 	 */
7584 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7585 	if (len > (mp->b_wptr - mp->b_rptr)) {
7586 		if (len > pkt_len) {
7587 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7588 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7589 			freemsg(mp);
7590 			return (NULL);
7591 		}
7592 		if (ip_pullup(mp, len, ira) == NULL) {
7593 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7594 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7595 			freemsg(mp);
7596 			return (NULL);
7597 		}
7598 	}
7599 	return (mp);
7600 }
7601 
7602 /*
7603  * Returns a new ire, or the same ire, or NULL.
7604  * If a different IRE is returned, then it is held; the caller
7605  * needs to release it.
7606  * In no case is there any hold/release on the ire argument.
7607  */
7608 ire_t *
7609 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7610 {
7611 	ire_t		*new_ire;
7612 	ill_t		*ire_ill;
7613 	uint_t		ifindex;
7614 	ip_stack_t	*ipst = ill->ill_ipst;
7615 	boolean_t	strict_check = B_FALSE;
7616 
7617 	/*
7618 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7619 	 * issue (e.g. packet received on an underlying interface matched an
7620 	 * IRE_LOCAL on its associated group interface).
7621 	 */
7622 	ASSERT(ire->ire_ill != NULL);
7623 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7624 		return (ire);
7625 
7626 	/*
7627 	 * Do another ire lookup here, using the ingress ill, to see if the
7628 	 * interface is in a usesrc group.
7629 	 * As long as the ills belong to the same group, we don't consider
7630 	 * them to be arriving on the wrong interface. Thus, if the switch
7631 	 * is doing inbound load spreading, we won't drop packets when the
7632 	 * ip*_strict_dst_multihoming switch is on.
7633 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7634 	 * where the local address may not be unique. In this case we were
7635 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7636 	 * actually returned. The new lookup, which is more specific, should
7637 	 * only find the IRE_LOCAL associated with the ingress ill if one
7638 	 * exists.
7639 	 */
7640 	if (ire->ire_ipversion == IPV4_VERSION) {
7641 		if (ipst->ips_ip_strict_dst_multihoming)
7642 			strict_check = B_TRUE;
7643 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7644 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7645 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7646 	} else {
7647 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7648 		if (ipst->ips_ipv6_strict_dst_multihoming)
7649 			strict_check = B_TRUE;
7650 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7651 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7652 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7653 	}
7654 	/*
7655 	 * If the same ire that was returned in ip_input() is found then this
7656 	 * is an indication that usesrc groups are in use. The packet
7657 	 * arrived on a different ill in the group than the one associated with
7658 	 * the destination address.  If a different ire was found then the same
7659 	 * IP address must be hosted on multiple ills. This is possible with
7660 	 * unnumbered point2point interfaces. We switch to use this new ire in
7661 	 * order to have accurate interface statistics.
7662 	 */
7663 	if (new_ire != NULL) {
7664 		/* Note: held in one case but not the other? Caller handles */
7665 		if (new_ire != ire)
7666 			return (new_ire);
7667 		/* Unchanged */
7668 		ire_refrele(new_ire);
7669 		return (ire);
7670 	}
7671 
7672 	/*
7673 	 * Chase pointers once and store locally.
7674 	 */
7675 	ASSERT(ire->ire_ill != NULL);
7676 	ire_ill = ire->ire_ill;
7677 	ifindex = ill->ill_usesrc_ifindex;
7678 
7679 	/*
7680 	 * Check if it's a legal address on the 'usesrc' interface.
7681 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7682 	 * can just check phyint_ifindex.
7683 	 */
7684 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7685 		return (ire);
7686 	}
7687 
7688 	/*
7689 	 * If the ip*_strict_dst_multihoming switch is on then we can
7690 	 * only accept this packet if the interface is marked as routing.
7691 	 */
7692 	if (!(strict_check))
7693 		return (ire);
7694 
7695 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7696 		return (ire);
7697 	}
7698 	return (NULL);
7699 }
7700 
7701 /*
7702  * This function is used to construct a mac_header_info_s from a
7703  * DL_UNITDATA_IND message.
7704  * The address fields in the mhi structure points into the message,
7705  * thus the caller can't use those fields after freeing the message.
7706  *
7707  * We determine whether the packet received is a non-unicast packet
7708  * and in doing so, determine whether or not it is broadcast vs multicast.
7709  * For it to be a broadcast packet, we must have the appropriate mblk_t
7710  * hanging off the ill_t.  If this is either not present or doesn't match
7711  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7712  * to be multicast.  Thus NICs that have no broadcast address (or no
7713  * capability for one, such as point to point links) cannot return as
7714  * the packet being broadcast.
7715  */
7716 void
7717 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7718 {
7719 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7720 	mblk_t *bmp;
7721 	uint_t extra_offset;
7722 
7723 	bzero(mhip, sizeof (struct mac_header_info_s));
7724 
7725 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7726 
7727 	if (ill->ill_sap_length < 0)
7728 		extra_offset = 0;
7729 	else
7730 		extra_offset = ill->ill_sap_length;
7731 
7732 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7733 	    extra_offset;
7734 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7735 	    extra_offset;
7736 
7737 	if (!ind->dl_group_address)
7738 		return;
7739 
7740 	/* Multicast or broadcast */
7741 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7742 
7743 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7744 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7745 	    (bmp = ill->ill_bcast_mp) != NULL) {
7746 		dl_unitdata_req_t *dlur;
7747 		uint8_t *bphys_addr;
7748 
7749 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7750 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7751 		    extra_offset;
7752 
7753 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7754 		    ind->dl_dest_addr_length) == 0)
7755 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7756 	}
7757 }
7758 
7759 /*
7760  * This function is used to construct a mac_header_info_s from a
7761  * M_DATA fastpath message from a DLPI driver.
7762  * The address fields in the mhi structure points into the message,
7763  * thus the caller can't use those fields after freeing the message.
7764  *
7765  * We determine whether the packet received is a non-unicast packet
7766  * and in doing so, determine whether or not it is broadcast vs multicast.
7767  * For it to be a broadcast packet, we must have the appropriate mblk_t
7768  * hanging off the ill_t.  If this is either not present or doesn't match
7769  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7770  * to be multicast.  Thus NICs that have no broadcast address (or no
7771  * capability for one, such as point to point links) cannot return as
7772  * the packet being broadcast.
7773  */
7774 void
7775 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7776 {
7777 	mblk_t *bmp;
7778 	struct ether_header *pether;
7779 
7780 	bzero(mhip, sizeof (struct mac_header_info_s));
7781 
7782 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7783 
7784 	pether = (struct ether_header *)((char *)mp->b_rptr
7785 	    - sizeof (struct ether_header));
7786 
7787 	/*
7788 	 * Make sure the interface is an ethernet type, since we don't
7789 	 * know the header format for anything but Ethernet. Also make
7790 	 * sure we are pointing correctly above db_base.
7791 	 */
7792 	if (ill->ill_type != IFT_ETHER)
7793 		return;
7794 
7795 retry:
7796 	if ((uchar_t *)pether < mp->b_datap->db_base)
7797 		return;
7798 
7799 	/* Is there a VLAN tag? */
7800 	if (ill->ill_isv6) {
7801 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7802 			pether = (struct ether_header *)((char *)pether - 4);
7803 			goto retry;
7804 		}
7805 	} else {
7806 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7807 			pether = (struct ether_header *)((char *)pether - 4);
7808 			goto retry;
7809 		}
7810 	}
7811 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7812 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7813 
7814 	if (!(mhip->mhi_daddr[0] & 0x01))
7815 		return;
7816 
7817 	/* Multicast or broadcast */
7818 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7819 
7820 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7821 		dl_unitdata_req_t *dlur;
7822 		uint8_t *bphys_addr;
7823 		uint_t	addrlen;
7824 
7825 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7826 		addrlen = dlur->dl_dest_addr_length;
7827 		if (ill->ill_sap_length < 0) {
7828 			bphys_addr = (uchar_t *)dlur +
7829 			    dlur->dl_dest_addr_offset;
7830 			addrlen += ill->ill_sap_length;
7831 		} else {
7832 			bphys_addr = (uchar_t *)dlur +
7833 			    dlur->dl_dest_addr_offset +
7834 			    ill->ill_sap_length;
7835 			addrlen -= ill->ill_sap_length;
7836 		}
7837 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7838 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7839 	}
7840 }
7841 
7842 /*
7843  * Handle anything but M_DATA messages
7844  * We see the DL_UNITDATA_IND which are part
7845  * of the data path, and also the other messages from the driver.
7846  */
7847 void
7848 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7849 {
7850 	mblk_t		*first_mp;
7851 	struct iocblk   *iocp;
7852 	struct mac_header_info_s mhi;
7853 
7854 	switch (DB_TYPE(mp)) {
7855 	case M_PROTO:
7856 	case M_PCPROTO: {
7857 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7858 		    DL_UNITDATA_IND) {
7859 			/* Go handle anything other than data elsewhere. */
7860 			ip_rput_dlpi(ill, mp);
7861 			return;
7862 		}
7863 
7864 		first_mp = mp;
7865 		mp = first_mp->b_cont;
7866 		first_mp->b_cont = NULL;
7867 
7868 		if (mp == NULL) {
7869 			freeb(first_mp);
7870 			return;
7871 		}
7872 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7873 		if (ill->ill_isv6)
7874 			ip_input_v6(ill, NULL, mp, &mhi);
7875 		else
7876 			ip_input(ill, NULL, mp, &mhi);
7877 
7878 		/* Ditch the DLPI header. */
7879 		freeb(first_mp);
7880 		return;
7881 	}
7882 	case M_IOCACK:
7883 		iocp = (struct iocblk *)mp->b_rptr;
7884 		switch (iocp->ioc_cmd) {
7885 		case DL_IOC_HDR_INFO:
7886 			ill_fastpath_ack(ill, mp);
7887 			return;
7888 		default:
7889 			putnext(ill->ill_rq, mp);
7890 			return;
7891 		}
7892 		/* FALLTHRU */
7893 	case M_ERROR:
7894 	case M_HANGUP:
7895 		mutex_enter(&ill->ill_lock);
7896 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7897 			mutex_exit(&ill->ill_lock);
7898 			freemsg(mp);
7899 			return;
7900 		}
7901 		ill_refhold_locked(ill);
7902 		mutex_exit(&ill->ill_lock);
7903 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7904 		    B_FALSE);
7905 		return;
7906 	case M_CTL:
7907 		putnext(ill->ill_rq, mp);
7908 		return;
7909 	case M_IOCNAK:
7910 		ip1dbg(("got iocnak "));
7911 		iocp = (struct iocblk *)mp->b_rptr;
7912 		switch (iocp->ioc_cmd) {
7913 		case DL_IOC_HDR_INFO:
7914 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7915 			return;
7916 		default:
7917 			break;
7918 		}
7919 		/* FALLTHRU */
7920 	default:
7921 		putnext(ill->ill_rq, mp);
7922 		return;
7923 	}
7924 }
7925 
7926 /* Read side put procedure.  Packets coming from the wire arrive here. */
7927 void
7928 ip_rput(queue_t *q, mblk_t *mp)
7929 {
7930 	ill_t	*ill;
7931 	union DL_primitives *dl;
7932 
7933 	ill = (ill_t *)q->q_ptr;
7934 
7935 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
7936 		/*
7937 		 * If things are opening or closing, only accept high-priority
7938 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
7939 		 * created; on close, things hanging off the ill may have been
7940 		 * freed already.)
7941 		 */
7942 		dl = (union DL_primitives *)mp->b_rptr;
7943 		if (DB_TYPE(mp) != M_PCPROTO ||
7944 		    dl->dl_primitive == DL_UNITDATA_IND) {
7945 			inet_freemsg(mp);
7946 			return;
7947 		}
7948 	}
7949 	if (DB_TYPE(mp) == M_DATA) {
7950 		struct mac_header_info_s mhi;
7951 
7952 		ip_mdata_to_mhi(ill, mp, &mhi);
7953 		ip_input(ill, NULL, mp, &mhi);
7954 	} else {
7955 		ip_rput_notdata(ill, mp);
7956 	}
7957 }
7958 
7959 /*
7960  * Move the information to a copy.
7961  */
7962 mblk_t *
7963 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
7964 {
7965 	mblk_t		*mp1;
7966 	ill_t		*ill = ira->ira_ill;
7967 	ip_stack_t	*ipst = ill->ill_ipst;
7968 
7969 	IP_STAT(ipst, ip_db_ref);
7970 
7971 	/* Make sure we have ira_l2src before we loose the original mblk */
7972 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7973 		ip_setl2src(mp, ira, ira->ira_rill);
7974 
7975 	mp1 = copymsg(mp);
7976 	if (mp1 == NULL) {
7977 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7978 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
7979 		freemsg(mp);
7980 		return (NULL);
7981 	}
7982 	/* preserve the hardware checksum flags and data, if present */
7983 	if (DB_CKSUMFLAGS(mp) != 0) {
7984 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
7985 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
7986 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
7987 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
7988 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
7989 	}
7990 	freemsg(mp);
7991 	return (mp1);
7992 }
7993 
7994 static void
7995 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
7996     t_uscalar_t err)
7997 {
7998 	if (dl_err == DL_SYSERR) {
7999 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8000 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8001 		    ill->ill_name, dl_primstr(prim), err);
8002 		return;
8003 	}
8004 
8005 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8006 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8007 	    dl_errstr(dl_err));
8008 }
8009 
8010 /*
8011  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8012  * than DL_UNITDATA_IND messages. If we need to process this message
8013  * exclusively, we call qwriter_ip, in which case we also need to call
8014  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8015  */
8016 void
8017 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8018 {
8019 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8020 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8021 	queue_t		*q = ill->ill_rq;
8022 	t_uscalar_t	prim = dloa->dl_primitive;
8023 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8024 
8025 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8026 	    char *, dl_primstr(prim), ill_t *, ill);
8027 	ip1dbg(("ip_rput_dlpi"));
8028 
8029 	/*
8030 	 * If we received an ACK but didn't send a request for it, then it
8031 	 * can't be part of any pending operation; discard up-front.
8032 	 */
8033 	switch (prim) {
8034 	case DL_ERROR_ACK:
8035 		reqprim = dlea->dl_error_primitive;
8036 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8037 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8038 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8039 		    dlea->dl_unix_errno));
8040 		break;
8041 	case DL_OK_ACK:
8042 		reqprim = dloa->dl_correct_primitive;
8043 		break;
8044 	case DL_INFO_ACK:
8045 		reqprim = DL_INFO_REQ;
8046 		break;
8047 	case DL_BIND_ACK:
8048 		reqprim = DL_BIND_REQ;
8049 		break;
8050 	case DL_PHYS_ADDR_ACK:
8051 		reqprim = DL_PHYS_ADDR_REQ;
8052 		break;
8053 	case DL_NOTIFY_ACK:
8054 		reqprim = DL_NOTIFY_REQ;
8055 		break;
8056 	case DL_CAPABILITY_ACK:
8057 		reqprim = DL_CAPABILITY_REQ;
8058 		break;
8059 	}
8060 
8061 	if (prim != DL_NOTIFY_IND) {
8062 		if (reqprim == DL_PRIM_INVAL ||
8063 		    !ill_dlpi_pending(ill, reqprim)) {
8064 			/* Not a DLPI message we support or expected */
8065 			freemsg(mp);
8066 			return;
8067 		}
8068 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8069 		    dl_primstr(reqprim)));
8070 	}
8071 
8072 	switch (reqprim) {
8073 	case DL_UNBIND_REQ:
8074 		/*
8075 		 * NOTE: we mark the unbind as complete even if we got a
8076 		 * DL_ERROR_ACK, since there's not much else we can do.
8077 		 */
8078 		mutex_enter(&ill->ill_lock);
8079 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8080 		cv_signal(&ill->ill_cv);
8081 		mutex_exit(&ill->ill_lock);
8082 		break;
8083 
8084 	case DL_ENABMULTI_REQ:
8085 		if (prim == DL_OK_ACK) {
8086 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8087 				ill->ill_dlpi_multicast_state = IDS_OK;
8088 		}
8089 		break;
8090 	}
8091 
8092 	/*
8093 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8094 	 * need to become writer to continue to process it.  Because an
8095 	 * exclusive operation doesn't complete until replies to all queued
8096 	 * DLPI messages have been received, we know we're in the middle of an
8097 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8098 	 *
8099 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8100 	 * Since this is on the ill stream we unconditionally bump up the
8101 	 * refcount without doing ILL_CAN_LOOKUP().
8102 	 */
8103 	ill_refhold(ill);
8104 	if (prim == DL_NOTIFY_IND)
8105 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8106 	else
8107 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8108 }
8109 
8110 /*
8111  * Handling of DLPI messages that require exclusive access to the ipsq.
8112  *
8113  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8114  * happen here. (along with mi_copy_done)
8115  */
8116 /* ARGSUSED */
8117 static void
8118 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8119 {
8120 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8121 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8122 	int		err = 0;
8123 	ill_t		*ill = (ill_t *)q->q_ptr;
8124 	ipif_t		*ipif = NULL;
8125 	mblk_t		*mp1 = NULL;
8126 	conn_t		*connp = NULL;
8127 	t_uscalar_t	paddrreq;
8128 	mblk_t		*mp_hw;
8129 	boolean_t	success;
8130 	boolean_t	ioctl_aborted = B_FALSE;
8131 	boolean_t	log = B_TRUE;
8132 
8133 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8134 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8135 
8136 	ip1dbg(("ip_rput_dlpi_writer .."));
8137 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8138 	ASSERT(IAM_WRITER_ILL(ill));
8139 
8140 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8141 	/*
8142 	 * The current ioctl could have been aborted by the user and a new
8143 	 * ioctl to bring up another ill could have started. We could still
8144 	 * get a response from the driver later.
8145 	 */
8146 	if (ipif != NULL && ipif->ipif_ill != ill)
8147 		ioctl_aborted = B_TRUE;
8148 
8149 	switch (dloa->dl_primitive) {
8150 	case DL_ERROR_ACK:
8151 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8152 		    dl_primstr(dlea->dl_error_primitive)));
8153 
8154 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8155 		    char *, dl_primstr(dlea->dl_error_primitive),
8156 		    ill_t *, ill);
8157 
8158 		switch (dlea->dl_error_primitive) {
8159 		case DL_DISABMULTI_REQ:
8160 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8161 			break;
8162 		case DL_PROMISCON_REQ:
8163 		case DL_PROMISCOFF_REQ:
8164 		case DL_UNBIND_REQ:
8165 		case DL_ATTACH_REQ:
8166 		case DL_INFO_REQ:
8167 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8168 			break;
8169 		case DL_NOTIFY_REQ:
8170 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8171 			log = B_FALSE;
8172 			break;
8173 		case DL_PHYS_ADDR_REQ:
8174 			/*
8175 			 * For IPv6 only, there are two additional
8176 			 * phys_addr_req's sent to the driver to get the
8177 			 * IPv6 token and lla. This allows IP to acquire
8178 			 * the hardware address format for a given interface
8179 			 * without having built in knowledge of the hardware
8180 			 * address. ill_phys_addr_pend keeps track of the last
8181 			 * DL_PAR sent so we know which response we are
8182 			 * dealing with. ill_dlpi_done will update
8183 			 * ill_phys_addr_pend when it sends the next req.
8184 			 * We don't complete the IOCTL until all three DL_PARs
8185 			 * have been attempted, so set *_len to 0 and break.
8186 			 */
8187 			paddrreq = ill->ill_phys_addr_pend;
8188 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8189 			if (paddrreq == DL_IPV6_TOKEN) {
8190 				ill->ill_token_length = 0;
8191 				log = B_FALSE;
8192 				break;
8193 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8194 				ill->ill_nd_lla_len = 0;
8195 				log = B_FALSE;
8196 				break;
8197 			}
8198 			/*
8199 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8200 			 * We presumably have an IOCTL hanging out waiting
8201 			 * for completion. Find it and complete the IOCTL
8202 			 * with the error noted.
8203 			 * However, ill_dl_phys was called on an ill queue
8204 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8205 			 * set. But the ioctl is known to be pending on ill_wq.
8206 			 */
8207 			if (!ill->ill_ifname_pending)
8208 				break;
8209 			ill->ill_ifname_pending = 0;
8210 			if (!ioctl_aborted)
8211 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8212 			if (mp1 != NULL) {
8213 				/*
8214 				 * This operation (SIOCSLIFNAME) must have
8215 				 * happened on the ill. Assert there is no conn
8216 				 */
8217 				ASSERT(connp == NULL);
8218 				q = ill->ill_wq;
8219 			}
8220 			break;
8221 		case DL_BIND_REQ:
8222 			ill_dlpi_done(ill, DL_BIND_REQ);
8223 			if (ill->ill_ifname_pending)
8224 				break;
8225 			mutex_enter(&ill->ill_lock);
8226 			ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8227 			mutex_exit(&ill->ill_lock);
8228 			/*
8229 			 * Something went wrong with the bind.  We presumably
8230 			 * have an IOCTL hanging out waiting for completion.
8231 			 * Find it, take down the interface that was coming
8232 			 * up, and complete the IOCTL with the error noted.
8233 			 */
8234 			if (!ioctl_aborted)
8235 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8236 			if (mp1 != NULL) {
8237 				/*
8238 				 * This might be a result of a DL_NOTE_REPLUMB
8239 				 * notification. In that case, connp is NULL.
8240 				 */
8241 				if (connp != NULL)
8242 					q = CONNP_TO_WQ(connp);
8243 
8244 				(void) ipif_down(ipif, NULL, NULL);
8245 				/* error is set below the switch */
8246 			}
8247 			break;
8248 		case DL_ENABMULTI_REQ:
8249 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8250 
8251 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8252 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8253 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8254 
8255 				printf("ip: joining multicasts failed (%d)"
8256 				    " on %s - will use link layer "
8257 				    "broadcasts for multicast\n",
8258 				    dlea->dl_errno, ill->ill_name);
8259 
8260 				/*
8261 				 * Set up for multi_bcast; We are the
8262 				 * writer, so ok to access ill->ill_ipif
8263 				 * without any lock.
8264 				 */
8265 				mutex_enter(&ill->ill_phyint->phyint_lock);
8266 				ill->ill_phyint->phyint_flags |=
8267 				    PHYI_MULTI_BCAST;
8268 				mutex_exit(&ill->ill_phyint->phyint_lock);
8269 
8270 			}
8271 			freemsg(mp);	/* Don't want to pass this up */
8272 			return;
8273 		case DL_CAPABILITY_REQ:
8274 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8275 			    "DL_CAPABILITY REQ\n"));
8276 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8277 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8278 			ill_capability_done(ill);
8279 			freemsg(mp);
8280 			return;
8281 		}
8282 		/*
8283 		 * Note the error for IOCTL completion (mp1 is set when
8284 		 * ready to complete ioctl). If ill_ifname_pending_err is
8285 		 * set, an error occured during plumbing (ill_ifname_pending),
8286 		 * so we want to report that error.
8287 		 *
8288 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8289 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8290 		 * expected to get errack'd if the driver doesn't support
8291 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8292 		 * if these error conditions are encountered.
8293 		 */
8294 		if (mp1 != NULL) {
8295 			if (ill->ill_ifname_pending_err != 0)  {
8296 				err = ill->ill_ifname_pending_err;
8297 				ill->ill_ifname_pending_err = 0;
8298 			} else {
8299 				err = dlea->dl_unix_errno ?
8300 				    dlea->dl_unix_errno : ENXIO;
8301 			}
8302 		/*
8303 		 * If we're plumbing an interface and an error hasn't already
8304 		 * been saved, set ill_ifname_pending_err to the error passed
8305 		 * up. Ignore the error if log is B_FALSE (see comment above).
8306 		 */
8307 		} else if (log && ill->ill_ifname_pending &&
8308 		    ill->ill_ifname_pending_err == 0) {
8309 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8310 			    dlea->dl_unix_errno : ENXIO;
8311 		}
8312 
8313 		if (log)
8314 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8315 			    dlea->dl_errno, dlea->dl_unix_errno);
8316 		break;
8317 	case DL_CAPABILITY_ACK:
8318 		ill_capability_ack(ill, mp);
8319 		/*
8320 		 * The message has been handed off to ill_capability_ack
8321 		 * and must not be freed below
8322 		 */
8323 		mp = NULL;
8324 		break;
8325 
8326 	case DL_INFO_ACK:
8327 		/* Call a routine to handle this one. */
8328 		ill_dlpi_done(ill, DL_INFO_REQ);
8329 		ip_ll_subnet_defaults(ill, mp);
8330 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8331 		return;
8332 	case DL_BIND_ACK:
8333 		/*
8334 		 * We should have an IOCTL waiting on this unless
8335 		 * sent by ill_dl_phys, in which case just return
8336 		 */
8337 		ill_dlpi_done(ill, DL_BIND_REQ);
8338 
8339 		if (ill->ill_ifname_pending) {
8340 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8341 			    ill_t *, ill, mblk_t *, mp);
8342 			break;
8343 		}
8344 		mutex_enter(&ill->ill_lock);
8345 		ill->ill_dl_up = 1;
8346 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8347 		mutex_exit(&ill->ill_lock);
8348 
8349 		if (!ioctl_aborted)
8350 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8351 		if (mp1 == NULL) {
8352 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8353 			break;
8354 		}
8355 		/*
8356 		 * mp1 was added by ill_dl_up(). if that is a result of
8357 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8358 		 */
8359 		if (connp != NULL)
8360 			q = CONNP_TO_WQ(connp);
8361 		/*
8362 		 * We are exclusive. So nothing can change even after
8363 		 * we get the pending mp.
8364 		 */
8365 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8366 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8367 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8368 
8369 		/*
8370 		 * Now bring up the resolver; when that is complete, we'll
8371 		 * create IREs.  Note that we intentionally mirror what
8372 		 * ipif_up() would have done, because we got here by way of
8373 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8374 		 */
8375 		if (ill->ill_isv6) {
8376 			/*
8377 			 * v6 interfaces.
8378 			 * Unlike ARP which has to do another bind
8379 			 * and attach, once we get here we are
8380 			 * done with NDP
8381 			 */
8382 			(void) ipif_resolver_up(ipif, Res_act_initial);
8383 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8384 				err = ipif_up_done_v6(ipif);
8385 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8386 			/*
8387 			 * ARP and other v4 external resolvers.
8388 			 * Leave the pending mblk intact so that
8389 			 * the ioctl completes in ip_rput().
8390 			 */
8391 			if (connp != NULL)
8392 				mutex_enter(&connp->conn_lock);
8393 			mutex_enter(&ill->ill_lock);
8394 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8395 			mutex_exit(&ill->ill_lock);
8396 			if (connp != NULL)
8397 				mutex_exit(&connp->conn_lock);
8398 			if (success) {
8399 				err = ipif_resolver_up(ipif, Res_act_initial);
8400 				if (err == EINPROGRESS) {
8401 					freemsg(mp);
8402 					return;
8403 				}
8404 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8405 			} else {
8406 				/* The conn has started closing */
8407 				err = EINTR;
8408 			}
8409 		} else {
8410 			/*
8411 			 * This one is complete. Reply to pending ioctl.
8412 			 */
8413 			(void) ipif_resolver_up(ipif, Res_act_initial);
8414 			err = ipif_up_done(ipif);
8415 		}
8416 
8417 		if ((err == 0) && (ill->ill_up_ipifs)) {
8418 			err = ill_up_ipifs(ill, q, mp1);
8419 			if (err == EINPROGRESS) {
8420 				freemsg(mp);
8421 				return;
8422 			}
8423 		}
8424 
8425 		/*
8426 		 * If we have a moved ipif to bring up, and everything has
8427 		 * succeeded to this point, bring it up on the IPMP ill.
8428 		 * Otherwise, leave it down -- the admin can try to bring it
8429 		 * up by hand if need be.
8430 		 */
8431 		if (ill->ill_move_ipif != NULL) {
8432 			if (err != 0) {
8433 				ill->ill_move_ipif = NULL;
8434 			} else {
8435 				ipif = ill->ill_move_ipif;
8436 				ill->ill_move_ipif = NULL;
8437 				err = ipif_up(ipif, q, mp1);
8438 				if (err == EINPROGRESS) {
8439 					freemsg(mp);
8440 					return;
8441 				}
8442 			}
8443 		}
8444 		break;
8445 
8446 	case DL_NOTIFY_IND: {
8447 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8448 		uint_t orig_mtu;
8449 
8450 		switch (notify->dl_notification) {
8451 		case DL_NOTE_PHYS_ADDR:
8452 			err = ill_set_phys_addr(ill, mp);
8453 			break;
8454 
8455 		case DL_NOTE_REPLUMB:
8456 			/*
8457 			 * Directly return after calling ill_replumb().
8458 			 * Note that we should not free mp as it is reused
8459 			 * in the ill_replumb() function.
8460 			 */
8461 			err = ill_replumb(ill, mp);
8462 			return;
8463 
8464 		case DL_NOTE_FASTPATH_FLUSH:
8465 			nce_flush(ill, B_FALSE);
8466 			break;
8467 
8468 		case DL_NOTE_SDU_SIZE:
8469 			/*
8470 			 * The dce and fragmentation code can cope with
8471 			 * this changing while packets are being sent.
8472 			 * When packets are sent ip_output will discover
8473 			 * a change.
8474 			 *
8475 			 * Change the MTU size of the interface.
8476 			 */
8477 			mutex_enter(&ill->ill_lock);
8478 			ill->ill_current_frag = (uint_t)notify->dl_data;
8479 			if (ill->ill_current_frag > ill->ill_max_frag)
8480 				ill->ill_max_frag = ill->ill_current_frag;
8481 
8482 			orig_mtu = ill->ill_mtu;
8483 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8484 				ill->ill_mtu = ill->ill_current_frag;
8485 
8486 				/*
8487 				 * If ill_user_mtu was set (via
8488 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8489 				 */
8490 				if (ill->ill_user_mtu != 0 &&
8491 				    ill->ill_user_mtu < ill->ill_mtu)
8492 					ill->ill_mtu = ill->ill_user_mtu;
8493 
8494 				if (ill->ill_isv6) {
8495 					if (ill->ill_mtu < IPV6_MIN_MTU)
8496 						ill->ill_mtu = IPV6_MIN_MTU;
8497 				} else {
8498 					if (ill->ill_mtu < IP_MIN_MTU)
8499 						ill->ill_mtu = IP_MIN_MTU;
8500 				}
8501 			}
8502 			mutex_exit(&ill->ill_lock);
8503 			/*
8504 			 * Make sure all dce_generation checks find out
8505 			 * that ill_mtu has changed.
8506 			 */
8507 			if (orig_mtu != ill->ill_mtu) {
8508 				dce_increment_all_generations(ill->ill_isv6,
8509 				    ill->ill_ipst);
8510 			}
8511 
8512 			/*
8513 			 * Refresh IPMP meta-interface MTU if necessary.
8514 			 */
8515 			if (IS_UNDER_IPMP(ill))
8516 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8517 			break;
8518 
8519 		case DL_NOTE_LINK_UP:
8520 		case DL_NOTE_LINK_DOWN: {
8521 			/*
8522 			 * We are writer. ill / phyint / ipsq assocs stable.
8523 			 * The RUNNING flag reflects the state of the link.
8524 			 */
8525 			phyint_t *phyint = ill->ill_phyint;
8526 			uint64_t new_phyint_flags;
8527 			boolean_t changed = B_FALSE;
8528 			boolean_t went_up;
8529 
8530 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8531 			mutex_enter(&phyint->phyint_lock);
8532 
8533 			new_phyint_flags = went_up ?
8534 			    phyint->phyint_flags | PHYI_RUNNING :
8535 			    phyint->phyint_flags & ~PHYI_RUNNING;
8536 
8537 			if (IS_IPMP(ill)) {
8538 				new_phyint_flags = went_up ?
8539 				    new_phyint_flags & ~PHYI_FAILED :
8540 				    new_phyint_flags | PHYI_FAILED;
8541 			}
8542 
8543 			if (new_phyint_flags != phyint->phyint_flags) {
8544 				phyint->phyint_flags = new_phyint_flags;
8545 				changed = B_TRUE;
8546 			}
8547 			mutex_exit(&phyint->phyint_lock);
8548 			/*
8549 			 * ill_restart_dad handles the DAD restart and routing
8550 			 * socket notification logic.
8551 			 */
8552 			if (changed) {
8553 				ill_restart_dad(phyint->phyint_illv4, went_up);
8554 				ill_restart_dad(phyint->phyint_illv6, went_up);
8555 			}
8556 			break;
8557 		}
8558 		case DL_NOTE_PROMISC_ON_PHYS: {
8559 			phyint_t *phyint = ill->ill_phyint;
8560 
8561 			mutex_enter(&phyint->phyint_lock);
8562 			phyint->phyint_flags |= PHYI_PROMISC;
8563 			mutex_exit(&phyint->phyint_lock);
8564 			break;
8565 		}
8566 		case DL_NOTE_PROMISC_OFF_PHYS: {
8567 			phyint_t *phyint = ill->ill_phyint;
8568 
8569 			mutex_enter(&phyint->phyint_lock);
8570 			phyint->phyint_flags &= ~PHYI_PROMISC;
8571 			mutex_exit(&phyint->phyint_lock);
8572 			break;
8573 		}
8574 		case DL_NOTE_CAPAB_RENEG:
8575 			/*
8576 			 * Something changed on the driver side.
8577 			 * It wants us to renegotiate the capabilities
8578 			 * on this ill. One possible cause is the aggregation
8579 			 * interface under us where a port got added or
8580 			 * went away.
8581 			 *
8582 			 * If the capability negotiation is already done
8583 			 * or is in progress, reset the capabilities and
8584 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8585 			 * so that when the ack comes back, we can start
8586 			 * the renegotiation process.
8587 			 *
8588 			 * Note that if ill_capab_reneg is already B_TRUE
8589 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8590 			 * the capability resetting request has been sent
8591 			 * and the renegotiation has not been started yet;
8592 			 * nothing needs to be done in this case.
8593 			 */
8594 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8595 			ill_capability_reset(ill, B_TRUE);
8596 			ipsq_current_finish(ipsq);
8597 			break;
8598 
8599 		case DL_NOTE_ALLOWED_IPS:
8600 			ill_set_allowed_ips(ill, mp);
8601 			break;
8602 		default:
8603 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8604 			    "type 0x%x for DL_NOTIFY_IND\n",
8605 			    notify->dl_notification));
8606 			break;
8607 		}
8608 
8609 		/*
8610 		 * As this is an asynchronous operation, we
8611 		 * should not call ill_dlpi_done
8612 		 */
8613 		break;
8614 	}
8615 	case DL_NOTIFY_ACK: {
8616 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8617 
8618 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8619 			ill->ill_note_link = 1;
8620 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8621 		break;
8622 	}
8623 	case DL_PHYS_ADDR_ACK: {
8624 		/*
8625 		 * As part of plumbing the interface via SIOCSLIFNAME,
8626 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8627 		 * whose answers we receive here.  As each answer is received,
8628 		 * we call ill_dlpi_done() to dispatch the next request as
8629 		 * we're processing the current one.  Once all answers have
8630 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8631 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8632 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8633 		 * available, but we know the ioctl is pending on ill_wq.)
8634 		 */
8635 		uint_t	paddrlen, paddroff;
8636 		uint8_t	*addr;
8637 
8638 		paddrreq = ill->ill_phys_addr_pend;
8639 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8640 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8641 		addr = mp->b_rptr + paddroff;
8642 
8643 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8644 		if (paddrreq == DL_IPV6_TOKEN) {
8645 			/*
8646 			 * bcopy to low-order bits of ill_token
8647 			 *
8648 			 * XXX Temporary hack - currently, all known tokens
8649 			 * are 64 bits, so I'll cheat for the moment.
8650 			 */
8651 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8652 			ill->ill_token_length = paddrlen;
8653 			break;
8654 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8655 			ASSERT(ill->ill_nd_lla_mp == NULL);
8656 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8657 			mp = NULL;
8658 			break;
8659 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8660 			ASSERT(ill->ill_dest_addr_mp == NULL);
8661 			ill->ill_dest_addr_mp = mp;
8662 			ill->ill_dest_addr = addr;
8663 			mp = NULL;
8664 			if (ill->ill_isv6) {
8665 				ill_setdesttoken(ill);
8666 				ipif_setdestlinklocal(ill->ill_ipif);
8667 			}
8668 			break;
8669 		}
8670 
8671 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8672 		ASSERT(ill->ill_phys_addr_mp == NULL);
8673 		if (!ill->ill_ifname_pending)
8674 			break;
8675 		ill->ill_ifname_pending = 0;
8676 		if (!ioctl_aborted)
8677 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8678 		if (mp1 != NULL) {
8679 			ASSERT(connp == NULL);
8680 			q = ill->ill_wq;
8681 		}
8682 		/*
8683 		 * If any error acks received during the plumbing sequence,
8684 		 * ill_ifname_pending_err will be set. Break out and send up
8685 		 * the error to the pending ioctl.
8686 		 */
8687 		if (ill->ill_ifname_pending_err != 0) {
8688 			err = ill->ill_ifname_pending_err;
8689 			ill->ill_ifname_pending_err = 0;
8690 			break;
8691 		}
8692 
8693 		ill->ill_phys_addr_mp = mp;
8694 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8695 		mp = NULL;
8696 
8697 		/*
8698 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8699 		 * provider doesn't support physical addresses.  We check both
8700 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8701 		 * not have physical addresses, but historically adversises a
8702 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8703 		 * its DL_PHYS_ADDR_ACK.
8704 		 */
8705 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8706 			ill->ill_phys_addr = NULL;
8707 		} else if (paddrlen != ill->ill_phys_addr_length) {
8708 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8709 			    paddrlen, ill->ill_phys_addr_length));
8710 			err = EINVAL;
8711 			break;
8712 		}
8713 
8714 		if (ill->ill_nd_lla_mp == NULL) {
8715 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8716 				err = ENOMEM;
8717 				break;
8718 			}
8719 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8720 		}
8721 
8722 		if (ill->ill_isv6) {
8723 			ill_setdefaulttoken(ill);
8724 			ipif_setlinklocal(ill->ill_ipif);
8725 		}
8726 		break;
8727 	}
8728 	case DL_OK_ACK:
8729 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8730 		    dl_primstr((int)dloa->dl_correct_primitive),
8731 		    dloa->dl_correct_primitive));
8732 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8733 		    char *, dl_primstr(dloa->dl_correct_primitive),
8734 		    ill_t *, ill);
8735 
8736 		switch (dloa->dl_correct_primitive) {
8737 		case DL_ENABMULTI_REQ:
8738 		case DL_DISABMULTI_REQ:
8739 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8740 			break;
8741 		case DL_PROMISCON_REQ:
8742 		case DL_PROMISCOFF_REQ:
8743 		case DL_UNBIND_REQ:
8744 		case DL_ATTACH_REQ:
8745 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8746 			break;
8747 		}
8748 		break;
8749 	default:
8750 		break;
8751 	}
8752 
8753 	freemsg(mp);
8754 	if (mp1 == NULL)
8755 		return;
8756 
8757 	/*
8758 	 * The operation must complete without EINPROGRESS since
8759 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8760 	 * the operation will be stuck forever inside the IPSQ.
8761 	 */
8762 	ASSERT(err != EINPROGRESS);
8763 
8764 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8765 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8766 	    ipif_t *, NULL);
8767 
8768 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8769 	case 0:
8770 		ipsq_current_finish(ipsq);
8771 		break;
8772 
8773 	case SIOCSLIFNAME:
8774 	case IF_UNITSEL: {
8775 		ill_t *ill_other = ILL_OTHER(ill);
8776 
8777 		/*
8778 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8779 		 * ill has a peer which is in an IPMP group, then place ill
8780 		 * into the same group.  One catch: although ifconfig plumbs
8781 		 * the appropriate IPMP meta-interface prior to plumbing this
8782 		 * ill, it is possible for multiple ifconfig applications to
8783 		 * race (or for another application to adjust plumbing), in
8784 		 * which case the IPMP meta-interface we need will be missing.
8785 		 * If so, kick the phyint out of the group.
8786 		 */
8787 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8788 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8789 			ipmp_illgrp_t	*illg;
8790 
8791 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8792 			if (illg == NULL)
8793 				ipmp_phyint_leave_grp(ill->ill_phyint);
8794 			else
8795 				ipmp_ill_join_illgrp(ill, illg);
8796 		}
8797 
8798 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8799 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8800 		else
8801 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8802 		break;
8803 	}
8804 	case SIOCLIFADDIF:
8805 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8806 		break;
8807 
8808 	default:
8809 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8810 		break;
8811 	}
8812 }
8813 
8814 /*
8815  * ip_rput_other is called by ip_rput to handle messages modifying the global
8816  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8817  */
8818 /* ARGSUSED */
8819 void
8820 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8821 {
8822 	ill_t		*ill = q->q_ptr;
8823 	struct iocblk	*iocp;
8824 
8825 	ip1dbg(("ip_rput_other "));
8826 	if (ipsq != NULL) {
8827 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8828 		ASSERT(ipsq->ipsq_xop ==
8829 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8830 	}
8831 
8832 	switch (mp->b_datap->db_type) {
8833 	case M_ERROR:
8834 	case M_HANGUP:
8835 		/*
8836 		 * The device has a problem.  We force the ILL down.  It can
8837 		 * be brought up again manually using SIOCSIFFLAGS (via
8838 		 * ifconfig or equivalent).
8839 		 */
8840 		ASSERT(ipsq != NULL);
8841 		if (mp->b_rptr < mp->b_wptr)
8842 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8843 		if (ill->ill_error == 0)
8844 			ill->ill_error = ENXIO;
8845 		if (!ill_down_start(q, mp))
8846 			return;
8847 		ipif_all_down_tail(ipsq, q, mp, NULL);
8848 		break;
8849 	case M_IOCNAK: {
8850 		iocp = (struct iocblk *)mp->b_rptr;
8851 
8852 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8853 		/*
8854 		 * If this was the first attempt, turn off the fastpath
8855 		 * probing.
8856 		 */
8857 		mutex_enter(&ill->ill_lock);
8858 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8859 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8860 			mutex_exit(&ill->ill_lock);
8861 			/*
8862 			 * don't flush the nce_t entries: we use them
8863 			 * as an index to the ncec itself.
8864 			 */
8865 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8866 			    ill->ill_name));
8867 		} else {
8868 			mutex_exit(&ill->ill_lock);
8869 		}
8870 		freemsg(mp);
8871 		break;
8872 	}
8873 	default:
8874 		ASSERT(0);
8875 		break;
8876 	}
8877 }
8878 
8879 /*
8880  * Update any source route, record route or timestamp options
8881  * When it fails it has consumed the message and BUMPed the MIB.
8882  */
8883 boolean_t
8884 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8885     ip_recv_attr_t *ira)
8886 {
8887 	ipoptp_t	opts;
8888 	uchar_t		*opt;
8889 	uint8_t		optval;
8890 	uint8_t		optlen;
8891 	ipaddr_t	dst;
8892 	ipaddr_t	ifaddr;
8893 	uint32_t	ts;
8894 	timestruc_t	now;
8895 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
8896 
8897 	ip2dbg(("ip_forward_options\n"));
8898 	dst = ipha->ipha_dst;
8899 	for (optval = ipoptp_first(&opts, ipha);
8900 	    optval != IPOPT_EOL;
8901 	    optval = ipoptp_next(&opts)) {
8902 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
8903 		opt = opts.ipoptp_cur;
8904 		optlen = opts.ipoptp_len;
8905 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
8906 		    optval, opts.ipoptp_len));
8907 		switch (optval) {
8908 			uint32_t off;
8909 		case IPOPT_SSRR:
8910 		case IPOPT_LSRR:
8911 			/* Check if adminstratively disabled */
8912 			if (!ipst->ips_ip_forward_src_routed) {
8913 				BUMP_MIB(dst_ill->ill_ip_mib,
8914 				    ipIfStatsForwProhibits);
8915 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
8916 				    mp, dst_ill);
8917 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
8918 				    ira);
8919 				return (B_FALSE);
8920 			}
8921 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8922 				/*
8923 				 * Must be partial since ip_input_options
8924 				 * checked for strict.
8925 				 */
8926 				break;
8927 			}
8928 			off = opt[IPOPT_OFFSET];
8929 			off--;
8930 		redo_srr:
8931 			if (optlen < IP_ADDR_LEN ||
8932 			    off > optlen - IP_ADDR_LEN) {
8933 				/* End of source route */
8934 				ip1dbg((
8935 				    "ip_forward_options: end of SR\n"));
8936 				break;
8937 			}
8938 			/* Pick a reasonable address on the outbound if */
8939 			ASSERT(dst_ill != NULL);
8940 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8941 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8942 			    NULL) != 0) {
8943 				/* No source! Shouldn't happen */
8944 				ifaddr = INADDR_ANY;
8945 			}
8946 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8947 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8948 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
8949 			    ntohl(dst)));
8950 
8951 			/*
8952 			 * Check if our address is present more than
8953 			 * once as consecutive hops in source route.
8954 			 */
8955 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
8956 				off += IP_ADDR_LEN;
8957 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8958 				goto redo_srr;
8959 			}
8960 			ipha->ipha_dst = dst;
8961 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8962 			break;
8963 		case IPOPT_RR:
8964 			off = opt[IPOPT_OFFSET];
8965 			off--;
8966 			if (optlen < IP_ADDR_LEN ||
8967 			    off > optlen - IP_ADDR_LEN) {
8968 				/* No more room - ignore */
8969 				ip1dbg((
8970 				    "ip_forward_options: end of RR\n"));
8971 				break;
8972 			}
8973 			/* Pick a reasonable address on the outbound if */
8974 			ASSERT(dst_ill != NULL);
8975 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8976 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8977 			    NULL) != 0) {
8978 				/* No source! Shouldn't happen */
8979 				ifaddr = INADDR_ANY;
8980 			}
8981 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8982 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8983 			break;
8984 		case IPOPT_TS:
8985 			/* Insert timestamp if there is room */
8986 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
8987 			case IPOPT_TS_TSONLY:
8988 				off = IPOPT_TS_TIMELEN;
8989 				break;
8990 			case IPOPT_TS_PRESPEC:
8991 			case IPOPT_TS_PRESPEC_RFC791:
8992 				/* Verify that the address matched */
8993 				off = opt[IPOPT_OFFSET] - 1;
8994 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8995 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8996 					/* Not for us */
8997 					break;
8998 				}
8999 				/* FALLTHRU */
9000 			case IPOPT_TS_TSANDADDR:
9001 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9002 				break;
9003 			default:
9004 				/*
9005 				 * ip_*put_options should have already
9006 				 * dropped this packet.
9007 				 */
9008 				cmn_err(CE_PANIC, "ip_forward_options: "
9009 				    "unknown IT - bug in ip_input_options?\n");
9010 				return (B_TRUE);	/* Keep "lint" happy */
9011 			}
9012 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9013 				/* Increase overflow counter */
9014 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9015 				opt[IPOPT_POS_OV_FLG] =
9016 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9017 				    (off << 4));
9018 				break;
9019 			}
9020 			off = opt[IPOPT_OFFSET] - 1;
9021 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9022 			case IPOPT_TS_PRESPEC:
9023 			case IPOPT_TS_PRESPEC_RFC791:
9024 			case IPOPT_TS_TSANDADDR:
9025 				/* Pick a reasonable addr on the outbound if */
9026 				ASSERT(dst_ill != NULL);
9027 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9028 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9029 				    NULL, NULL) != 0) {
9030 					/* No source! Shouldn't happen */
9031 					ifaddr = INADDR_ANY;
9032 				}
9033 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9034 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9035 				/* FALLTHRU */
9036 			case IPOPT_TS_TSONLY:
9037 				off = opt[IPOPT_OFFSET] - 1;
9038 				/* Compute # of milliseconds since midnight */
9039 				gethrestime(&now);
9040 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9041 				    now.tv_nsec / (NANOSEC / MILLISEC);
9042 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9043 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9044 				break;
9045 			}
9046 			break;
9047 		}
9048 	}
9049 	return (B_TRUE);
9050 }
9051 
9052 /*
9053  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9054  * returns 'true' if there are still fragments left on the queue, in
9055  * which case we restart the timer.
9056  */
9057 void
9058 ill_frag_timer(void *arg)
9059 {
9060 	ill_t	*ill = (ill_t *)arg;
9061 	boolean_t frag_pending;
9062 	ip_stack_t *ipst = ill->ill_ipst;
9063 	time_t	timeout;
9064 
9065 	mutex_enter(&ill->ill_lock);
9066 	ASSERT(!ill->ill_fragtimer_executing);
9067 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9068 		ill->ill_frag_timer_id = 0;
9069 		mutex_exit(&ill->ill_lock);
9070 		return;
9071 	}
9072 	ill->ill_fragtimer_executing = 1;
9073 	mutex_exit(&ill->ill_lock);
9074 
9075 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9076 	    ipst->ips_ip_reassembly_timeout);
9077 
9078 	frag_pending = ill_frag_timeout(ill, timeout);
9079 
9080 	/*
9081 	 * Restart the timer, if we have fragments pending or if someone
9082 	 * wanted us to be scheduled again.
9083 	 */
9084 	mutex_enter(&ill->ill_lock);
9085 	ill->ill_fragtimer_executing = 0;
9086 	ill->ill_frag_timer_id = 0;
9087 	if (frag_pending || ill->ill_fragtimer_needrestart)
9088 		ill_frag_timer_start(ill);
9089 	mutex_exit(&ill->ill_lock);
9090 }
9091 
9092 void
9093 ill_frag_timer_start(ill_t *ill)
9094 {
9095 	ip_stack_t *ipst = ill->ill_ipst;
9096 	clock_t	timeo_ms;
9097 
9098 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9099 
9100 	/* If the ill is closing or opening don't proceed */
9101 	if (ill->ill_state_flags & ILL_CONDEMNED)
9102 		return;
9103 
9104 	if (ill->ill_fragtimer_executing) {
9105 		/*
9106 		 * ill_frag_timer is currently executing. Just record the
9107 		 * the fact that we want the timer to be restarted.
9108 		 * ill_frag_timer will post a timeout before it returns,
9109 		 * ensuring it will be called again.
9110 		 */
9111 		ill->ill_fragtimer_needrestart = 1;
9112 		return;
9113 	}
9114 
9115 	if (ill->ill_frag_timer_id == 0) {
9116 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9117 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9118 
9119 		/*
9120 		 * The timer is neither running nor is the timeout handler
9121 		 * executing. Post a timeout so that ill_frag_timer will be
9122 		 * called
9123 		 */
9124 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9125 		    MSEC_TO_TICK(timeo_ms >> 1));
9126 		ill->ill_fragtimer_needrestart = 0;
9127 	}
9128 }
9129 
9130 /*
9131  * Update any source route, record route or timestamp options.
9132  * Check that we are at end of strict source route.
9133  * The options have already been checked for sanity in ip_input_options().
9134  */
9135 boolean_t
9136 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9137 {
9138 	ipoptp_t	opts;
9139 	uchar_t		*opt;
9140 	uint8_t		optval;
9141 	uint8_t		optlen;
9142 	ipaddr_t	dst;
9143 	ipaddr_t	ifaddr;
9144 	uint32_t	ts;
9145 	timestruc_t	now;
9146 	ill_t		*ill = ira->ira_ill;
9147 	ip_stack_t	*ipst = ill->ill_ipst;
9148 
9149 	ip2dbg(("ip_input_local_options\n"));
9150 
9151 	for (optval = ipoptp_first(&opts, ipha);
9152 	    optval != IPOPT_EOL;
9153 	    optval = ipoptp_next(&opts)) {
9154 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9155 		opt = opts.ipoptp_cur;
9156 		optlen = opts.ipoptp_len;
9157 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9158 		    optval, optlen));
9159 		switch (optval) {
9160 			uint32_t off;
9161 		case IPOPT_SSRR:
9162 		case IPOPT_LSRR:
9163 			off = opt[IPOPT_OFFSET];
9164 			off--;
9165 			if (optlen < IP_ADDR_LEN ||
9166 			    off > optlen - IP_ADDR_LEN) {
9167 				/* End of source route */
9168 				ip1dbg(("ip_input_local_options: end of SR\n"));
9169 				break;
9170 			}
9171 			/*
9172 			 * This will only happen if two consecutive entries
9173 			 * in the source route contains our address or if
9174 			 * it is a packet with a loose source route which
9175 			 * reaches us before consuming the whole source route
9176 			 */
9177 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9178 			if (optval == IPOPT_SSRR) {
9179 				goto bad_src_route;
9180 			}
9181 			/*
9182 			 * Hack: instead of dropping the packet truncate the
9183 			 * source route to what has been used by filling the
9184 			 * rest with IPOPT_NOP.
9185 			 */
9186 			opt[IPOPT_OLEN] = (uint8_t)off;
9187 			while (off < optlen) {
9188 				opt[off++] = IPOPT_NOP;
9189 			}
9190 			break;
9191 		case IPOPT_RR:
9192 			off = opt[IPOPT_OFFSET];
9193 			off--;
9194 			if (optlen < IP_ADDR_LEN ||
9195 			    off > optlen - IP_ADDR_LEN) {
9196 				/* No more room - ignore */
9197 				ip1dbg((
9198 				    "ip_input_local_options: end of RR\n"));
9199 				break;
9200 			}
9201 			/* Pick a reasonable address on the outbound if */
9202 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9203 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9204 			    NULL) != 0) {
9205 				/* No source! Shouldn't happen */
9206 				ifaddr = INADDR_ANY;
9207 			}
9208 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9209 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9210 			break;
9211 		case IPOPT_TS:
9212 			/* Insert timestamp if there is romm */
9213 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9214 			case IPOPT_TS_TSONLY:
9215 				off = IPOPT_TS_TIMELEN;
9216 				break;
9217 			case IPOPT_TS_PRESPEC:
9218 			case IPOPT_TS_PRESPEC_RFC791:
9219 				/* Verify that the address matched */
9220 				off = opt[IPOPT_OFFSET] - 1;
9221 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9222 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9223 					/* Not for us */
9224 					break;
9225 				}
9226 				/* FALLTHRU */
9227 			case IPOPT_TS_TSANDADDR:
9228 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9229 				break;
9230 			default:
9231 				/*
9232 				 * ip_*put_options should have already
9233 				 * dropped this packet.
9234 				 */
9235 				cmn_err(CE_PANIC, "ip_input_local_options: "
9236 				    "unknown IT - bug in ip_input_options?\n");
9237 				return (B_TRUE);	/* Keep "lint" happy */
9238 			}
9239 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9240 				/* Increase overflow counter */
9241 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9242 				opt[IPOPT_POS_OV_FLG] =
9243 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9244 				    (off << 4));
9245 				break;
9246 			}
9247 			off = opt[IPOPT_OFFSET] - 1;
9248 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9249 			case IPOPT_TS_PRESPEC:
9250 			case IPOPT_TS_PRESPEC_RFC791:
9251 			case IPOPT_TS_TSANDADDR:
9252 				/* Pick a reasonable addr on the outbound if */
9253 				if (ip_select_source_v4(ill, INADDR_ANY,
9254 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9255 				    &ifaddr, NULL, NULL) != 0) {
9256 					/* No source! Shouldn't happen */
9257 					ifaddr = INADDR_ANY;
9258 				}
9259 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9260 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9261 				/* FALLTHRU */
9262 			case IPOPT_TS_TSONLY:
9263 				off = opt[IPOPT_OFFSET] - 1;
9264 				/* Compute # of milliseconds since midnight */
9265 				gethrestime(&now);
9266 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9267 				    now.tv_nsec / (NANOSEC / MILLISEC);
9268 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9269 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9270 				break;
9271 			}
9272 			break;
9273 		}
9274 	}
9275 	return (B_TRUE);
9276 
9277 bad_src_route:
9278 	/* make sure we clear any indication of a hardware checksum */
9279 	DB_CKSUMFLAGS(mp) = 0;
9280 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9281 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9282 	return (B_FALSE);
9283 
9284 }
9285 
9286 /*
9287  * Process IP options in an inbound packet.  Always returns the nexthop.
9288  * Normally this is the passed in nexthop, but if there is an option
9289  * that effects the nexthop (such as a source route) that will be returned.
9290  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9291  * and mp freed.
9292  */
9293 ipaddr_t
9294 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9295     ip_recv_attr_t *ira, int *errorp)
9296 {
9297 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9298 	ipoptp_t	opts;
9299 	uchar_t		*opt;
9300 	uint8_t		optval;
9301 	uint8_t		optlen;
9302 	intptr_t	code = 0;
9303 	ire_t		*ire;
9304 
9305 	ip2dbg(("ip_input_options\n"));
9306 	*errorp = 0;
9307 	for (optval = ipoptp_first(&opts, ipha);
9308 	    optval != IPOPT_EOL;
9309 	    optval = ipoptp_next(&opts)) {
9310 		opt = opts.ipoptp_cur;
9311 		optlen = opts.ipoptp_len;
9312 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9313 		    optval, optlen));
9314 		/*
9315 		 * Note: we need to verify the checksum before we
9316 		 * modify anything thus this routine only extracts the next
9317 		 * hop dst from any source route.
9318 		 */
9319 		switch (optval) {
9320 			uint32_t off;
9321 		case IPOPT_SSRR:
9322 		case IPOPT_LSRR:
9323 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9324 				if (optval == IPOPT_SSRR) {
9325 					ip1dbg(("ip_input_options: not next"
9326 					    " strict source route 0x%x\n",
9327 					    ntohl(dst)));
9328 					code = (char *)&ipha->ipha_dst -
9329 					    (char *)ipha;
9330 					goto param_prob; /* RouterReq's */
9331 				}
9332 				ip2dbg(("ip_input_options: "
9333 				    "not next source route 0x%x\n",
9334 				    ntohl(dst)));
9335 				break;
9336 			}
9337 
9338 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9339 				ip1dbg((
9340 				    "ip_input_options: bad option offset\n"));
9341 				code = (char *)&opt[IPOPT_OLEN] -
9342 				    (char *)ipha;
9343 				goto param_prob;
9344 			}
9345 			off = opt[IPOPT_OFFSET];
9346 			off--;
9347 		redo_srr:
9348 			if (optlen < IP_ADDR_LEN ||
9349 			    off > optlen - IP_ADDR_LEN) {
9350 				/* End of source route */
9351 				ip1dbg(("ip_input_options: end of SR\n"));
9352 				break;
9353 			}
9354 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9355 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9356 			    ntohl(dst)));
9357 
9358 			/*
9359 			 * Check if our address is present more than
9360 			 * once as consecutive hops in source route.
9361 			 * XXX verify per-interface ip_forwarding
9362 			 * for source route?
9363 			 */
9364 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9365 				off += IP_ADDR_LEN;
9366 				goto redo_srr;
9367 			}
9368 
9369 			if (dst == htonl(INADDR_LOOPBACK)) {
9370 				ip1dbg(("ip_input_options: loopback addr in "
9371 				    "source route!\n"));
9372 				goto bad_src_route;
9373 			}
9374 			/*
9375 			 * For strict: verify that dst is directly
9376 			 * reachable.
9377 			 */
9378 			if (optval == IPOPT_SSRR) {
9379 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9380 				    IRE_IF_ALL, NULL, ALL_ZONES,
9381 				    ira->ira_tsl,
9382 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9383 				    NULL);
9384 				if (ire == NULL) {
9385 					ip1dbg(("ip_input_options: SSRR not "
9386 					    "directly reachable: 0x%x\n",
9387 					    ntohl(dst)));
9388 					goto bad_src_route;
9389 				}
9390 				ire_refrele(ire);
9391 			}
9392 			/*
9393 			 * Defer update of the offset and the record route
9394 			 * until the packet is forwarded.
9395 			 */
9396 			break;
9397 		case IPOPT_RR:
9398 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9399 				ip1dbg((
9400 				    "ip_input_options: bad option offset\n"));
9401 				code = (char *)&opt[IPOPT_OLEN] -
9402 				    (char *)ipha;
9403 				goto param_prob;
9404 			}
9405 			break;
9406 		case IPOPT_TS:
9407 			/*
9408 			 * Verify that length >= 5 and that there is either
9409 			 * room for another timestamp or that the overflow
9410 			 * counter is not maxed out.
9411 			 */
9412 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9413 			if (optlen < IPOPT_MINLEN_IT) {
9414 				goto param_prob;
9415 			}
9416 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9417 				ip1dbg((
9418 				    "ip_input_options: bad option offset\n"));
9419 				code = (char *)&opt[IPOPT_OFFSET] -
9420 				    (char *)ipha;
9421 				goto param_prob;
9422 			}
9423 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9424 			case IPOPT_TS_TSONLY:
9425 				off = IPOPT_TS_TIMELEN;
9426 				break;
9427 			case IPOPT_TS_TSANDADDR:
9428 			case IPOPT_TS_PRESPEC:
9429 			case IPOPT_TS_PRESPEC_RFC791:
9430 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9431 				break;
9432 			default:
9433 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9434 				    (char *)ipha;
9435 				goto param_prob;
9436 			}
9437 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9438 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9439 				/*
9440 				 * No room and the overflow counter is 15
9441 				 * already.
9442 				 */
9443 				goto param_prob;
9444 			}
9445 			break;
9446 		}
9447 	}
9448 
9449 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9450 		return (dst);
9451 	}
9452 
9453 	ip1dbg(("ip_input_options: error processing IP options."));
9454 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9455 
9456 param_prob:
9457 	/* make sure we clear any indication of a hardware checksum */
9458 	DB_CKSUMFLAGS(mp) = 0;
9459 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9460 	icmp_param_problem(mp, (uint8_t)code, ira);
9461 	*errorp = -1;
9462 	return (dst);
9463 
9464 bad_src_route:
9465 	/* make sure we clear any indication of a hardware checksum */
9466 	DB_CKSUMFLAGS(mp) = 0;
9467 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9468 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9469 	*errorp = -1;
9470 	return (dst);
9471 }
9472 
9473 /*
9474  * IP & ICMP info in >=14 msg's ...
9475  *  - ip fixed part (mib2_ip_t)
9476  *  - icmp fixed part (mib2_icmp_t)
9477  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9478  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9479  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9480  *  - ipRouteAttributeTable (ip 102)	labeled routes
9481  *  - ip multicast membership (ip_member_t)
9482  *  - ip multicast source filtering (ip_grpsrc_t)
9483  *  - igmp fixed part (struct igmpstat)
9484  *  - multicast routing stats (struct mrtstat)
9485  *  - multicast routing vifs (array of struct vifctl)
9486  *  - multicast routing routes (array of struct mfcctl)
9487  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9488  *					One per ill plus one generic
9489  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9490  *					One per ill plus one generic
9491  *  - ipv6RouteEntry			all IPv6 IREs
9492  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9493  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9494  *  - ipv6AddrEntry			all IPv6 ipifs
9495  *  - ipv6 multicast membership (ipv6_member_t)
9496  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9497  *
9498  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9499  * already filled in by the caller.
9500  * Return value of 0 indicates that no messages were sent and caller
9501  * should free mpctl.
9502  */
9503 int
9504 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
9505 {
9506 	ip_stack_t *ipst;
9507 	sctp_stack_t *sctps;
9508 
9509 	if (q->q_next != NULL) {
9510 		ipst = ILLQ_TO_IPST(q);
9511 	} else {
9512 		ipst = CONNQ_TO_IPST(q);
9513 	}
9514 	ASSERT(ipst != NULL);
9515 	sctps = ipst->ips_netstack->netstack_sctp;
9516 
9517 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9518 		return (0);
9519 	}
9520 
9521 	/*
9522 	 * For the purposes of the (broken) packet shell use
9523 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9524 	 * to make TCP and UDP appear first in the list of mib items.
9525 	 * TBD: We could expand this and use it in netstat so that
9526 	 * the kernel doesn't have to produce large tables (connections,
9527 	 * routes, etc) when netstat only wants the statistics or a particular
9528 	 * table.
9529 	 */
9530 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9531 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9532 			return (1);
9533 		}
9534 	}
9535 
9536 	if (level != MIB2_TCP) {
9537 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
9538 			return (1);
9539 		}
9540 	}
9541 
9542 	if (level != MIB2_UDP) {
9543 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
9544 			return (1);
9545 		}
9546 	}
9547 
9548 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9549 	    ipst)) == NULL) {
9550 		return (1);
9551 	}
9552 
9553 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
9554 		return (1);
9555 	}
9556 
9557 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9558 		return (1);
9559 	}
9560 
9561 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9562 		return (1);
9563 	}
9564 
9565 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9566 		return (1);
9567 	}
9568 
9569 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9570 		return (1);
9571 	}
9572 
9573 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
9574 		return (1);
9575 	}
9576 
9577 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
9578 		return (1);
9579 	}
9580 
9581 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9582 		return (1);
9583 	}
9584 
9585 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9586 		return (1);
9587 	}
9588 
9589 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9590 		return (1);
9591 	}
9592 
9593 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9594 		return (1);
9595 	}
9596 
9597 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9598 		return (1);
9599 	}
9600 
9601 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9602 		return (1);
9603 	}
9604 
9605 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9606 	if (mpctl == NULL)
9607 		return (1);
9608 
9609 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9610 	if (mpctl == NULL)
9611 		return (1);
9612 
9613 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9614 		return (1);
9615 	}
9616 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9617 		return (1);
9618 	}
9619 	freemsg(mpctl);
9620 	return (1);
9621 }
9622 
9623 /* Get global (legacy) IPv4 statistics */
9624 static mblk_t *
9625 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9626     ip_stack_t *ipst)
9627 {
9628 	mib2_ip_t		old_ip_mib;
9629 	struct opthdr		*optp;
9630 	mblk_t			*mp2ctl;
9631 
9632 	/*
9633 	 * make a copy of the original message
9634 	 */
9635 	mp2ctl = copymsg(mpctl);
9636 
9637 	/* fixed length IP structure... */
9638 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9639 	optp->level = MIB2_IP;
9640 	optp->name = 0;
9641 	SET_MIB(old_ip_mib.ipForwarding,
9642 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9643 	SET_MIB(old_ip_mib.ipDefaultTTL,
9644 	    (uint32_t)ipst->ips_ip_def_ttl);
9645 	SET_MIB(old_ip_mib.ipReasmTimeout,
9646 	    ipst->ips_ip_reassembly_timeout);
9647 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9648 	    sizeof (mib2_ipAddrEntry_t));
9649 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9650 	    sizeof (mib2_ipRouteEntry_t));
9651 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9652 	    sizeof (mib2_ipNetToMediaEntry_t));
9653 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9654 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9655 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9656 	    sizeof (mib2_ipAttributeEntry_t));
9657 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9658 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9659 
9660 	/*
9661 	 * Grab the statistics from the new IP MIB
9662 	 */
9663 	SET_MIB(old_ip_mib.ipInReceives,
9664 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9665 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9666 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9667 	SET_MIB(old_ip_mib.ipForwDatagrams,
9668 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9669 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9670 	    ipmib->ipIfStatsInUnknownProtos);
9671 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9672 	SET_MIB(old_ip_mib.ipInDelivers,
9673 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9674 	SET_MIB(old_ip_mib.ipOutRequests,
9675 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9676 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9677 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9678 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9679 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9680 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9681 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9682 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9683 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9684 
9685 	/* ipRoutingDiscards is not being used */
9686 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9687 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9688 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9689 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9690 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9691 	    ipmib->ipIfStatsReasmDuplicates);
9692 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9693 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9694 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9695 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9696 	SET_MIB(old_ip_mib.rawipInOverflows,
9697 	    ipmib->rawipIfStatsInOverflows);
9698 
9699 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9700 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9701 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9702 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9703 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9704 	    ipmib->ipIfStatsOutSwitchIPVersion);
9705 
9706 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9707 	    (int)sizeof (old_ip_mib))) {
9708 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9709 		    (uint_t)sizeof (old_ip_mib)));
9710 	}
9711 
9712 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9713 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9714 	    (int)optp->level, (int)optp->name, (int)optp->len));
9715 	qreply(q, mpctl);
9716 	return (mp2ctl);
9717 }
9718 
9719 /* Per interface IPv4 statistics */
9720 static mblk_t *
9721 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9722 {
9723 	struct opthdr		*optp;
9724 	mblk_t			*mp2ctl;
9725 	ill_t			*ill;
9726 	ill_walk_context_t	ctx;
9727 	mblk_t			*mp_tail = NULL;
9728 	mib2_ipIfStatsEntry_t	global_ip_mib;
9729 
9730 	/*
9731 	 * Make a copy of the original message
9732 	 */
9733 	mp2ctl = copymsg(mpctl);
9734 
9735 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9736 	optp->level = MIB2_IP;
9737 	optp->name = MIB2_IP_TRAFFIC_STATS;
9738 	/* Include "unknown interface" ip_mib */
9739 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9740 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9741 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9742 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9743 	    (ipst->ips_ip_forwarding ? 1 : 2));
9744 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9745 	    (uint32_t)ipst->ips_ip_def_ttl);
9746 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9747 	    sizeof (mib2_ipIfStatsEntry_t));
9748 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9749 	    sizeof (mib2_ipAddrEntry_t));
9750 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9751 	    sizeof (mib2_ipRouteEntry_t));
9752 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9753 	    sizeof (mib2_ipNetToMediaEntry_t));
9754 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9755 	    sizeof (ip_member_t));
9756 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9757 	    sizeof (ip_grpsrc_t));
9758 
9759 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9760 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
9761 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9762 		    "failed to allocate %u bytes\n",
9763 		    (uint_t)sizeof (ipst->ips_ip_mib)));
9764 	}
9765 
9766 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9767 
9768 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9769 	ill = ILL_START_WALK_V4(&ctx, ipst);
9770 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9771 		ill->ill_ip_mib->ipIfStatsIfIndex =
9772 		    ill->ill_phyint->phyint_ifindex;
9773 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9774 		    (ipst->ips_ip_forwarding ? 1 : 2));
9775 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9776 		    (uint32_t)ipst->ips_ip_def_ttl);
9777 
9778 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9779 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9780 		    (char *)ill->ill_ip_mib,
9781 		    (int)sizeof (*ill->ill_ip_mib))) {
9782 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9783 			    "failed to allocate %u bytes\n",
9784 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9785 		}
9786 	}
9787 	rw_exit(&ipst->ips_ill_g_lock);
9788 
9789 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9790 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9791 	    "level %d, name %d, len %d\n",
9792 	    (int)optp->level, (int)optp->name, (int)optp->len));
9793 	qreply(q, mpctl);
9794 
9795 	if (mp2ctl == NULL)
9796 		return (NULL);
9797 
9798 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
9799 }
9800 
9801 /* Global IPv4 ICMP statistics */
9802 static mblk_t *
9803 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9804 {
9805 	struct opthdr		*optp;
9806 	mblk_t			*mp2ctl;
9807 
9808 	/*
9809 	 * Make a copy of the original message
9810 	 */
9811 	mp2ctl = copymsg(mpctl);
9812 
9813 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9814 	optp->level = MIB2_ICMP;
9815 	optp->name = 0;
9816 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9817 	    (int)sizeof (ipst->ips_icmp_mib))) {
9818 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9819 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9820 	}
9821 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9822 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9823 	    (int)optp->level, (int)optp->name, (int)optp->len));
9824 	qreply(q, mpctl);
9825 	return (mp2ctl);
9826 }
9827 
9828 /* Global IPv4 IGMP statistics */
9829 static mblk_t *
9830 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9831 {
9832 	struct opthdr		*optp;
9833 	mblk_t			*mp2ctl;
9834 
9835 	/*
9836 	 * make a copy of the original message
9837 	 */
9838 	mp2ctl = copymsg(mpctl);
9839 
9840 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9841 	optp->level = EXPER_IGMP;
9842 	optp->name = 0;
9843 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9844 	    (int)sizeof (ipst->ips_igmpstat))) {
9845 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9846 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9847 	}
9848 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9849 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9850 	    (int)optp->level, (int)optp->name, (int)optp->len));
9851 	qreply(q, mpctl);
9852 	return (mp2ctl);
9853 }
9854 
9855 /* Global IPv4 Multicast Routing statistics */
9856 static mblk_t *
9857 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9858 {
9859 	struct opthdr		*optp;
9860 	mblk_t			*mp2ctl;
9861 
9862 	/*
9863 	 * make a copy of the original message
9864 	 */
9865 	mp2ctl = copymsg(mpctl);
9866 
9867 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9868 	optp->level = EXPER_DVMRP;
9869 	optp->name = 0;
9870 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9871 		ip0dbg(("ip_mroute_stats: failed\n"));
9872 	}
9873 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9874 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9875 	    (int)optp->level, (int)optp->name, (int)optp->len));
9876 	qreply(q, mpctl);
9877 	return (mp2ctl);
9878 }
9879 
9880 /* IPv4 address information */
9881 static mblk_t *
9882 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9883 {
9884 	struct opthdr		*optp;
9885 	mblk_t			*mp2ctl;
9886 	mblk_t			*mp_tail = NULL;
9887 	ill_t			*ill;
9888 	ipif_t			*ipif;
9889 	uint_t			bitval;
9890 	mib2_ipAddrEntry_t	mae;
9891 	zoneid_t		zoneid;
9892 	ill_walk_context_t ctx;
9893 
9894 	/*
9895 	 * make a copy of the original message
9896 	 */
9897 	mp2ctl = copymsg(mpctl);
9898 
9899 	/* ipAddrEntryTable */
9900 
9901 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9902 	optp->level = MIB2_IP;
9903 	optp->name = MIB2_IP_ADDR;
9904 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9905 
9906 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9907 	ill = ILL_START_WALK_V4(&ctx, ipst);
9908 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9909 		for (ipif = ill->ill_ipif; ipif != NULL;
9910 		    ipif = ipif->ipif_next) {
9911 			if (ipif->ipif_zoneid != zoneid &&
9912 			    ipif->ipif_zoneid != ALL_ZONES)
9913 				continue;
9914 			/* Sum of count from dead IRE_LO* and our current */
9915 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9916 			if (ipif->ipif_ire_local != NULL) {
9917 				mae.ipAdEntInfo.ae_ibcnt +=
9918 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9919 			}
9920 			mae.ipAdEntInfo.ae_obcnt = 0;
9921 			mae.ipAdEntInfo.ae_focnt = 0;
9922 
9923 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
9924 			    OCTET_LENGTH);
9925 			mae.ipAdEntIfIndex.o_length =
9926 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
9927 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
9928 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
9929 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
9930 			mae.ipAdEntInfo.ae_subnet_len =
9931 			    ip_mask_to_plen(ipif->ipif_net_mask);
9932 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
9933 			for (bitval = 1;
9934 			    bitval &&
9935 			    !(bitval & ipif->ipif_brd_addr);
9936 			    bitval <<= 1)
9937 				noop;
9938 			mae.ipAdEntBcastAddr = bitval;
9939 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
9940 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
9941 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
9942 			mae.ipAdEntInfo.ae_broadcast_addr =
9943 			    ipif->ipif_brd_addr;
9944 			mae.ipAdEntInfo.ae_pp_dst_addr =
9945 			    ipif->ipif_pp_dst_addr;
9946 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
9947 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
9948 			mae.ipAdEntRetransmitTime =
9949 			    ill->ill_reachable_retrans_time;
9950 
9951 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9952 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
9953 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
9954 				    "allocate %u bytes\n",
9955 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
9956 			}
9957 		}
9958 	}
9959 	rw_exit(&ipst->ips_ill_g_lock);
9960 
9961 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9962 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
9963 	    (int)optp->level, (int)optp->name, (int)optp->len));
9964 	qreply(q, mpctl);
9965 	return (mp2ctl);
9966 }
9967 
9968 /* IPv6 address information */
9969 static mblk_t *
9970 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9971 {
9972 	struct opthdr		*optp;
9973 	mblk_t			*mp2ctl;
9974 	mblk_t			*mp_tail = NULL;
9975 	ill_t			*ill;
9976 	ipif_t			*ipif;
9977 	mib2_ipv6AddrEntry_t	mae6;
9978 	zoneid_t		zoneid;
9979 	ill_walk_context_t	ctx;
9980 
9981 	/*
9982 	 * make a copy of the original message
9983 	 */
9984 	mp2ctl = copymsg(mpctl);
9985 
9986 	/* ipv6AddrEntryTable */
9987 
9988 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9989 	optp->level = MIB2_IP6;
9990 	optp->name = MIB2_IP6_ADDR;
9991 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9992 
9993 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9994 	ill = ILL_START_WALK_V6(&ctx, ipst);
9995 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9996 		for (ipif = ill->ill_ipif; ipif != NULL;
9997 		    ipif = ipif->ipif_next) {
9998 			if (ipif->ipif_zoneid != zoneid &&
9999 			    ipif->ipif_zoneid != ALL_ZONES)
10000 				continue;
10001 			/* Sum of count from dead IRE_LO* and our current */
10002 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10003 			if (ipif->ipif_ire_local != NULL) {
10004 				mae6.ipv6AddrInfo.ae_ibcnt +=
10005 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10006 			}
10007 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10008 			mae6.ipv6AddrInfo.ae_focnt = 0;
10009 
10010 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10011 			    OCTET_LENGTH);
10012 			mae6.ipv6AddrIfIndex.o_length =
10013 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10014 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10015 			mae6.ipv6AddrPfxLength =
10016 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10017 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10018 			mae6.ipv6AddrInfo.ae_subnet_len =
10019 			    mae6.ipv6AddrPfxLength;
10020 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10021 
10022 			/* Type: stateless(1), stateful(2), unknown(3) */
10023 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10024 				mae6.ipv6AddrType = 1;
10025 			else
10026 				mae6.ipv6AddrType = 2;
10027 			/* Anycast: true(1), false(2) */
10028 			if (ipif->ipif_flags & IPIF_ANYCAST)
10029 				mae6.ipv6AddrAnycastFlag = 1;
10030 			else
10031 				mae6.ipv6AddrAnycastFlag = 2;
10032 
10033 			/*
10034 			 * Address status: preferred(1), deprecated(2),
10035 			 * invalid(3), inaccessible(4), unknown(5)
10036 			 */
10037 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10038 				mae6.ipv6AddrStatus = 3;
10039 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10040 				mae6.ipv6AddrStatus = 2;
10041 			else
10042 				mae6.ipv6AddrStatus = 1;
10043 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10044 			mae6.ipv6AddrInfo.ae_metric  =
10045 			    ipif->ipif_ill->ill_metric;
10046 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10047 			    ipif->ipif_v6pp_dst_addr;
10048 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10049 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10050 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10051 			mae6.ipv6AddrIdentifier = ill->ill_token;
10052 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10053 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10054 			mae6.ipv6AddrRetransmitTime =
10055 			    ill->ill_reachable_retrans_time;
10056 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10057 			    (char *)&mae6,
10058 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
10059 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10060 				    "allocate %u bytes\n",
10061 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
10062 			}
10063 		}
10064 	}
10065 	rw_exit(&ipst->ips_ill_g_lock);
10066 
10067 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10068 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10069 	    (int)optp->level, (int)optp->name, (int)optp->len));
10070 	qreply(q, mpctl);
10071 	return (mp2ctl);
10072 }
10073 
10074 /* IPv4 multicast group membership. */
10075 static mblk_t *
10076 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10077 {
10078 	struct opthdr		*optp;
10079 	mblk_t			*mp2ctl;
10080 	ill_t			*ill;
10081 	ipif_t			*ipif;
10082 	ilm_t			*ilm;
10083 	ip_member_t		ipm;
10084 	mblk_t			*mp_tail = NULL;
10085 	ill_walk_context_t	ctx;
10086 	zoneid_t		zoneid;
10087 
10088 	/*
10089 	 * make a copy of the original message
10090 	 */
10091 	mp2ctl = copymsg(mpctl);
10092 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10093 
10094 	/* ipGroupMember table */
10095 	optp = (struct opthdr *)&mpctl->b_rptr[
10096 	    sizeof (struct T_optmgmt_ack)];
10097 	optp->level = MIB2_IP;
10098 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10099 
10100 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10101 	ill = ILL_START_WALK_V4(&ctx, ipst);
10102 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10103 		/* Make sure the ill isn't going away. */
10104 		if (!ill_check_and_refhold(ill))
10105 			continue;
10106 		rw_exit(&ipst->ips_ill_g_lock);
10107 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10108 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10109 			if (ilm->ilm_zoneid != zoneid &&
10110 			    ilm->ilm_zoneid != ALL_ZONES)
10111 				continue;
10112 
10113 			/* Is there an ipif for ilm_ifaddr? */
10114 			for (ipif = ill->ill_ipif; ipif != NULL;
10115 			    ipif = ipif->ipif_next) {
10116 				if (!IPIF_IS_CONDEMNED(ipif) &&
10117 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10118 				    ilm->ilm_ifaddr != INADDR_ANY)
10119 					break;
10120 			}
10121 			if (ipif != NULL) {
10122 				ipif_get_name(ipif,
10123 				    ipm.ipGroupMemberIfIndex.o_bytes,
10124 				    OCTET_LENGTH);
10125 			} else {
10126 				ill_get_name(ill,
10127 				    ipm.ipGroupMemberIfIndex.o_bytes,
10128 				    OCTET_LENGTH);
10129 			}
10130 			ipm.ipGroupMemberIfIndex.o_length =
10131 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10132 
10133 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10134 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10135 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10136 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10137 			    (char *)&ipm, (int)sizeof (ipm))) {
10138 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10139 				    "failed to allocate %u bytes\n",
10140 				    (uint_t)sizeof (ipm)));
10141 			}
10142 		}
10143 		rw_exit(&ill->ill_mcast_lock);
10144 		ill_refrele(ill);
10145 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10146 	}
10147 	rw_exit(&ipst->ips_ill_g_lock);
10148 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10149 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10150 	    (int)optp->level, (int)optp->name, (int)optp->len));
10151 	qreply(q, mpctl);
10152 	return (mp2ctl);
10153 }
10154 
10155 /* IPv6 multicast group membership. */
10156 static mblk_t *
10157 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10158 {
10159 	struct opthdr		*optp;
10160 	mblk_t			*mp2ctl;
10161 	ill_t			*ill;
10162 	ilm_t			*ilm;
10163 	ipv6_member_t		ipm6;
10164 	mblk_t			*mp_tail = NULL;
10165 	ill_walk_context_t	ctx;
10166 	zoneid_t		zoneid;
10167 
10168 	/*
10169 	 * make a copy of the original message
10170 	 */
10171 	mp2ctl = copymsg(mpctl);
10172 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10173 
10174 	/* ip6GroupMember table */
10175 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10176 	optp->level = MIB2_IP6;
10177 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10178 
10179 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10180 	ill = ILL_START_WALK_V6(&ctx, ipst);
10181 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10182 		/* Make sure the ill isn't going away. */
10183 		if (!ill_check_and_refhold(ill))
10184 			continue;
10185 		rw_exit(&ipst->ips_ill_g_lock);
10186 		/*
10187 		 * Normally we don't have any members on under IPMP interfaces.
10188 		 * We report them as a debugging aid.
10189 		 */
10190 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10191 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10192 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10193 			if (ilm->ilm_zoneid != zoneid &&
10194 			    ilm->ilm_zoneid != ALL_ZONES)
10195 				continue;	/* not this zone */
10196 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10197 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10198 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10199 			if (!snmp_append_data2(mpctl->b_cont,
10200 			    &mp_tail,
10201 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10202 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10203 				    "failed to allocate %u bytes\n",
10204 				    (uint_t)sizeof (ipm6)));
10205 			}
10206 		}
10207 		rw_exit(&ill->ill_mcast_lock);
10208 		ill_refrele(ill);
10209 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10210 	}
10211 	rw_exit(&ipst->ips_ill_g_lock);
10212 
10213 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10214 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10215 	    (int)optp->level, (int)optp->name, (int)optp->len));
10216 	qreply(q, mpctl);
10217 	return (mp2ctl);
10218 }
10219 
10220 /* IP multicast filtered sources */
10221 static mblk_t *
10222 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10223 {
10224 	struct opthdr		*optp;
10225 	mblk_t			*mp2ctl;
10226 	ill_t			*ill;
10227 	ipif_t			*ipif;
10228 	ilm_t			*ilm;
10229 	ip_grpsrc_t		ips;
10230 	mblk_t			*mp_tail = NULL;
10231 	ill_walk_context_t	ctx;
10232 	zoneid_t		zoneid;
10233 	int			i;
10234 	slist_t			*sl;
10235 
10236 	/*
10237 	 * make a copy of the original message
10238 	 */
10239 	mp2ctl = copymsg(mpctl);
10240 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10241 
10242 	/* ipGroupSource table */
10243 	optp = (struct opthdr *)&mpctl->b_rptr[
10244 	    sizeof (struct T_optmgmt_ack)];
10245 	optp->level = MIB2_IP;
10246 	optp->name = EXPER_IP_GROUP_SOURCES;
10247 
10248 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10249 	ill = ILL_START_WALK_V4(&ctx, ipst);
10250 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10251 		/* Make sure the ill isn't going away. */
10252 		if (!ill_check_and_refhold(ill))
10253 			continue;
10254 		rw_exit(&ipst->ips_ill_g_lock);
10255 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10256 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10257 			sl = ilm->ilm_filter;
10258 			if (ilm->ilm_zoneid != zoneid &&
10259 			    ilm->ilm_zoneid != ALL_ZONES)
10260 				continue;
10261 			if (SLIST_IS_EMPTY(sl))
10262 				continue;
10263 
10264 			/* Is there an ipif for ilm_ifaddr? */
10265 			for (ipif = ill->ill_ipif; ipif != NULL;
10266 			    ipif = ipif->ipif_next) {
10267 				if (!IPIF_IS_CONDEMNED(ipif) &&
10268 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10269 				    ilm->ilm_ifaddr != INADDR_ANY)
10270 					break;
10271 			}
10272 			if (ipif != NULL) {
10273 				ipif_get_name(ipif,
10274 				    ips.ipGroupSourceIfIndex.o_bytes,
10275 				    OCTET_LENGTH);
10276 			} else {
10277 				ill_get_name(ill,
10278 				    ips.ipGroupSourceIfIndex.o_bytes,
10279 				    OCTET_LENGTH);
10280 			}
10281 			ips.ipGroupSourceIfIndex.o_length =
10282 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10283 
10284 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10285 			for (i = 0; i < sl->sl_numsrc; i++) {
10286 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10287 					continue;
10288 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10289 				    ips.ipGroupSourceAddress);
10290 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10291 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10292 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10293 					    " failed to allocate %u bytes\n",
10294 					    (uint_t)sizeof (ips)));
10295 				}
10296 			}
10297 		}
10298 		rw_exit(&ill->ill_mcast_lock);
10299 		ill_refrele(ill);
10300 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10301 	}
10302 	rw_exit(&ipst->ips_ill_g_lock);
10303 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10304 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10305 	    (int)optp->level, (int)optp->name, (int)optp->len));
10306 	qreply(q, mpctl);
10307 	return (mp2ctl);
10308 }
10309 
10310 /* IPv6 multicast filtered sources. */
10311 static mblk_t *
10312 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10313 {
10314 	struct opthdr		*optp;
10315 	mblk_t			*mp2ctl;
10316 	ill_t			*ill;
10317 	ilm_t			*ilm;
10318 	ipv6_grpsrc_t		ips6;
10319 	mblk_t			*mp_tail = NULL;
10320 	ill_walk_context_t	ctx;
10321 	zoneid_t		zoneid;
10322 	int			i;
10323 	slist_t			*sl;
10324 
10325 	/*
10326 	 * make a copy of the original message
10327 	 */
10328 	mp2ctl = copymsg(mpctl);
10329 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10330 
10331 	/* ip6GroupMember table */
10332 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10333 	optp->level = MIB2_IP6;
10334 	optp->name = EXPER_IP6_GROUP_SOURCES;
10335 
10336 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10337 	ill = ILL_START_WALK_V6(&ctx, ipst);
10338 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10339 		/* Make sure the ill isn't going away. */
10340 		if (!ill_check_and_refhold(ill))
10341 			continue;
10342 		rw_exit(&ipst->ips_ill_g_lock);
10343 		/*
10344 		 * Normally we don't have any members on under IPMP interfaces.
10345 		 * We report them as a debugging aid.
10346 		 */
10347 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10348 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10349 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10350 			sl = ilm->ilm_filter;
10351 			if (ilm->ilm_zoneid != zoneid &&
10352 			    ilm->ilm_zoneid != ALL_ZONES)
10353 				continue;
10354 			if (SLIST_IS_EMPTY(sl))
10355 				continue;
10356 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10357 			for (i = 0; i < sl->sl_numsrc; i++) {
10358 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10359 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10360 				    (char *)&ips6, (int)sizeof (ips6))) {
10361 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10362 					    "group_src: failed to allocate "
10363 					    "%u bytes\n",
10364 					    (uint_t)sizeof (ips6)));
10365 				}
10366 			}
10367 		}
10368 		rw_exit(&ill->ill_mcast_lock);
10369 		ill_refrele(ill);
10370 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10371 	}
10372 	rw_exit(&ipst->ips_ill_g_lock);
10373 
10374 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10375 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10376 	    (int)optp->level, (int)optp->name, (int)optp->len));
10377 	qreply(q, mpctl);
10378 	return (mp2ctl);
10379 }
10380 
10381 /* Multicast routing virtual interface table. */
10382 static mblk_t *
10383 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10384 {
10385 	struct opthdr		*optp;
10386 	mblk_t			*mp2ctl;
10387 
10388 	/*
10389 	 * make a copy of the original message
10390 	 */
10391 	mp2ctl = copymsg(mpctl);
10392 
10393 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10394 	optp->level = EXPER_DVMRP;
10395 	optp->name = EXPER_DVMRP_VIF;
10396 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10397 		ip0dbg(("ip_mroute_vif: failed\n"));
10398 	}
10399 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10400 	ip3dbg(("ip_snmp_get_mib2_virt_multi: 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 table. */
10407 static mblk_t *
10408 ip_snmp_get_mib2_multi_rtable(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_MRT;
10421 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10422 		ip0dbg(("ip_mroute_mrt: failed\n"));
10423 	}
10424 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10425 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: 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 /*
10432  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10433  * in one IRE walk.
10434  */
10435 static mblk_t *
10436 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10437     ip_stack_t *ipst)
10438 {
10439 	struct opthdr	*optp;
10440 	mblk_t		*mp2ctl;	/* Returned */
10441 	mblk_t		*mp3ctl;	/* nettomedia */
10442 	mblk_t		*mp4ctl;	/* routeattrs */
10443 	iproutedata_t	ird;
10444 	zoneid_t	zoneid;
10445 
10446 	/*
10447 	 * make copies of the original message
10448 	 *	- mp2ctl is returned unchanged to the caller for his use
10449 	 *	- mpctl is sent upstream as ipRouteEntryTable
10450 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10451 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10452 	 */
10453 	mp2ctl = copymsg(mpctl);
10454 	mp3ctl = copymsg(mpctl);
10455 	mp4ctl = copymsg(mpctl);
10456 	if (mp3ctl == NULL || mp4ctl == NULL) {
10457 		freemsg(mp4ctl);
10458 		freemsg(mp3ctl);
10459 		freemsg(mp2ctl);
10460 		freemsg(mpctl);
10461 		return (NULL);
10462 	}
10463 
10464 	bzero(&ird, sizeof (ird));
10465 
10466 	ird.ird_route.lp_head = mpctl->b_cont;
10467 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10468 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10469 	/*
10470 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10471 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10472 	 * intended a temporary solution until a proper MIB API is provided
10473 	 * that provides complete filtering/caller-opt-in.
10474 	 */
10475 	if (level == EXPER_IP_AND_ALL_IRES)
10476 		ird.ird_flags |= IRD_REPORT_ALL;
10477 
10478 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10479 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10480 
10481 	/* ipRouteEntryTable in mpctl */
10482 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10483 	optp->level = MIB2_IP;
10484 	optp->name = MIB2_IP_ROUTE;
10485 	optp->len = msgdsize(ird.ird_route.lp_head);
10486 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10487 	    (int)optp->level, (int)optp->name, (int)optp->len));
10488 	qreply(q, mpctl);
10489 
10490 	/* ipNetToMediaEntryTable in mp3ctl */
10491 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10492 
10493 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10494 	optp->level = MIB2_IP;
10495 	optp->name = MIB2_IP_MEDIA;
10496 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10497 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10498 	    (int)optp->level, (int)optp->name, (int)optp->len));
10499 	qreply(q, mp3ctl);
10500 
10501 	/* ipRouteAttributeTable in mp4ctl */
10502 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10503 	optp->level = MIB2_IP;
10504 	optp->name = EXPER_IP_RTATTR;
10505 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10506 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10507 	    (int)optp->level, (int)optp->name, (int)optp->len));
10508 	if (optp->len == 0)
10509 		freemsg(mp4ctl);
10510 	else
10511 		qreply(q, mp4ctl);
10512 
10513 	return (mp2ctl);
10514 }
10515 
10516 /*
10517  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10518  * ipv6NetToMediaEntryTable in an NDP walk.
10519  */
10520 static mblk_t *
10521 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10522     ip_stack_t *ipst)
10523 {
10524 	struct opthdr	*optp;
10525 	mblk_t		*mp2ctl;	/* Returned */
10526 	mblk_t		*mp3ctl;	/* nettomedia */
10527 	mblk_t		*mp4ctl;	/* routeattrs */
10528 	iproutedata_t	ird;
10529 	zoneid_t	zoneid;
10530 
10531 	/*
10532 	 * make copies of the original message
10533 	 *	- mp2ctl is returned unchanged to the caller for his use
10534 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10535 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10536 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10537 	 */
10538 	mp2ctl = copymsg(mpctl);
10539 	mp3ctl = copymsg(mpctl);
10540 	mp4ctl = copymsg(mpctl);
10541 	if (mp3ctl == NULL || mp4ctl == NULL) {
10542 		freemsg(mp4ctl);
10543 		freemsg(mp3ctl);
10544 		freemsg(mp2ctl);
10545 		freemsg(mpctl);
10546 		return (NULL);
10547 	}
10548 
10549 	bzero(&ird, sizeof (ird));
10550 
10551 	ird.ird_route.lp_head = mpctl->b_cont;
10552 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10553 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10554 	/*
10555 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10556 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10557 	 * intended a temporary solution until a proper MIB API is provided
10558 	 * that provides complete filtering/caller-opt-in.
10559 	 */
10560 	if (level == EXPER_IP_AND_ALL_IRES)
10561 		ird.ird_flags |= IRD_REPORT_ALL;
10562 
10563 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10564 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10565 
10566 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10567 	optp->level = MIB2_IP6;
10568 	optp->name = MIB2_IP6_ROUTE;
10569 	optp->len = msgdsize(ird.ird_route.lp_head);
10570 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10571 	    (int)optp->level, (int)optp->name, (int)optp->len));
10572 	qreply(q, mpctl);
10573 
10574 	/* ipv6NetToMediaEntryTable in mp3ctl */
10575 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10576 
10577 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10578 	optp->level = MIB2_IP6;
10579 	optp->name = MIB2_IP6_MEDIA;
10580 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10581 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10582 	    (int)optp->level, (int)optp->name, (int)optp->len));
10583 	qreply(q, mp3ctl);
10584 
10585 	/* ipv6RouteAttributeTable in mp4ctl */
10586 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10587 	optp->level = MIB2_IP6;
10588 	optp->name = EXPER_IP_RTATTR;
10589 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10590 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10591 	    (int)optp->level, (int)optp->name, (int)optp->len));
10592 	if (optp->len == 0)
10593 		freemsg(mp4ctl);
10594 	else
10595 		qreply(q, mp4ctl);
10596 
10597 	return (mp2ctl);
10598 }
10599 
10600 /*
10601  * IPv6 mib: One per ill
10602  */
10603 static mblk_t *
10604 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10605 {
10606 	struct opthdr		*optp;
10607 	mblk_t			*mp2ctl;
10608 	ill_t			*ill;
10609 	ill_walk_context_t	ctx;
10610 	mblk_t			*mp_tail = NULL;
10611 
10612 	/*
10613 	 * Make a copy of the original message
10614 	 */
10615 	mp2ctl = copymsg(mpctl);
10616 
10617 	/* fixed length IPv6 structure ... */
10618 
10619 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10620 	optp->level = MIB2_IP6;
10621 	optp->name = 0;
10622 	/* Include "unknown interface" ip6_mib */
10623 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10624 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10625 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10626 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10627 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10628 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10629 	    ipst->ips_ipv6_def_hops);
10630 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10631 	    sizeof (mib2_ipIfStatsEntry_t));
10632 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10633 	    sizeof (mib2_ipv6AddrEntry_t));
10634 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10635 	    sizeof (mib2_ipv6RouteEntry_t));
10636 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10637 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10638 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10639 	    sizeof (ipv6_member_t));
10640 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10641 	    sizeof (ipv6_grpsrc_t));
10642 
10643 	/*
10644 	 * Synchronize 64- and 32-bit counters
10645 	 */
10646 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10647 	    ipIfStatsHCInReceives);
10648 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10649 	    ipIfStatsHCInDelivers);
10650 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10651 	    ipIfStatsHCOutRequests);
10652 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10653 	    ipIfStatsHCOutForwDatagrams);
10654 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10655 	    ipIfStatsHCOutMcastPkts);
10656 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10657 	    ipIfStatsHCInMcastPkts);
10658 
10659 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10660 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
10661 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10662 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
10663 	}
10664 
10665 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10666 	ill = ILL_START_WALK_V6(&ctx, ipst);
10667 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10668 		ill->ill_ip_mib->ipIfStatsIfIndex =
10669 		    ill->ill_phyint->phyint_ifindex;
10670 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10671 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10672 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10673 		    ill->ill_max_hops);
10674 
10675 		/*
10676 		 * Synchronize 64- and 32-bit counters
10677 		 */
10678 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10679 		    ipIfStatsHCInReceives);
10680 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10681 		    ipIfStatsHCInDelivers);
10682 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10683 		    ipIfStatsHCOutRequests);
10684 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10685 		    ipIfStatsHCOutForwDatagrams);
10686 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10687 		    ipIfStatsHCOutMcastPkts);
10688 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10689 		    ipIfStatsHCInMcastPkts);
10690 
10691 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10692 		    (char *)ill->ill_ip_mib,
10693 		    (int)sizeof (*ill->ill_ip_mib))) {
10694 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10695 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
10696 		}
10697 	}
10698 	rw_exit(&ipst->ips_ill_g_lock);
10699 
10700 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10701 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10702 	    (int)optp->level, (int)optp->name, (int)optp->len));
10703 	qreply(q, mpctl);
10704 	return (mp2ctl);
10705 }
10706 
10707 /*
10708  * ICMPv6 mib: One per ill
10709  */
10710 static mblk_t *
10711 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10712 {
10713 	struct opthdr		*optp;
10714 	mblk_t			*mp2ctl;
10715 	ill_t			*ill;
10716 	ill_walk_context_t	ctx;
10717 	mblk_t			*mp_tail = NULL;
10718 	/*
10719 	 * Make a copy of the original message
10720 	 */
10721 	mp2ctl = copymsg(mpctl);
10722 
10723 	/* fixed length ICMPv6 structure ... */
10724 
10725 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10726 	optp->level = MIB2_ICMP6;
10727 	optp->name = 0;
10728 	/* Include "unknown interface" icmp6_mib */
10729 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10730 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10731 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10732 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10733 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10734 	    (char *)&ipst->ips_icmp6_mib,
10735 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10736 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10737 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10738 	}
10739 
10740 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10741 	ill = ILL_START_WALK_V6(&ctx, ipst);
10742 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10743 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10744 		    ill->ill_phyint->phyint_ifindex;
10745 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10746 		    (char *)ill->ill_icmp6_mib,
10747 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10748 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10749 			    "%u bytes\n",
10750 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10751 		}
10752 	}
10753 	rw_exit(&ipst->ips_ill_g_lock);
10754 
10755 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10756 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10757 	    (int)optp->level, (int)optp->name, (int)optp->len));
10758 	qreply(q, mpctl);
10759 	return (mp2ctl);
10760 }
10761 
10762 /*
10763  * ire_walk routine to create both ipRouteEntryTable and
10764  * ipRouteAttributeTable in one IRE walk
10765  */
10766 static void
10767 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10768 {
10769 	ill_t				*ill;
10770 	mib2_ipRouteEntry_t		*re;
10771 	mib2_ipAttributeEntry_t		iaes;
10772 	tsol_ire_gw_secattr_t		*attrp;
10773 	tsol_gc_t			*gc = NULL;
10774 	tsol_gcgrp_t			*gcgrp = NULL;
10775 	ip_stack_t			*ipst = ire->ire_ipst;
10776 
10777 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10778 
10779 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10780 		if (ire->ire_testhidden)
10781 			return;
10782 		if (ire->ire_type & IRE_IF_CLONE)
10783 			return;
10784 	}
10785 
10786 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10787 		return;
10788 
10789 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10790 		mutex_enter(&attrp->igsa_lock);
10791 		if ((gc = attrp->igsa_gc) != NULL) {
10792 			gcgrp = gc->gc_grp;
10793 			ASSERT(gcgrp != NULL);
10794 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10795 		}
10796 		mutex_exit(&attrp->igsa_lock);
10797 	}
10798 	/*
10799 	 * Return all IRE types for route table... let caller pick and choose
10800 	 */
10801 	re->ipRouteDest = ire->ire_addr;
10802 	ill = ire->ire_ill;
10803 	re->ipRouteIfIndex.o_length = 0;
10804 	if (ill != NULL) {
10805 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10806 		re->ipRouteIfIndex.o_length =
10807 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10808 	}
10809 	re->ipRouteMetric1 = -1;
10810 	re->ipRouteMetric2 = -1;
10811 	re->ipRouteMetric3 = -1;
10812 	re->ipRouteMetric4 = -1;
10813 
10814 	re->ipRouteNextHop = ire->ire_gateway_addr;
10815 	/* indirect(4), direct(3), or invalid(2) */
10816 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10817 		re->ipRouteType = 2;
10818 	else if (ire->ire_type & IRE_ONLINK)
10819 		re->ipRouteType = 3;
10820 	else
10821 		re->ipRouteType = 4;
10822 
10823 	re->ipRouteProto = -1;
10824 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10825 	re->ipRouteMask = ire->ire_mask;
10826 	re->ipRouteMetric5 = -1;
10827 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10828 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10829 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10830 
10831 	re->ipRouteInfo.re_frag_flag	= 0;
10832 	re->ipRouteInfo.re_rtt		= 0;
10833 	re->ipRouteInfo.re_src_addr	= 0;
10834 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
10835 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10836 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10837 	re->ipRouteInfo.re_flags	= ire->ire_flags;
10838 
10839 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10840 	if (ire->ire_type & IRE_INTERFACE) {
10841 		ire_t *child;
10842 
10843 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10844 		child = ire->ire_dep_children;
10845 		while (child != NULL) {
10846 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10847 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10848 			child = child->ire_dep_sib_next;
10849 		}
10850 		rw_exit(&ipst->ips_ire_dep_lock);
10851 	}
10852 
10853 	if (ire->ire_flags & RTF_DYNAMIC) {
10854 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10855 	} else {
10856 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
10857 	}
10858 
10859 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10860 	    (char *)re, (int)sizeof (*re))) {
10861 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
10862 		    (uint_t)sizeof (*re)));
10863 	}
10864 
10865 	if (gc != NULL) {
10866 		iaes.iae_routeidx = ird->ird_idx;
10867 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10868 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10869 
10870 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10871 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10872 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
10873 			    "bytes\n", (uint_t)sizeof (iaes)));
10874 		}
10875 	}
10876 
10877 	/* bump route index for next pass */
10878 	ird->ird_idx++;
10879 
10880 	kmem_free(re, sizeof (*re));
10881 	if (gcgrp != NULL)
10882 		rw_exit(&gcgrp->gcgrp_rwlock);
10883 }
10884 
10885 /*
10886  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
10887  */
10888 static void
10889 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
10890 {
10891 	ill_t				*ill;
10892 	mib2_ipv6RouteEntry_t		*re;
10893 	mib2_ipAttributeEntry_t		iaes;
10894 	tsol_ire_gw_secattr_t		*attrp;
10895 	tsol_gc_t			*gc = NULL;
10896 	tsol_gcgrp_t			*gcgrp = NULL;
10897 	ip_stack_t			*ipst = ire->ire_ipst;
10898 
10899 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
10900 
10901 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10902 		if (ire->ire_testhidden)
10903 			return;
10904 		if (ire->ire_type & IRE_IF_CLONE)
10905 			return;
10906 	}
10907 
10908 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10909 		return;
10910 
10911 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10912 		mutex_enter(&attrp->igsa_lock);
10913 		if ((gc = attrp->igsa_gc) != NULL) {
10914 			gcgrp = gc->gc_grp;
10915 			ASSERT(gcgrp != NULL);
10916 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10917 		}
10918 		mutex_exit(&attrp->igsa_lock);
10919 	}
10920 	/*
10921 	 * Return all IRE types for route table... let caller pick and choose
10922 	 */
10923 	re->ipv6RouteDest = ire->ire_addr_v6;
10924 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
10925 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
10926 	re->ipv6RouteIfIndex.o_length = 0;
10927 	ill = ire->ire_ill;
10928 	if (ill != NULL) {
10929 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
10930 		re->ipv6RouteIfIndex.o_length =
10931 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
10932 	}
10933 
10934 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
10935 
10936 	mutex_enter(&ire->ire_lock);
10937 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
10938 	mutex_exit(&ire->ire_lock);
10939 
10940 	/* remote(4), local(3), or discard(2) */
10941 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10942 		re->ipv6RouteType = 2;
10943 	else if (ire->ire_type & IRE_ONLINK)
10944 		re->ipv6RouteType = 3;
10945 	else
10946 		re->ipv6RouteType = 4;
10947 
10948 	re->ipv6RouteProtocol	= -1;
10949 	re->ipv6RoutePolicy	= 0;
10950 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
10951 	re->ipv6RouteNextHopRDI	= 0;
10952 	re->ipv6RouteWeight	= 0;
10953 	re->ipv6RouteMetric	= 0;
10954 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10955 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
10956 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10957 
10958 	re->ipv6RouteInfo.re_frag_flag	= 0;
10959 	re->ipv6RouteInfo.re_rtt	= 0;
10960 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
10961 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10962 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10963 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
10964 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
10965 
10966 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10967 	if (ire->ire_type & IRE_INTERFACE) {
10968 		ire_t *child;
10969 
10970 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10971 		child = ire->ire_dep_children;
10972 		while (child != NULL) {
10973 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
10974 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10975 			child = child->ire_dep_sib_next;
10976 		}
10977 		rw_exit(&ipst->ips_ire_dep_lock);
10978 	}
10979 	if (ire->ire_flags & RTF_DYNAMIC) {
10980 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10981 	} else {
10982 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
10983 	}
10984 
10985 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10986 	    (char *)re, (int)sizeof (*re))) {
10987 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
10988 		    (uint_t)sizeof (*re)));
10989 	}
10990 
10991 	if (gc != NULL) {
10992 		iaes.iae_routeidx = ird->ird_idx;
10993 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10994 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10995 
10996 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10997 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10998 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
10999 			    "bytes\n", (uint_t)sizeof (iaes)));
11000 		}
11001 	}
11002 
11003 	/* bump route index for next pass */
11004 	ird->ird_idx++;
11005 
11006 	kmem_free(re, sizeof (*re));
11007 	if (gcgrp != NULL)
11008 		rw_exit(&gcgrp->gcgrp_rwlock);
11009 }
11010 
11011 /*
11012  * ncec_walk routine to create ipv6NetToMediaEntryTable
11013  */
11014 static int
11015 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11016 {
11017 	ill_t				*ill;
11018 	mib2_ipv6NetToMediaEntry_t	ntme;
11019 
11020 	ill = ncec->ncec_ill;
11021 	/* skip arpce entries, and loopback ncec entries */
11022 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11023 		return (0);
11024 	/*
11025 	 * Neighbor cache entry attached to IRE with on-link
11026 	 * destination.
11027 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11028 	 */
11029 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11030 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11031 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11032 	if (ncec->ncec_lladdr != NULL) {
11033 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11034 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11035 	}
11036 	/*
11037 	 * Note: Returns ND_* states. Should be:
11038 	 * reachable(1), stale(2), delay(3), probe(4),
11039 	 * invalid(5), unknown(6)
11040 	 */
11041 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11042 	ntme.ipv6NetToMediaLastUpdated = 0;
11043 
11044 	/* other(1), dynamic(2), static(3), local(4) */
11045 	if (NCE_MYADDR(ncec)) {
11046 		ntme.ipv6NetToMediaType = 4;
11047 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11048 		ntme.ipv6NetToMediaType = 1; /* proxy */
11049 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11050 		ntme.ipv6NetToMediaType = 3;
11051 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11052 		ntme.ipv6NetToMediaType = 1;
11053 	} else {
11054 		ntme.ipv6NetToMediaType = 2;
11055 	}
11056 
11057 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11058 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11059 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11060 		    (uint_t)sizeof (ntme)));
11061 	}
11062 	return (0);
11063 }
11064 
11065 int
11066 nce2ace(ncec_t *ncec)
11067 {
11068 	int flags = 0;
11069 
11070 	if (NCE_ISREACHABLE(ncec))
11071 		flags |= ACE_F_RESOLVED;
11072 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11073 		flags |= ACE_F_AUTHORITY;
11074 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11075 		flags |= ACE_F_PUBLISH;
11076 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11077 		flags |= ACE_F_PERMANENT;
11078 	if (NCE_MYADDR(ncec))
11079 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11080 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11081 		flags |= ACE_F_UNVERIFIED;
11082 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11083 		flags |= ACE_F_AUTHORITY;
11084 	if (ncec->ncec_flags & NCE_F_DELAYED)
11085 		flags |= ACE_F_DELAYED;
11086 	return (flags);
11087 }
11088 
11089 /*
11090  * ncec_walk routine to create ipNetToMediaEntryTable
11091  */
11092 static int
11093 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11094 {
11095 	ill_t				*ill;
11096 	mib2_ipNetToMediaEntry_t	ntme;
11097 	const char			*name = "unknown";
11098 	ipaddr_t			ncec_addr;
11099 
11100 	ill = ncec->ncec_ill;
11101 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11102 	    ill->ill_net_type == IRE_LOOPBACK)
11103 		return (0);
11104 
11105 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11106 	name = ill->ill_name;
11107 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11108 	if (NCE_MYADDR(ncec)) {
11109 		ntme.ipNetToMediaType = 4;
11110 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11111 		ntme.ipNetToMediaType = 1;
11112 	} else {
11113 		ntme.ipNetToMediaType = 3;
11114 	}
11115 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11116 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11117 	    ntme.ipNetToMediaIfIndex.o_length);
11118 
11119 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11120 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11121 
11122 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11123 	ncec_addr = INADDR_BROADCAST;
11124 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11125 	    sizeof (ncec_addr));
11126 	/*
11127 	 * map all the flags to the ACE counterpart.
11128 	 */
11129 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11130 
11131 	ntme.ipNetToMediaPhysAddress.o_length =
11132 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11133 
11134 	if (!NCE_ISREACHABLE(ncec))
11135 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11136 	else {
11137 		if (ncec->ncec_lladdr != NULL) {
11138 			bcopy(ncec->ncec_lladdr,
11139 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11140 			    ntme.ipNetToMediaPhysAddress.o_length);
11141 		}
11142 	}
11143 
11144 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11145 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11146 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11147 		    (uint_t)sizeof (ntme)));
11148 	}
11149 	return (0);
11150 }
11151 
11152 /*
11153  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11154  */
11155 /* ARGSUSED */
11156 int
11157 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11158 {
11159 	switch (level) {
11160 	case MIB2_IP:
11161 	case MIB2_ICMP:
11162 		switch (name) {
11163 		default:
11164 			break;
11165 		}
11166 		return (1);
11167 	default:
11168 		return (1);
11169 	}
11170 }
11171 
11172 /*
11173  * When there exists both a 64- and 32-bit counter of a particular type
11174  * (i.e., InReceives), only the 64-bit counters are added.
11175  */
11176 void
11177 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11178 {
11179 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11180 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11181 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11182 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11183 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11184 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11185 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11186 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11187 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11188 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11189 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11190 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11191 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11192 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11193 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11194 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11195 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11196 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11197 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11198 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11199 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11200 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11201 	    o2->ipIfStatsInWrongIPVersion);
11202 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11203 	    o2->ipIfStatsInWrongIPVersion);
11204 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11205 	    o2->ipIfStatsOutSwitchIPVersion);
11206 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11207 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11208 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11209 	    o2->ipIfStatsHCInForwDatagrams);
11210 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11211 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11212 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11213 	    o2->ipIfStatsHCOutForwDatagrams);
11214 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11215 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11216 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11217 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11218 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11219 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11220 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11221 	    o2->ipIfStatsHCOutMcastOctets);
11222 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11223 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11224 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11225 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11226 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11227 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11228 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11229 }
11230 
11231 void
11232 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11233 {
11234 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11235 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11236 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11237 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11238 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11239 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11240 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11241 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11242 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11243 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11244 	    o2->ipv6IfIcmpInRouterSolicits);
11245 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11246 	    o2->ipv6IfIcmpInRouterAdvertisements);
11247 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11248 	    o2->ipv6IfIcmpInNeighborSolicits);
11249 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11250 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11251 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11252 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11253 	    o2->ipv6IfIcmpInGroupMembQueries);
11254 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11255 	    o2->ipv6IfIcmpInGroupMembResponses);
11256 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11257 	    o2->ipv6IfIcmpInGroupMembReductions);
11258 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11259 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11260 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11261 	    o2->ipv6IfIcmpOutDestUnreachs);
11262 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11263 	    o2->ipv6IfIcmpOutAdminProhibs);
11264 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11265 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11266 	    o2->ipv6IfIcmpOutParmProblems);
11267 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11268 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11269 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11270 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11271 	    o2->ipv6IfIcmpOutRouterSolicits);
11272 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11273 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11274 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11275 	    o2->ipv6IfIcmpOutNeighborSolicits);
11276 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11277 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11278 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11279 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11280 	    o2->ipv6IfIcmpOutGroupMembQueries);
11281 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11282 	    o2->ipv6IfIcmpOutGroupMembResponses);
11283 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11284 	    o2->ipv6IfIcmpOutGroupMembReductions);
11285 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11286 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11287 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11288 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11289 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11290 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11291 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11292 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11293 	    o2->ipv6IfIcmpInGroupMembTotal);
11294 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11295 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11296 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11297 	    o2->ipv6IfIcmpInGroupMembBadReports);
11298 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11299 	    o2->ipv6IfIcmpInGroupMembOurReports);
11300 }
11301 
11302 /*
11303  * Called before the options are updated to check if this packet will
11304  * be source routed from here.
11305  * This routine assumes that the options are well formed i.e. that they
11306  * have already been checked.
11307  */
11308 boolean_t
11309 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11310 {
11311 	ipoptp_t	opts;
11312 	uchar_t		*opt;
11313 	uint8_t		optval;
11314 	uint8_t		optlen;
11315 	ipaddr_t	dst;
11316 
11317 	if (IS_SIMPLE_IPH(ipha)) {
11318 		ip2dbg(("not source routed\n"));
11319 		return (B_FALSE);
11320 	}
11321 	dst = ipha->ipha_dst;
11322 	for (optval = ipoptp_first(&opts, ipha);
11323 	    optval != IPOPT_EOL;
11324 	    optval = ipoptp_next(&opts)) {
11325 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11326 		opt = opts.ipoptp_cur;
11327 		optlen = opts.ipoptp_len;
11328 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11329 		    optval, optlen));
11330 		switch (optval) {
11331 			uint32_t off;
11332 		case IPOPT_SSRR:
11333 		case IPOPT_LSRR:
11334 			/*
11335 			 * If dst is one of our addresses and there are some
11336 			 * entries left in the source route return (true).
11337 			 */
11338 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11339 				ip2dbg(("ip_source_routed: not next"
11340 				    " source route 0x%x\n",
11341 				    ntohl(dst)));
11342 				return (B_FALSE);
11343 			}
11344 			off = opt[IPOPT_OFFSET];
11345 			off--;
11346 			if (optlen < IP_ADDR_LEN ||
11347 			    off > optlen - IP_ADDR_LEN) {
11348 				/* End of source route */
11349 				ip1dbg(("ip_source_routed: end of SR\n"));
11350 				return (B_FALSE);
11351 			}
11352 			return (B_TRUE);
11353 		}
11354 	}
11355 	ip2dbg(("not source routed\n"));
11356 	return (B_FALSE);
11357 }
11358 
11359 /*
11360  * ip_unbind is called by the transports to remove a conn from
11361  * the fanout table.
11362  */
11363 void
11364 ip_unbind(conn_t *connp)
11365 {
11366 
11367 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11368 
11369 	if (is_system_labeled() && connp->conn_anon_port) {
11370 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11371 		    connp->conn_mlp_type, connp->conn_proto,
11372 		    ntohs(connp->conn_lport), B_FALSE);
11373 		connp->conn_anon_port = 0;
11374 	}
11375 	connp->conn_mlp_type = mlptSingle;
11376 
11377 	ipcl_hash_remove(connp);
11378 }
11379 
11380 /*
11381  * Used for deciding the MSS size for the upper layer. Thus
11382  * we need to check the outbound policy values in the conn.
11383  */
11384 int
11385 conn_ipsec_length(conn_t *connp)
11386 {
11387 	ipsec_latch_t *ipl;
11388 
11389 	ipl = connp->conn_latch;
11390 	if (ipl == NULL)
11391 		return (0);
11392 
11393 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11394 		return (0);
11395 
11396 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11397 }
11398 
11399 /*
11400  * Returns an estimate of the IPsec headers size. This is used if
11401  * we don't want to call into IPsec to get the exact size.
11402  */
11403 int
11404 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11405 {
11406 	ipsec_action_t *a;
11407 
11408 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11409 		return (0);
11410 
11411 	a = ixa->ixa_ipsec_action;
11412 	if (a == NULL) {
11413 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11414 		a = ixa->ixa_ipsec_policy->ipsp_act;
11415 	}
11416 	ASSERT(a != NULL);
11417 
11418 	return (a->ipa_ovhd);
11419 }
11420 
11421 /*
11422  * If there are any source route options, return the true final
11423  * destination. Otherwise, return the destination.
11424  */
11425 ipaddr_t
11426 ip_get_dst(ipha_t *ipha)
11427 {
11428 	ipoptp_t	opts;
11429 	uchar_t		*opt;
11430 	uint8_t		optval;
11431 	uint8_t		optlen;
11432 	ipaddr_t	dst;
11433 	uint32_t off;
11434 
11435 	dst = ipha->ipha_dst;
11436 
11437 	if (IS_SIMPLE_IPH(ipha))
11438 		return (dst);
11439 
11440 	for (optval = ipoptp_first(&opts, ipha);
11441 	    optval != IPOPT_EOL;
11442 	    optval = ipoptp_next(&opts)) {
11443 		opt = opts.ipoptp_cur;
11444 		optlen = opts.ipoptp_len;
11445 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11446 		switch (optval) {
11447 		case IPOPT_SSRR:
11448 		case IPOPT_LSRR:
11449 			off = opt[IPOPT_OFFSET];
11450 			/*
11451 			 * If one of the conditions is true, it means
11452 			 * end of options and dst already has the right
11453 			 * value.
11454 			 */
11455 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11456 				off = optlen - IP_ADDR_LEN;
11457 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11458 			}
11459 			return (dst);
11460 		default:
11461 			break;
11462 		}
11463 	}
11464 
11465 	return (dst);
11466 }
11467 
11468 /*
11469  * Outbound IP fragmentation routine.
11470  * Assumes the caller has checked whether or not fragmentation should
11471  * be allowed. Here we copy the DF bit from the header to all the generated
11472  * fragments.
11473  */
11474 int
11475 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11476     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11477     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11478 {
11479 	int		i1;
11480 	int		hdr_len;
11481 	mblk_t		*hdr_mp;
11482 	ipha_t		*ipha;
11483 	int		ip_data_end;
11484 	int		len;
11485 	mblk_t		*mp = mp_orig;
11486 	int		offset;
11487 	ill_t		*ill = nce->nce_ill;
11488 	ip_stack_t	*ipst = ill->ill_ipst;
11489 	mblk_t		*carve_mp;
11490 	uint32_t	frag_flag;
11491 	uint_t		priority = mp->b_band;
11492 	int		error = 0;
11493 
11494 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11495 
11496 	if (pkt_len != msgdsize(mp)) {
11497 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11498 		    pkt_len, msgdsize(mp)));
11499 		freemsg(mp);
11500 		return (EINVAL);
11501 	}
11502 
11503 	if (max_frag == 0) {
11504 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11505 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11506 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11507 		freemsg(mp);
11508 		return (EINVAL);
11509 	}
11510 
11511 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11512 	ipha = (ipha_t *)mp->b_rptr;
11513 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11514 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11515 
11516 	/*
11517 	 * Establish the starting offset.  May not be zero if we are fragging
11518 	 * a fragment that is being forwarded.
11519 	 */
11520 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11521 
11522 	/* TODO why is this test needed? */
11523 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11524 		/* TODO: notify ulp somehow */
11525 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11526 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11527 		freemsg(mp);
11528 		return (EINVAL);
11529 	}
11530 
11531 	hdr_len = IPH_HDR_LENGTH(ipha);
11532 	ipha->ipha_hdr_checksum = 0;
11533 
11534 	/*
11535 	 * Establish the number of bytes maximum per frag, after putting
11536 	 * in the header.
11537 	 */
11538 	len = (max_frag - hdr_len) & ~7;
11539 
11540 	/* Get a copy of the header for the trailing frags */
11541 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11542 	    mp);
11543 	if (hdr_mp == NULL) {
11544 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11545 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11546 		freemsg(mp);
11547 		return (ENOBUFS);
11548 	}
11549 
11550 	/* Store the starting offset, with the MoreFrags flag. */
11551 	i1 = offset | IPH_MF | frag_flag;
11552 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11553 
11554 	/* Establish the ending byte offset, based on the starting offset. */
11555 	offset <<= 3;
11556 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11557 
11558 	/* Store the length of the first fragment in the IP header. */
11559 	i1 = len + hdr_len;
11560 	ASSERT(i1 <= IP_MAXPACKET);
11561 	ipha->ipha_length = htons((uint16_t)i1);
11562 
11563 	/*
11564 	 * Compute the IP header checksum for the first frag.  We have to
11565 	 * watch out that we stop at the end of the header.
11566 	 */
11567 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11568 
11569 	/*
11570 	 * Now carve off the first frag.  Note that this will include the
11571 	 * original IP header.
11572 	 */
11573 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11574 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11575 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11576 		freeb(hdr_mp);
11577 		freemsg(mp_orig);
11578 		return (ENOBUFS);
11579 	}
11580 
11581 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11582 
11583 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11584 	    ixa_cookie);
11585 	if (error != 0 && error != EWOULDBLOCK) {
11586 		/* No point in sending the other fragments */
11587 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11588 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11589 		freeb(hdr_mp);
11590 		freemsg(mp_orig);
11591 		return (error);
11592 	}
11593 
11594 	/* No need to redo state machine in loop */
11595 	ixaflags &= ~IXAF_REACH_CONF;
11596 
11597 	/* Advance the offset to the second frag starting point. */
11598 	offset += len;
11599 	/*
11600 	 * Update hdr_len from the copied header - there might be less options
11601 	 * in the later fragments.
11602 	 */
11603 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11604 	/* Loop until done. */
11605 	for (;;) {
11606 		uint16_t	offset_and_flags;
11607 		uint16_t	ip_len;
11608 
11609 		if (ip_data_end - offset > len) {
11610 			/*
11611 			 * Carve off the appropriate amount from the original
11612 			 * datagram.
11613 			 */
11614 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11615 				mp = NULL;
11616 				break;
11617 			}
11618 			/*
11619 			 * More frags after this one.  Get another copy
11620 			 * of the header.
11621 			 */
11622 			if (carve_mp->b_datap->db_ref == 1 &&
11623 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11624 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11625 				/* Inline IP header */
11626 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11627 				    hdr_mp->b_rptr;
11628 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11629 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11630 				mp = carve_mp;
11631 			} else {
11632 				if (!(mp = copyb(hdr_mp))) {
11633 					freemsg(carve_mp);
11634 					break;
11635 				}
11636 				/* Get priority marking, if any. */
11637 				mp->b_band = priority;
11638 				mp->b_cont = carve_mp;
11639 			}
11640 			ipha = (ipha_t *)mp->b_rptr;
11641 			offset_and_flags = IPH_MF;
11642 		} else {
11643 			/*
11644 			 * Last frag.  Consume the header. Set len to
11645 			 * the length of this last piece.
11646 			 */
11647 			len = ip_data_end - offset;
11648 
11649 			/*
11650 			 * Carve off the appropriate amount from the original
11651 			 * datagram.
11652 			 */
11653 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11654 				mp = NULL;
11655 				break;
11656 			}
11657 			if (carve_mp->b_datap->db_ref == 1 &&
11658 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11659 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11660 				/* Inline IP header */
11661 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11662 				    hdr_mp->b_rptr;
11663 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11664 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11665 				mp = carve_mp;
11666 				freeb(hdr_mp);
11667 				hdr_mp = mp;
11668 			} else {
11669 				mp = hdr_mp;
11670 				/* Get priority marking, if any. */
11671 				mp->b_band = priority;
11672 				mp->b_cont = carve_mp;
11673 			}
11674 			ipha = (ipha_t *)mp->b_rptr;
11675 			/* A frag of a frag might have IPH_MF non-zero */
11676 			offset_and_flags =
11677 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11678 			    IPH_MF;
11679 		}
11680 		offset_and_flags |= (uint16_t)(offset >> 3);
11681 		offset_and_flags |= (uint16_t)frag_flag;
11682 		/* Store the offset and flags in the IP header. */
11683 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11684 
11685 		/* Store the length in the IP header. */
11686 		ip_len = (uint16_t)(len + hdr_len);
11687 		ipha->ipha_length = htons(ip_len);
11688 
11689 		/*
11690 		 * Set the IP header checksum.	Note that mp is just
11691 		 * the header, so this is easy to pass to ip_csum.
11692 		 */
11693 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11694 
11695 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11696 
11697 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11698 		    nolzid, ixa_cookie);
11699 		/* All done if we just consumed the hdr_mp. */
11700 		if (mp == hdr_mp) {
11701 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11702 			return (error);
11703 		}
11704 		if (error != 0 && error != EWOULDBLOCK) {
11705 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11706 			    mblk_t *, hdr_mp);
11707 			/* No point in sending the other fragments */
11708 			break;
11709 		}
11710 
11711 		/* Otherwise, advance and loop. */
11712 		offset += len;
11713 	}
11714 	/* Clean up following allocation failure. */
11715 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11716 	ip_drop_output("FragFails: loop ended", NULL, ill);
11717 	if (mp != hdr_mp)
11718 		freeb(hdr_mp);
11719 	if (mp != mp_orig)
11720 		freemsg(mp_orig);
11721 	return (error);
11722 }
11723 
11724 /*
11725  * Copy the header plus those options which have the copy bit set
11726  */
11727 static mblk_t *
11728 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11729     mblk_t *src)
11730 {
11731 	mblk_t	*mp;
11732 	uchar_t	*up;
11733 
11734 	/*
11735 	 * Quick check if we need to look for options without the copy bit
11736 	 * set
11737 	 */
11738 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11739 	if (!mp)
11740 		return (mp);
11741 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11742 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11743 		bcopy(rptr, mp->b_rptr, hdr_len);
11744 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11745 		return (mp);
11746 	}
11747 	up  = mp->b_rptr;
11748 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11749 	up += IP_SIMPLE_HDR_LENGTH;
11750 	rptr += IP_SIMPLE_HDR_LENGTH;
11751 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11752 	while (hdr_len > 0) {
11753 		uint32_t optval;
11754 		uint32_t optlen;
11755 
11756 		optval = *rptr;
11757 		if (optval == IPOPT_EOL)
11758 			break;
11759 		if (optval == IPOPT_NOP)
11760 			optlen = 1;
11761 		else
11762 			optlen = rptr[1];
11763 		if (optval & IPOPT_COPY) {
11764 			bcopy(rptr, up, optlen);
11765 			up += optlen;
11766 		}
11767 		rptr += optlen;
11768 		hdr_len -= optlen;
11769 	}
11770 	/*
11771 	 * Make sure that we drop an even number of words by filling
11772 	 * with EOL to the next word boundary.
11773 	 */
11774 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11775 	    hdr_len & 0x3; hdr_len++)
11776 		*up++ = IPOPT_EOL;
11777 	mp->b_wptr = up;
11778 	/* Update header length */
11779 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11780 	return (mp);
11781 }
11782 
11783 /*
11784  * Update any source route, record route, or timestamp options when
11785  * sending a packet back to ourselves.
11786  * Check that we are at end of strict source route.
11787  * The options have been sanity checked by ip_output_options().
11788  */
11789 void
11790 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11791 {
11792 	ipoptp_t	opts;
11793 	uchar_t		*opt;
11794 	uint8_t		optval;
11795 	uint8_t		optlen;
11796 	ipaddr_t	dst;
11797 	uint32_t	ts;
11798 	timestruc_t	now;
11799 
11800 	for (optval = ipoptp_first(&opts, ipha);
11801 	    optval != IPOPT_EOL;
11802 	    optval = ipoptp_next(&opts)) {
11803 		opt = opts.ipoptp_cur;
11804 		optlen = opts.ipoptp_len;
11805 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11806 		switch (optval) {
11807 			uint32_t off;
11808 		case IPOPT_SSRR:
11809 		case IPOPT_LSRR:
11810 			off = opt[IPOPT_OFFSET];
11811 			off--;
11812 			if (optlen < IP_ADDR_LEN ||
11813 			    off > optlen - IP_ADDR_LEN) {
11814 				/* End of source route */
11815 				break;
11816 			}
11817 			/*
11818 			 * This will only happen if two consecutive entries
11819 			 * in the source route contains our address or if
11820 			 * it is a packet with a loose source route which
11821 			 * reaches us before consuming the whole source route
11822 			 */
11823 
11824 			if (optval == IPOPT_SSRR) {
11825 				return;
11826 			}
11827 			/*
11828 			 * Hack: instead of dropping the packet truncate the
11829 			 * source route to what has been used by filling the
11830 			 * rest with IPOPT_NOP.
11831 			 */
11832 			opt[IPOPT_OLEN] = (uint8_t)off;
11833 			while (off < optlen) {
11834 				opt[off++] = IPOPT_NOP;
11835 			}
11836 			break;
11837 		case IPOPT_RR:
11838 			off = opt[IPOPT_OFFSET];
11839 			off--;
11840 			if (optlen < IP_ADDR_LEN ||
11841 			    off > optlen - IP_ADDR_LEN) {
11842 				/* No more room - ignore */
11843 				ip1dbg((
11844 				    "ip_output_local_options: end of RR\n"));
11845 				break;
11846 			}
11847 			dst = htonl(INADDR_LOOPBACK);
11848 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11849 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11850 			break;
11851 		case IPOPT_TS:
11852 			/* Insert timestamp if there is romm */
11853 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11854 			case IPOPT_TS_TSONLY:
11855 				off = IPOPT_TS_TIMELEN;
11856 				break;
11857 			case IPOPT_TS_PRESPEC:
11858 			case IPOPT_TS_PRESPEC_RFC791:
11859 				/* Verify that the address matched */
11860 				off = opt[IPOPT_OFFSET] - 1;
11861 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
11862 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11863 					/* Not for us */
11864 					break;
11865 				}
11866 				/* FALLTHRU */
11867 			case IPOPT_TS_TSANDADDR:
11868 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
11869 				break;
11870 			default:
11871 				/*
11872 				 * ip_*put_options should have already
11873 				 * dropped this packet.
11874 				 */
11875 				cmn_err(CE_PANIC, "ip_output_local_options: "
11876 				    "unknown IT - bug in ip_output_options?\n");
11877 				return;	/* Keep "lint" happy */
11878 			}
11879 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
11880 				/* Increase overflow counter */
11881 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
11882 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
11883 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
11884 				    (off << 4);
11885 				break;
11886 			}
11887 			off = opt[IPOPT_OFFSET] - 1;
11888 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11889 			case IPOPT_TS_PRESPEC:
11890 			case IPOPT_TS_PRESPEC_RFC791:
11891 			case IPOPT_TS_TSANDADDR:
11892 				dst = htonl(INADDR_LOOPBACK);
11893 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11894 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11895 				/* FALLTHRU */
11896 			case IPOPT_TS_TSONLY:
11897 				off = opt[IPOPT_OFFSET] - 1;
11898 				/* Compute # of milliseconds since midnight */
11899 				gethrestime(&now);
11900 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
11901 				    now.tv_nsec / (NANOSEC / MILLISEC);
11902 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
11903 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
11904 				break;
11905 			}
11906 			break;
11907 		}
11908 	}
11909 }
11910 
11911 /*
11912  * Prepend an M_DATA fastpath header, and if none present prepend a
11913  * DL_UNITDATA_REQ. Frees the mblk on failure.
11914  *
11915  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
11916  * If there is a change to them, the nce will be deleted (condemned) and
11917  * a new nce_t will be created when packets are sent. Thus we need no locks
11918  * to access those fields.
11919  *
11920  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
11921  * we place b_band in dl_priority.dl_max.
11922  */
11923 static mblk_t *
11924 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
11925 {
11926 	uint_t	hlen;
11927 	mblk_t *mp1;
11928 	uint_t	priority;
11929 	uchar_t *rptr;
11930 
11931 	rptr = mp->b_rptr;
11932 
11933 	ASSERT(DB_TYPE(mp) == M_DATA);
11934 	priority = mp->b_band;
11935 
11936 	ASSERT(nce != NULL);
11937 	if ((mp1 = nce->nce_fp_mp) != NULL) {
11938 		hlen = MBLKL(mp1);
11939 		/*
11940 		 * Check if we have enough room to prepend fastpath
11941 		 * header
11942 		 */
11943 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
11944 			rptr -= hlen;
11945 			bcopy(mp1->b_rptr, rptr, hlen);
11946 			/*
11947 			 * Set the b_rptr to the start of the link layer
11948 			 * header
11949 			 */
11950 			mp->b_rptr = rptr;
11951 			return (mp);
11952 		}
11953 		mp1 = copyb(mp1);
11954 		if (mp1 == NULL) {
11955 			ill_t *ill = nce->nce_ill;
11956 
11957 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
11958 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
11959 			freemsg(mp);
11960 			return (NULL);
11961 		}
11962 		mp1->b_band = priority;
11963 		mp1->b_cont = mp;
11964 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
11965 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
11966 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
11967 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
11968 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
11969 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
11970 		/*
11971 		 * XXX disable ICK_VALID and compute checksum
11972 		 * here; can happen if nce_fp_mp changes and
11973 		 * it can't be copied now due to insufficient
11974 		 * space. (unlikely, fp mp can change, but it
11975 		 * does not increase in length)
11976 		 */
11977 		return (mp1);
11978 	}
11979 	mp1 = copyb(nce->nce_dlur_mp);
11980 
11981 	if (mp1 == NULL) {
11982 		ill_t *ill = nce->nce_ill;
11983 
11984 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
11985 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
11986 		freemsg(mp);
11987 		return (NULL);
11988 	}
11989 	mp1->b_cont = mp;
11990 	if (priority != 0) {
11991 		mp1->b_band = priority;
11992 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
11993 		    priority;
11994 	}
11995 	return (mp1);
11996 #undef rptr
11997 }
11998 
11999 /*
12000  * Finish the outbound IPsec processing. This function is called from
12001  * ipsec_out_process() if the IPsec packet was processed
12002  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12003  * asynchronously.
12004  *
12005  * This is common to IPv4 and IPv6.
12006  */
12007 int
12008 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12009 {
12010 	iaflags_t	ixaflags = ixa->ixa_flags;
12011 	uint_t		pktlen;
12012 
12013 
12014 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12015 	if (ixaflags & IXAF_IS_IPV4) {
12016 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12017 
12018 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12019 		pktlen = ntohs(ipha->ipha_length);
12020 	} else {
12021 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12022 
12023 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12024 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12025 	}
12026 
12027 	/*
12028 	 * We release any hard reference on the SAs here to make
12029 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12030 	 * on the SAs.
12031 	 * If in the future we want the hard latching of the SAs in the
12032 	 * ip_xmit_attr_t then we should remove this.
12033 	 */
12034 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12035 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12036 		ixa->ixa_ipsec_esp_sa = NULL;
12037 	}
12038 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12039 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12040 		ixa->ixa_ipsec_ah_sa = NULL;
12041 	}
12042 
12043 	/* Do we need to fragment? */
12044 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12045 	    pktlen > ixa->ixa_fragsize) {
12046 		if (ixaflags & IXAF_IS_IPV4) {
12047 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12048 			/*
12049 			 * We check for the DF case in ipsec_out_process
12050 			 * hence this only handles the non-DF case.
12051 			 */
12052 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12053 			    pktlen, ixa->ixa_fragsize,
12054 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12055 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12056 			    &ixa->ixa_cookie));
12057 		} else {
12058 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12059 			if (mp == NULL) {
12060 				/* MIB and ip_drop_output already done */
12061 				return (ENOMEM);
12062 			}
12063 			pktlen += sizeof (ip6_frag_t);
12064 			if (pktlen > ixa->ixa_fragsize) {
12065 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12066 				    ixa->ixa_flags, pktlen,
12067 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12068 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12069 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12070 			}
12071 		}
12072 	}
12073 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12074 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12075 	    ixa->ixa_no_loop_zoneid, NULL));
12076 }
12077 
12078 /*
12079  * Finish the inbound IPsec processing. This function is called from
12080  * ipsec_out_process() if the IPsec packet was processed
12081  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12082  * asynchronously.
12083  *
12084  * This is common to IPv4 and IPv6.
12085  */
12086 void
12087 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12088 {
12089 	iaflags_t	iraflags = ira->ira_flags;
12090 
12091 	/* Length might have changed */
12092 	if (iraflags & IRAF_IS_IPV4) {
12093 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12094 
12095 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12096 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12097 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12098 		ira->ira_protocol = ipha->ipha_protocol;
12099 
12100 		ip_fanout_v4(mp, ipha, ira);
12101 	} else {
12102 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12103 		uint8_t		*nexthdrp;
12104 
12105 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12106 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12107 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12108 		    &nexthdrp)) {
12109 			/* Malformed packet */
12110 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12111 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12112 			freemsg(mp);
12113 			return;
12114 		}
12115 		ira->ira_protocol = *nexthdrp;
12116 		ip_fanout_v6(mp, ip6h, ira);
12117 	}
12118 }
12119 
12120 /*
12121  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12122  *
12123  * If this function returns B_TRUE, the requested SA's have been filled
12124  * into the ixa_ipsec_*_sa pointers.
12125  *
12126  * If the function returns B_FALSE, the packet has been "consumed", most
12127  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12128  *
12129  * The SA references created by the protocol-specific "select"
12130  * function will be released in ip_output_post_ipsec.
12131  */
12132 static boolean_t
12133 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12134 {
12135 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12136 	ipsec_policy_t *pp;
12137 	ipsec_action_t *ap;
12138 
12139 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12140 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12141 	    (ixa->ixa_ipsec_action != NULL));
12142 
12143 	ap = ixa->ixa_ipsec_action;
12144 	if (ap == NULL) {
12145 		pp = ixa->ixa_ipsec_policy;
12146 		ASSERT(pp != NULL);
12147 		ap = pp->ipsp_act;
12148 		ASSERT(ap != NULL);
12149 	}
12150 
12151 	/*
12152 	 * We have an action.  now, let's select SA's.
12153 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12154 	 * be cached in the conn_t.
12155 	 */
12156 	if (ap->ipa_want_esp) {
12157 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12158 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12159 			    IPPROTO_ESP);
12160 		}
12161 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12162 	}
12163 
12164 	if (ap->ipa_want_ah) {
12165 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12166 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12167 			    IPPROTO_AH);
12168 		}
12169 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12170 		/*
12171 		 * The ESP and AH processing order needs to be preserved
12172 		 * when both protocols are required (ESP should be applied
12173 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12174 		 * when both ESP and AH are required, and an AH ACQUIRE
12175 		 * is needed.
12176 		 */
12177 		if (ap->ipa_want_esp && need_ah_acquire)
12178 			need_esp_acquire = B_TRUE;
12179 	}
12180 
12181 	/*
12182 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12183 	 * Release SAs that got referenced, but will not be used until we
12184 	 * acquire _all_ of the SAs we need.
12185 	 */
12186 	if (need_ah_acquire || need_esp_acquire) {
12187 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12188 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12189 			ixa->ixa_ipsec_ah_sa = NULL;
12190 		}
12191 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12192 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12193 			ixa->ixa_ipsec_esp_sa = NULL;
12194 		}
12195 
12196 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12197 		return (B_FALSE);
12198 	}
12199 
12200 	return (B_TRUE);
12201 }
12202 
12203 /*
12204  * Handle IPsec output processing.
12205  * This function is only entered once for a given packet.
12206  * We try to do things synchronously, but if we need to have user-level
12207  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12208  * will be completed
12209  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12210  *  - when asynchronous ESP is done it will do AH
12211  *
12212  * In all cases we come back in ip_output_post_ipsec() to fragment and
12213  * send out the packet.
12214  */
12215 int
12216 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12217 {
12218 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12219 	ip_stack_t	*ipst = ixa->ixa_ipst;
12220 	ipsec_stack_t	*ipss;
12221 	ipsec_policy_t	*pp;
12222 	ipsec_action_t	*ap;
12223 
12224 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12225 
12226 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12227 	    (ixa->ixa_ipsec_action != NULL));
12228 
12229 	ipss = ipst->ips_netstack->netstack_ipsec;
12230 	if (!ipsec_loaded(ipss)) {
12231 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12232 		ip_drop_packet(mp, B_TRUE, ill,
12233 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12234 		    &ipss->ipsec_dropper);
12235 		return (ENOTSUP);
12236 	}
12237 
12238 	ap = ixa->ixa_ipsec_action;
12239 	if (ap == NULL) {
12240 		pp = ixa->ixa_ipsec_policy;
12241 		ASSERT(pp != NULL);
12242 		ap = pp->ipsp_act;
12243 		ASSERT(ap != NULL);
12244 	}
12245 
12246 	/* Handle explicit drop action and bypass. */
12247 	switch (ap->ipa_act.ipa_type) {
12248 	case IPSEC_ACT_DISCARD:
12249 	case IPSEC_ACT_REJECT:
12250 		ip_drop_packet(mp, B_FALSE, ill,
12251 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12252 		return (EHOSTUNREACH);	/* IPsec policy failure */
12253 	case IPSEC_ACT_BYPASS:
12254 		return (ip_output_post_ipsec(mp, ixa));
12255 	}
12256 
12257 	/*
12258 	 * The order of processing is first insert a IP header if needed.
12259 	 * Then insert the ESP header and then the AH header.
12260 	 */
12261 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12262 		/*
12263 		 * First get the outer IP header before sending
12264 		 * it to ESP.
12265 		 */
12266 		ipha_t *oipha, *iipha;
12267 		mblk_t *outer_mp, *inner_mp;
12268 
12269 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12270 			(void) mi_strlog(ill->ill_rq, 0,
12271 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12272 			    "ipsec_out_process: "
12273 			    "Self-Encapsulation failed: Out of memory\n");
12274 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12275 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12276 			freemsg(mp);
12277 			return (ENOBUFS);
12278 		}
12279 		inner_mp = mp;
12280 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12281 		oipha = (ipha_t *)outer_mp->b_rptr;
12282 		iipha = (ipha_t *)inner_mp->b_rptr;
12283 		*oipha = *iipha;
12284 		outer_mp->b_wptr += sizeof (ipha_t);
12285 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12286 		    sizeof (ipha_t));
12287 		oipha->ipha_protocol = IPPROTO_ENCAP;
12288 		oipha->ipha_version_and_hdr_length =
12289 		    IP_SIMPLE_HDR_VERSION;
12290 		oipha->ipha_hdr_checksum = 0;
12291 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12292 		outer_mp->b_cont = inner_mp;
12293 		mp = outer_mp;
12294 
12295 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12296 	}
12297 
12298 	/* If we need to wait for a SA then we can't return any errno */
12299 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12300 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12301 	    !ipsec_out_select_sa(mp, ixa))
12302 		return (0);
12303 
12304 	/*
12305 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12306 	 * to do the heavy lifting.
12307 	 */
12308 	if (ap->ipa_want_esp) {
12309 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12310 
12311 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12312 		if (mp == NULL) {
12313 			/*
12314 			 * Either it failed or is pending. In the former case
12315 			 * ipIfStatsInDiscards was increased.
12316 			 */
12317 			return (0);
12318 		}
12319 	}
12320 
12321 	if (ap->ipa_want_ah) {
12322 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12323 
12324 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12325 		if (mp == NULL) {
12326 			/*
12327 			 * Either it failed or is pending. In the former case
12328 			 * ipIfStatsInDiscards was increased.
12329 			 */
12330 			return (0);
12331 		}
12332 	}
12333 	/*
12334 	 * We are done with IPsec processing. Send it over
12335 	 * the wire.
12336 	 */
12337 	return (ip_output_post_ipsec(mp, ixa));
12338 }
12339 
12340 /*
12341  * ioctls that go through a down/up sequence may need to wait for the down
12342  * to complete. This involves waiting for the ire and ipif refcnts to go down
12343  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12344  */
12345 /* ARGSUSED */
12346 void
12347 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12348 {
12349 	struct iocblk *iocp;
12350 	mblk_t *mp1;
12351 	ip_ioctl_cmd_t *ipip;
12352 	int err;
12353 	sin_t	*sin;
12354 	struct lifreq *lifr;
12355 	struct ifreq *ifr;
12356 
12357 	iocp = (struct iocblk *)mp->b_rptr;
12358 	ASSERT(ipsq != NULL);
12359 	/* Existence of mp1 verified in ip_wput_nondata */
12360 	mp1 = mp->b_cont->b_cont;
12361 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12362 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12363 		/*
12364 		 * Special case where ipx_current_ipif is not set:
12365 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12366 		 * We are here as were not able to complete the operation in
12367 		 * ipif_set_values because we could not become exclusive on
12368 		 * the new ipsq.
12369 		 */
12370 		ill_t *ill = q->q_ptr;
12371 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12372 	}
12373 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12374 
12375 	if (ipip->ipi_cmd_type == IF_CMD) {
12376 		/* This a old style SIOC[GS]IF* command */
12377 		ifr = (struct ifreq *)mp1->b_rptr;
12378 		sin = (sin_t *)&ifr->ifr_addr;
12379 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12380 		/* This a new style SIOC[GS]LIF* command */
12381 		lifr = (struct lifreq *)mp1->b_rptr;
12382 		sin = (sin_t *)&lifr->lifr_addr;
12383 	} else {
12384 		sin = NULL;
12385 	}
12386 
12387 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12388 	    q, mp, ipip, mp1->b_rptr);
12389 
12390 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12391 	    int, ipip->ipi_cmd,
12392 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12393 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12394 
12395 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12396 }
12397 
12398 /*
12399  * ioctl processing
12400  *
12401  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12402  * the ioctl command in the ioctl tables, determines the copyin data size
12403  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12404  *
12405  * ioctl processing then continues when the M_IOCDATA makes its way down to
12406  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12407  * associated 'conn' is refheld till the end of the ioctl and the general
12408  * ioctl processing function ip_process_ioctl() is called to extract the
12409  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12410  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12411  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12412  * is used to extract the ioctl's arguments.
12413  *
12414  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12415  * so goes thru the serialization primitive ipsq_try_enter. Then the
12416  * appropriate function to handle the ioctl is called based on the entry in
12417  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12418  * which also refreleases the 'conn' that was refheld at the start of the
12419  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12420  *
12421  * Many exclusive ioctls go thru an internal down up sequence as part of
12422  * the operation. For example an attempt to change the IP address of an
12423  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12424  * does all the cleanup such as deleting all ires that use this address.
12425  * Then we need to wait till all references to the interface go away.
12426  */
12427 void
12428 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12429 {
12430 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12431 	ip_ioctl_cmd_t *ipip = arg;
12432 	ip_extract_func_t *extract_funcp;
12433 	cmd_info_t ci;
12434 	int err;
12435 	boolean_t entered_ipsq = B_FALSE;
12436 
12437 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12438 
12439 	if (ipip == NULL)
12440 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12441 
12442 	/*
12443 	 * SIOCLIFADDIF needs to go thru a special path since the
12444 	 * ill may not exist yet. This happens in the case of lo0
12445 	 * which is created using this ioctl.
12446 	 */
12447 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12448 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12449 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12450 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12451 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12452 		return;
12453 	}
12454 
12455 	ci.ci_ipif = NULL;
12456 	switch (ipip->ipi_cmd_type) {
12457 	case MISC_CMD:
12458 	case MSFILT_CMD:
12459 		/*
12460 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12461 		 */
12462 		if (ipip->ipi_cmd == IF_UNITSEL) {
12463 			/* ioctl comes down the ill */
12464 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12465 			ipif_refhold(ci.ci_ipif);
12466 		}
12467 		err = 0;
12468 		ci.ci_sin = NULL;
12469 		ci.ci_sin6 = NULL;
12470 		ci.ci_lifr = NULL;
12471 		extract_funcp = NULL;
12472 		break;
12473 
12474 	case IF_CMD:
12475 	case LIF_CMD:
12476 		extract_funcp = ip_extract_lifreq;
12477 		break;
12478 
12479 	case ARP_CMD:
12480 	case XARP_CMD:
12481 		extract_funcp = ip_extract_arpreq;
12482 		break;
12483 
12484 	default:
12485 		ASSERT(0);
12486 	}
12487 
12488 	if (extract_funcp != NULL) {
12489 		err = (*extract_funcp)(q, mp, ipip, &ci);
12490 		if (err != 0) {
12491 			DTRACE_PROBE4(ipif__ioctl,
12492 			    char *, "ip_process_ioctl finish err",
12493 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12494 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12495 			return;
12496 		}
12497 
12498 		/*
12499 		 * All of the extraction functions return a refheld ipif.
12500 		 */
12501 		ASSERT(ci.ci_ipif != NULL);
12502 	}
12503 
12504 	if (!(ipip->ipi_flags & IPI_WR)) {
12505 		/*
12506 		 * A return value of EINPROGRESS means the ioctl is
12507 		 * either queued and waiting for some reason or has
12508 		 * already completed.
12509 		 */
12510 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12511 		    ci.ci_lifr);
12512 		if (ci.ci_ipif != NULL) {
12513 			DTRACE_PROBE4(ipif__ioctl,
12514 			    char *, "ip_process_ioctl finish RD",
12515 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12516 			    ipif_t *, ci.ci_ipif);
12517 			ipif_refrele(ci.ci_ipif);
12518 		} else {
12519 			DTRACE_PROBE4(ipif__ioctl,
12520 			    char *, "ip_process_ioctl finish RD",
12521 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12522 		}
12523 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12524 		return;
12525 	}
12526 
12527 	ASSERT(ci.ci_ipif != NULL);
12528 
12529 	/*
12530 	 * If ipsq is non-NULL, we are already being called exclusively
12531 	 */
12532 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12533 	if (ipsq == NULL) {
12534 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12535 		    NEW_OP, B_TRUE);
12536 		if (ipsq == NULL) {
12537 			ipif_refrele(ci.ci_ipif);
12538 			return;
12539 		}
12540 		entered_ipsq = B_TRUE;
12541 	}
12542 	/*
12543 	 * Release the ipif so that ipif_down and friends that wait for
12544 	 * references to go away are not misled about the current ipif_refcnt
12545 	 * values. We are writer so we can access the ipif even after releasing
12546 	 * the ipif.
12547 	 */
12548 	ipif_refrele(ci.ci_ipif);
12549 
12550 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12551 
12552 	/*
12553 	 * A return value of EINPROGRESS means the ioctl is
12554 	 * either queued and waiting for some reason or has
12555 	 * already completed.
12556 	 */
12557 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12558 
12559 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12560 	    int, ipip->ipi_cmd,
12561 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12562 	    ipif_t *, ci.ci_ipif);
12563 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12564 
12565 	if (entered_ipsq)
12566 		ipsq_exit(ipsq);
12567 }
12568 
12569 /*
12570  * Complete the ioctl. Typically ioctls use the mi package and need to
12571  * do mi_copyout/mi_copy_done.
12572  */
12573 void
12574 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12575 {
12576 	conn_t	*connp = NULL;
12577 
12578 	if (err == EINPROGRESS)
12579 		return;
12580 
12581 	if (CONN_Q(q)) {
12582 		connp = Q_TO_CONN(q);
12583 		ASSERT(connp->conn_ref >= 2);
12584 	}
12585 
12586 	switch (mode) {
12587 	case COPYOUT:
12588 		if (err == 0)
12589 			mi_copyout(q, mp);
12590 		else
12591 			mi_copy_done(q, mp, err);
12592 		break;
12593 
12594 	case NO_COPYOUT:
12595 		mi_copy_done(q, mp, err);
12596 		break;
12597 
12598 	default:
12599 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12600 		break;
12601 	}
12602 
12603 	/*
12604 	 * The conn refhold and ioctlref placed on the conn at the start of the
12605 	 * ioctl are released here.
12606 	 */
12607 	if (connp != NULL) {
12608 		CONN_DEC_IOCTLREF(connp);
12609 		CONN_OPER_PENDING_DONE(connp);
12610 	}
12611 
12612 	if (ipsq != NULL)
12613 		ipsq_current_finish(ipsq);
12614 }
12615 
12616 /* Handles all non data messages */
12617 void
12618 ip_wput_nondata(queue_t *q, mblk_t *mp)
12619 {
12620 	mblk_t		*mp1;
12621 	struct iocblk	*iocp;
12622 	ip_ioctl_cmd_t	*ipip;
12623 	conn_t		*connp;
12624 	cred_t		*cr;
12625 	char		*proto_str;
12626 
12627 	if (CONN_Q(q))
12628 		connp = Q_TO_CONN(q);
12629 	else
12630 		connp = NULL;
12631 
12632 	switch (DB_TYPE(mp)) {
12633 	case M_IOCTL:
12634 		/*
12635 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12636 		 * will arrange to copy in associated control structures.
12637 		 */
12638 		ip_sioctl_copyin_setup(q, mp);
12639 		return;
12640 	case M_IOCDATA:
12641 		/*
12642 		 * Ensure that this is associated with one of our trans-
12643 		 * parent ioctls.  If it's not ours, discard it if we're
12644 		 * running as a driver, or pass it on if we're a module.
12645 		 */
12646 		iocp = (struct iocblk *)mp->b_rptr;
12647 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12648 		if (ipip == NULL) {
12649 			if (q->q_next == NULL) {
12650 				goto nak;
12651 			} else {
12652 				putnext(q, mp);
12653 			}
12654 			return;
12655 		}
12656 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12657 			/*
12658 			 * The ioctl is one we recognise, but is not consumed
12659 			 * by IP as a module and we are a module, so we drop
12660 			 */
12661 			goto nak;
12662 		}
12663 
12664 		/* IOCTL continuation following copyin or copyout. */
12665 		if (mi_copy_state(q, mp, NULL) == -1) {
12666 			/*
12667 			 * The copy operation failed.  mi_copy_state already
12668 			 * cleaned up, so we're out of here.
12669 			 */
12670 			return;
12671 		}
12672 		/*
12673 		 * If we just completed a copy in, we become writer and
12674 		 * continue processing in ip_sioctl_copyin_done.  If it
12675 		 * was a copy out, we call mi_copyout again.  If there is
12676 		 * nothing more to copy out, it will complete the IOCTL.
12677 		 */
12678 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12679 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12680 				mi_copy_done(q, mp, EPROTO);
12681 				return;
12682 			}
12683 			/*
12684 			 * Check for cases that need more copying.  A return
12685 			 * value of 0 means a second copyin has been started,
12686 			 * so we return; a return value of 1 means no more
12687 			 * copying is needed, so we continue.
12688 			 */
12689 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12690 			    MI_COPY_COUNT(mp) == 1) {
12691 				if (ip_copyin_msfilter(q, mp) == 0)
12692 					return;
12693 			}
12694 			/*
12695 			 * Refhold the conn, till the ioctl completes. This is
12696 			 * needed in case the ioctl ends up in the pending mp
12697 			 * list. Every mp in the ipx_pending_mp list must have
12698 			 * a refhold on the conn to resume processing. The
12699 			 * refhold is released when the ioctl completes
12700 			 * (whether normally or abnormally). An ioctlref is also
12701 			 * placed on the conn to prevent TCP from removing the
12702 			 * queue needed to send the ioctl reply back.
12703 			 * In all cases ip_ioctl_finish is called to finish
12704 			 * the ioctl and release the refholds.
12705 			 */
12706 			if (connp != NULL) {
12707 				/* This is not a reentry */
12708 				CONN_INC_REF(connp);
12709 				CONN_INC_IOCTLREF(connp);
12710 			} else {
12711 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12712 					mi_copy_done(q, mp, EINVAL);
12713 					return;
12714 				}
12715 			}
12716 
12717 			ip_process_ioctl(NULL, q, mp, ipip);
12718 
12719 		} else {
12720 			mi_copyout(q, mp);
12721 		}
12722 		return;
12723 
12724 	case M_IOCNAK:
12725 		/*
12726 		 * The only way we could get here is if a resolver didn't like
12727 		 * an IOCTL we sent it.	 This shouldn't happen.
12728 		 */
12729 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12730 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12731 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12732 		freemsg(mp);
12733 		return;
12734 	case M_IOCACK:
12735 		/* /dev/ip shouldn't see this */
12736 		goto nak;
12737 	case M_FLUSH:
12738 		if (*mp->b_rptr & FLUSHW)
12739 			flushq(q, FLUSHALL);
12740 		if (q->q_next) {
12741 			putnext(q, mp);
12742 			return;
12743 		}
12744 		if (*mp->b_rptr & FLUSHR) {
12745 			*mp->b_rptr &= ~FLUSHW;
12746 			qreply(q, mp);
12747 			return;
12748 		}
12749 		freemsg(mp);
12750 		return;
12751 	case M_CTL:
12752 		break;
12753 	case M_PROTO:
12754 	case M_PCPROTO:
12755 		/*
12756 		 * The only PROTO messages we expect are SNMP-related.
12757 		 */
12758 		switch (((union T_primitives *)mp->b_rptr)->type) {
12759 		case T_SVR4_OPTMGMT_REQ:
12760 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12761 			    "flags %x\n",
12762 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12763 
12764 			if (connp == NULL) {
12765 				proto_str = "T_SVR4_OPTMGMT_REQ";
12766 				goto protonak;
12767 			}
12768 
12769 			/*
12770 			 * All Solaris components should pass a db_credp
12771 			 * for this TPI message, hence we ASSERT.
12772 			 * But in case there is some other M_PROTO that looks
12773 			 * like a TPI message sent by some other kernel
12774 			 * component, we check and return an error.
12775 			 */
12776 			cr = msg_getcred(mp, NULL);
12777 			ASSERT(cr != NULL);
12778 			if (cr == NULL) {
12779 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12780 				if (mp != NULL)
12781 					qreply(q, mp);
12782 				return;
12783 			}
12784 
12785 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12786 				proto_str = "Bad SNMPCOM request?";
12787 				goto protonak;
12788 			}
12789 			return;
12790 		default:
12791 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12792 			    (int)*(uint_t *)mp->b_rptr));
12793 			freemsg(mp);
12794 			return;
12795 		}
12796 	default:
12797 		break;
12798 	}
12799 	if (q->q_next) {
12800 		putnext(q, mp);
12801 	} else
12802 		freemsg(mp);
12803 	return;
12804 
12805 nak:
12806 	iocp->ioc_error = EINVAL;
12807 	mp->b_datap->db_type = M_IOCNAK;
12808 	iocp->ioc_count = 0;
12809 	qreply(q, mp);
12810 	return;
12811 
12812 protonak:
12813 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12814 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12815 		qreply(q, mp);
12816 }
12817 
12818 /*
12819  * Process IP options in an outbound packet.  Verify that the nexthop in a
12820  * strict source route is onlink.
12821  * Returns non-zero if something fails in which case an ICMP error has been
12822  * sent and mp freed.
12823  *
12824  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12825  */
12826 int
12827 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12828 {
12829 	ipoptp_t	opts;
12830 	uchar_t		*opt;
12831 	uint8_t		optval;
12832 	uint8_t		optlen;
12833 	ipaddr_t	dst;
12834 	intptr_t	code = 0;
12835 	ire_t		*ire;
12836 	ip_stack_t	*ipst = ixa->ixa_ipst;
12837 	ip_recv_attr_t	iras;
12838 
12839 	ip2dbg(("ip_output_options\n"));
12840 
12841 	dst = ipha->ipha_dst;
12842 	for (optval = ipoptp_first(&opts, ipha);
12843 	    optval != IPOPT_EOL;
12844 	    optval = ipoptp_next(&opts)) {
12845 		opt = opts.ipoptp_cur;
12846 		optlen = opts.ipoptp_len;
12847 		ip2dbg(("ip_output_options: opt %d, len %d\n",
12848 		    optval, optlen));
12849 		switch (optval) {
12850 			uint32_t off;
12851 		case IPOPT_SSRR:
12852 		case IPOPT_LSRR:
12853 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12854 				ip1dbg((
12855 				    "ip_output_options: bad option offset\n"));
12856 				code = (char *)&opt[IPOPT_OLEN] -
12857 				    (char *)ipha;
12858 				goto param_prob;
12859 			}
12860 			off = opt[IPOPT_OFFSET];
12861 			ip1dbg(("ip_output_options: next hop 0x%x\n",
12862 			    ntohl(dst)));
12863 			/*
12864 			 * For strict: verify that dst is directly
12865 			 * reachable.
12866 			 */
12867 			if (optval == IPOPT_SSRR) {
12868 				ire = ire_ftable_lookup_v4(dst, 0, 0,
12869 				    IRE_IF_ALL, NULL, ALL_ZONES, ixa->ixa_tsl,
12870 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
12871 				    NULL);
12872 				if (ire == NULL) {
12873 					ip1dbg(("ip_output_options: SSRR not"
12874 					    " directly reachable: 0x%x\n",
12875 					    ntohl(dst)));
12876 					goto bad_src_route;
12877 				}
12878 				ire_refrele(ire);
12879 			}
12880 			break;
12881 		case IPOPT_RR:
12882 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12883 				ip1dbg((
12884 				    "ip_output_options: bad option offset\n"));
12885 				code = (char *)&opt[IPOPT_OLEN] -
12886 				    (char *)ipha;
12887 				goto param_prob;
12888 			}
12889 			break;
12890 		case IPOPT_TS:
12891 			/*
12892 			 * Verify that length >=5 and that there is either
12893 			 * room for another timestamp or that the overflow
12894 			 * counter is not maxed out.
12895 			 */
12896 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
12897 			if (optlen < IPOPT_MINLEN_IT) {
12898 				goto param_prob;
12899 			}
12900 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12901 				ip1dbg((
12902 				    "ip_output_options: bad option offset\n"));
12903 				code = (char *)&opt[IPOPT_OFFSET] -
12904 				    (char *)ipha;
12905 				goto param_prob;
12906 			}
12907 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12908 			case IPOPT_TS_TSONLY:
12909 				off = IPOPT_TS_TIMELEN;
12910 				break;
12911 			case IPOPT_TS_TSANDADDR:
12912 			case IPOPT_TS_PRESPEC:
12913 			case IPOPT_TS_PRESPEC_RFC791:
12914 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12915 				break;
12916 			default:
12917 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
12918 				    (char *)ipha;
12919 				goto param_prob;
12920 			}
12921 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
12922 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
12923 				/*
12924 				 * No room and the overflow counter is 15
12925 				 * already.
12926 				 */
12927 				goto param_prob;
12928 			}
12929 			break;
12930 		}
12931 	}
12932 
12933 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
12934 		return (0);
12935 
12936 	ip1dbg(("ip_output_options: error processing IP options."));
12937 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
12938 
12939 param_prob:
12940 	bzero(&iras, sizeof (iras));
12941 	iras.ira_ill = iras.ira_rill = ill;
12942 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12943 	iras.ira_rifindex = iras.ira_ruifindex;
12944 	iras.ira_flags = IRAF_IS_IPV4;
12945 
12946 	ip_drop_output("ip_output_options", mp, ill);
12947 	icmp_param_problem(mp, (uint8_t)code, &iras);
12948 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12949 	return (-1);
12950 
12951 bad_src_route:
12952 	bzero(&iras, sizeof (iras));
12953 	iras.ira_ill = iras.ira_rill = ill;
12954 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12955 	iras.ira_rifindex = iras.ira_ruifindex;
12956 	iras.ira_flags = IRAF_IS_IPV4;
12957 
12958 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
12959 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
12960 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12961 	return (-1);
12962 }
12963 
12964 /*
12965  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
12966  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
12967  * thru /etc/system.
12968  */
12969 #define	CONN_MAXDRAINCNT	64
12970 
12971 static void
12972 conn_drain_init(ip_stack_t *ipst)
12973 {
12974 	int i, j;
12975 	idl_tx_list_t *itl_tx;
12976 
12977 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
12978 
12979 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
12980 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
12981 		/*
12982 		 * Default value of the number of drainers is the
12983 		 * number of cpus, subject to maximum of 8 drainers.
12984 		 */
12985 		if (boot_max_ncpus != -1)
12986 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
12987 		else
12988 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
12989 	}
12990 
12991 	ipst->ips_idl_tx_list =
12992 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
12993 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
12994 		itl_tx =  &ipst->ips_idl_tx_list[i];
12995 		itl_tx->txl_drain_list =
12996 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
12997 		    sizeof (idl_t), KM_SLEEP);
12998 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
12999 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13000 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13001 			    MUTEX_DEFAULT, NULL);
13002 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13003 		}
13004 	}
13005 }
13006 
13007 static void
13008 conn_drain_fini(ip_stack_t *ipst)
13009 {
13010 	int i;
13011 	idl_tx_list_t *itl_tx;
13012 
13013 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13014 		itl_tx =  &ipst->ips_idl_tx_list[i];
13015 		kmem_free(itl_tx->txl_drain_list,
13016 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13017 	}
13018 	kmem_free(ipst->ips_idl_tx_list,
13019 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13020 	ipst->ips_idl_tx_list = NULL;
13021 }
13022 
13023 /*
13024  * Flow control has blocked us from proceeding.  Insert the given conn in one
13025  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13026  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13027  * will call conn_walk_drain().  See the flow control notes at the top of this
13028  * file for more details.
13029  */
13030 void
13031 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13032 {
13033 	idl_t	*idl = tx_list->txl_drain_list;
13034 	uint_t	index;
13035 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13036 
13037 	mutex_enter(&connp->conn_lock);
13038 	if (connp->conn_state_flags & CONN_CLOSING) {
13039 		/*
13040 		 * The conn is closing as a result of which CONN_CLOSING
13041 		 * is set. Return.
13042 		 */
13043 		mutex_exit(&connp->conn_lock);
13044 		return;
13045 	} else if (connp->conn_idl == NULL) {
13046 		/*
13047 		 * Assign the next drain list round robin. We dont' use
13048 		 * a lock, and thus it may not be strictly round robin.
13049 		 * Atomicity of load/stores is enough to make sure that
13050 		 * conn_drain_list_index is always within bounds.
13051 		 */
13052 		index = tx_list->txl_drain_index;
13053 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13054 		connp->conn_idl = &tx_list->txl_drain_list[index];
13055 		index++;
13056 		if (index == ipst->ips_conn_drain_list_cnt)
13057 			index = 0;
13058 		tx_list->txl_drain_index = index;
13059 	} else {
13060 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13061 	}
13062 	mutex_exit(&connp->conn_lock);
13063 
13064 	idl = connp->conn_idl;
13065 	mutex_enter(&idl->idl_lock);
13066 	if ((connp->conn_drain_prev != NULL) ||
13067 	    (connp->conn_state_flags & CONN_CLOSING)) {
13068 		/*
13069 		 * The conn is either already in the drain list or closing.
13070 		 * (We needed to check for CONN_CLOSING again since close can
13071 		 * sneak in between dropping conn_lock and acquiring idl_lock.)
13072 		 */
13073 		mutex_exit(&idl->idl_lock);
13074 		return;
13075 	}
13076 
13077 	/*
13078 	 * The conn is not in the drain list. Insert it at the
13079 	 * tail of the drain list. The drain list is circular
13080 	 * and doubly linked. idl_conn points to the 1st element
13081 	 * in the list.
13082 	 */
13083 	if (idl->idl_conn == NULL) {
13084 		idl->idl_conn = connp;
13085 		connp->conn_drain_next = connp;
13086 		connp->conn_drain_prev = connp;
13087 	} else {
13088 		conn_t *head = idl->idl_conn;
13089 
13090 		connp->conn_drain_next = head;
13091 		connp->conn_drain_prev = head->conn_drain_prev;
13092 		head->conn_drain_prev->conn_drain_next = connp;
13093 		head->conn_drain_prev = connp;
13094 	}
13095 	/*
13096 	 * For non streams based sockets assert flow control.
13097 	 */
13098 	conn_setqfull(connp, NULL);
13099 	mutex_exit(&idl->idl_lock);
13100 }
13101 
13102 static void
13103 conn_drain_remove(conn_t *connp)
13104 {
13105 	idl_t *idl = connp->conn_idl;
13106 
13107 	if (idl != NULL) {
13108 		/*
13109 		 * Remove ourself from the drain list.
13110 		 */
13111 		if (connp->conn_drain_next == connp) {
13112 			/* Singleton in the list */
13113 			ASSERT(connp->conn_drain_prev == connp);
13114 			idl->idl_conn = NULL;
13115 		} else {
13116 			connp->conn_drain_prev->conn_drain_next =
13117 			    connp->conn_drain_next;
13118 			connp->conn_drain_next->conn_drain_prev =
13119 			    connp->conn_drain_prev;
13120 			if (idl->idl_conn == connp)
13121 				idl->idl_conn = connp->conn_drain_next;
13122 		}
13123 
13124 		/*
13125 		 * NOTE: because conn_idl is associated with a specific drain
13126 		 * list which in turn is tied to the index the TX ring
13127 		 * (txl_cookie) hashes to, and because the TX ring can change
13128 		 * over the lifetime of the conn_t, we must clear conn_idl so
13129 		 * a subsequent conn_drain_insert() will set conn_idl again
13130 		 * based on the latest txl_cookie.
13131 		 */
13132 		connp->conn_idl = NULL;
13133 	}
13134 	connp->conn_drain_next = NULL;
13135 	connp->conn_drain_prev = NULL;
13136 
13137 	conn_clrqfull(connp, NULL);
13138 	/*
13139 	 * For streams based sockets open up flow control.
13140 	 */
13141 	if (!IPCL_IS_NONSTR(connp))
13142 		enableok(connp->conn_wq);
13143 }
13144 
13145 /*
13146  * This conn is closing, and we are called from ip_close. OR
13147  * this conn is draining because flow-control on the ill has been relieved.
13148  *
13149  * We must also need to remove conn's on this idl from the list, and also
13150  * inform the sockfs upcalls about the change in flow-control.
13151  */
13152 static void
13153 conn_drain(conn_t *connp, boolean_t closing)
13154 {
13155 	idl_t *idl;
13156 	conn_t *next_connp;
13157 
13158 	/*
13159 	 * connp->conn_idl is stable at this point, and no lock is needed
13160 	 * to check it. If we are called from ip_close, close has already
13161 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13162 	 * called us only because conn_idl is non-null. If we are called thru
13163 	 * service, conn_idl could be null, but it cannot change because
13164 	 * service is single-threaded per queue, and there cannot be another
13165 	 * instance of service trying to call conn_drain_insert on this conn
13166 	 * now.
13167 	 */
13168 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13169 
13170 	/*
13171 	 * If the conn doesn't exist or is not on a drain list, bail.
13172 	 */
13173 	if (connp == NULL || connp->conn_idl == NULL ||
13174 	    connp->conn_drain_prev == NULL) {
13175 		return;
13176 	}
13177 
13178 	idl = connp->conn_idl;
13179 	ASSERT(MUTEX_HELD(&idl->idl_lock));
13180 
13181 	if (!closing) {
13182 		next_connp = connp->conn_drain_next;
13183 		while (next_connp != connp) {
13184 			conn_t *delconnp = next_connp;
13185 
13186 			next_connp = next_connp->conn_drain_next;
13187 			conn_drain_remove(delconnp);
13188 		}
13189 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13190 	}
13191 	conn_drain_remove(connp);
13192 }
13193 
13194 /*
13195  * Write service routine. Shared perimeter entry point.
13196  * The device queue's messages has fallen below the low water mark and STREAMS
13197  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13198  * each waiting conn.
13199  */
13200 void
13201 ip_wsrv(queue_t *q)
13202 {
13203 	ill_t	*ill;
13204 
13205 	ill = (ill_t *)q->q_ptr;
13206 	if (ill->ill_state_flags == 0) {
13207 		ip_stack_t *ipst = ill->ill_ipst;
13208 
13209 		/*
13210 		 * The device flow control has opened up.
13211 		 * Walk through conn drain lists and qenable the
13212 		 * first conn in each list. This makes sense only
13213 		 * if the stream is fully plumbed and setup.
13214 		 * Hence the ill_state_flags check above.
13215 		 */
13216 		ip1dbg(("ip_wsrv: walking\n"));
13217 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13218 		enableok(ill->ill_wq);
13219 	}
13220 }
13221 
13222 /*
13223  * Callback to disable flow control in IP.
13224  *
13225  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13226  * is enabled.
13227  *
13228  * When MAC_TX() is not able to send any more packets, dld sets its queue
13229  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13230  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13231  * function and wakes up corresponding mac worker threads, which in turn
13232  * calls this callback function, and disables flow control.
13233  */
13234 void
13235 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13236 {
13237 	ill_t *ill = (ill_t *)arg;
13238 	ip_stack_t *ipst = ill->ill_ipst;
13239 	idl_tx_list_t *idl_txl;
13240 
13241 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13242 	mutex_enter(&idl_txl->txl_lock);
13243 	/* add code to to set a flag to indicate idl_txl is enabled */
13244 	conn_walk_drain(ipst, idl_txl);
13245 	mutex_exit(&idl_txl->txl_lock);
13246 }
13247 
13248 /*
13249  * Flow control has been relieved and STREAMS has backenabled us; drain
13250  * all the conn lists on `tx_list'.
13251  */
13252 static void
13253 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13254 {
13255 	int i;
13256 	idl_t *idl;
13257 
13258 	IP_STAT(ipst, ip_conn_walk_drain);
13259 
13260 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13261 		idl = &tx_list->txl_drain_list[i];
13262 		mutex_enter(&idl->idl_lock);
13263 		conn_drain(idl->idl_conn, B_FALSE);
13264 		mutex_exit(&idl->idl_lock);
13265 	}
13266 }
13267 
13268 /*
13269  * Determine if the ill and multicast aspects of that packets
13270  * "matches" the conn.
13271  */
13272 boolean_t
13273 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13274 {
13275 	ill_t		*ill = ira->ira_rill;
13276 	zoneid_t	zoneid = ira->ira_zoneid;
13277 	uint_t		in_ifindex;
13278 	ipaddr_t	dst, src;
13279 
13280 	dst = ipha->ipha_dst;
13281 	src = ipha->ipha_src;
13282 
13283 	/*
13284 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13285 	 * unicast, broadcast and multicast reception to
13286 	 * conn_incoming_ifindex.
13287 	 * conn_wantpacket is called for unicast, broadcast and
13288 	 * multicast packets.
13289 	 */
13290 	in_ifindex = connp->conn_incoming_ifindex;
13291 
13292 	/* mpathd can bind to the under IPMP interface, which we allow */
13293 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13294 		if (!IS_UNDER_IPMP(ill))
13295 			return (B_FALSE);
13296 
13297 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13298 			return (B_FALSE);
13299 	}
13300 
13301 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13302 		return (B_FALSE);
13303 
13304 	if (!(ira->ira_flags & IRAF_MULTICAST))
13305 		return (B_TRUE);
13306 
13307 	if (connp->conn_multi_router) {
13308 		/* multicast packet and multicast router socket: send up */
13309 		return (B_TRUE);
13310 	}
13311 
13312 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13313 	    ipha->ipha_protocol == IPPROTO_RSVP)
13314 		return (B_TRUE);
13315 
13316 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13317 }
13318 
13319 void
13320 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13321 {
13322 	if (IPCL_IS_NONSTR(connp)) {
13323 		(*connp->conn_upcalls->su_txq_full)
13324 		    (connp->conn_upper_handle, B_TRUE);
13325 		if (flow_stopped != NULL)
13326 			*flow_stopped = B_TRUE;
13327 	} else {
13328 		queue_t *q = connp->conn_wq;
13329 
13330 		ASSERT(q != NULL);
13331 		if (!(q->q_flag & QFULL)) {
13332 			mutex_enter(QLOCK(q));
13333 			if (!(q->q_flag & QFULL)) {
13334 				/* still need to set QFULL */
13335 				q->q_flag |= QFULL;
13336 				/* set flow_stopped to true under QLOCK */
13337 				if (flow_stopped != NULL)
13338 					*flow_stopped = B_TRUE;
13339 				mutex_exit(QLOCK(q));
13340 			} else {
13341 				/* flow_stopped is left unchanged */
13342 				mutex_exit(QLOCK(q));
13343 			}
13344 		}
13345 	}
13346 }
13347 
13348 void
13349 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13350 {
13351 	if (IPCL_IS_NONSTR(connp)) {
13352 		(*connp->conn_upcalls->su_txq_full)
13353 		    (connp->conn_upper_handle, B_FALSE);
13354 		if (flow_stopped != NULL)
13355 			*flow_stopped = B_FALSE;
13356 	} else {
13357 		queue_t *q = connp->conn_wq;
13358 
13359 		ASSERT(q != NULL);
13360 		if (q->q_flag & QFULL) {
13361 			mutex_enter(QLOCK(q));
13362 			if (q->q_flag & QFULL) {
13363 				q->q_flag &= ~QFULL;
13364 				/* set flow_stopped to false under QLOCK */
13365 				if (flow_stopped != NULL)
13366 					*flow_stopped = B_FALSE;
13367 				mutex_exit(QLOCK(q));
13368 				if (q->q_flag & QWANTW)
13369 					qbackenable(q, 0);
13370 			} else {
13371 				/* flow_stopped is left unchanged */
13372 				mutex_exit(QLOCK(q));
13373 			}
13374 		}
13375 	}
13376 
13377 	mutex_enter(&connp->conn_lock);
13378 	connp->conn_blocked = B_FALSE;
13379 	mutex_exit(&connp->conn_lock);
13380 }
13381 
13382 /*
13383  * Return the length in bytes of the IPv4 headers (base header, label, and
13384  * other IP options) that will be needed based on the
13385  * ip_pkt_t structure passed by the caller.
13386  *
13387  * The returned length does not include the length of the upper level
13388  * protocol (ULP) header.
13389  * The caller needs to check that the length doesn't exceed the max for IPv4.
13390  */
13391 int
13392 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13393 {
13394 	int len;
13395 
13396 	len = IP_SIMPLE_HDR_LENGTH;
13397 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13398 		ASSERT(ipp->ipp_label_len_v4 != 0);
13399 		/* We need to round up here */
13400 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13401 	}
13402 
13403 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13404 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13405 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13406 		len += ipp->ipp_ipv4_options_len;
13407 	}
13408 	return (len);
13409 }
13410 
13411 /*
13412  * All-purpose routine to build an IPv4 header with options based
13413  * on the abstract ip_pkt_t.
13414  *
13415  * The caller has to set the source and destination address as well as
13416  * ipha_length. The caller has to massage any source route and compensate
13417  * for the ULP pseudo-header checksum due to the source route.
13418  */
13419 void
13420 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13421     uint8_t protocol)
13422 {
13423 	ipha_t	*ipha = (ipha_t *)buf;
13424 	uint8_t *cp;
13425 
13426 	/* Initialize IPv4 header */
13427 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13428 	ipha->ipha_length = 0;	/* Caller will set later */
13429 	ipha->ipha_ident = 0;
13430 	ipha->ipha_fragment_offset_and_flags = 0;
13431 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13432 	ipha->ipha_protocol = protocol;
13433 	ipha->ipha_hdr_checksum = 0;
13434 
13435 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13436 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13437 		ipha->ipha_src = ipp->ipp_addr_v4;
13438 
13439 	cp = (uint8_t *)&ipha[1];
13440 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13441 		ASSERT(ipp->ipp_label_len_v4 != 0);
13442 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13443 		cp += ipp->ipp_label_len_v4;
13444 		/* We need to round up here */
13445 		while ((uintptr_t)cp & 0x3) {
13446 			*cp++ = IPOPT_NOP;
13447 		}
13448 	}
13449 
13450 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13451 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13452 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13453 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13454 		cp += ipp->ipp_ipv4_options_len;
13455 	}
13456 	ipha->ipha_version_and_hdr_length =
13457 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13458 
13459 	ASSERT((int)(cp - buf) == buf_len);
13460 }
13461 
13462 /* Allocate the private structure */
13463 static int
13464 ip_priv_alloc(void **bufp)
13465 {
13466 	void	*buf;
13467 
13468 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13469 		return (ENOMEM);
13470 
13471 	*bufp = buf;
13472 	return (0);
13473 }
13474 
13475 /* Function to delete the private structure */
13476 void
13477 ip_priv_free(void *buf)
13478 {
13479 	ASSERT(buf != NULL);
13480 	kmem_free(buf, sizeof (ip_priv_t));
13481 }
13482 
13483 /*
13484  * The entry point for IPPF processing.
13485  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13486  * routine just returns.
13487  *
13488  * When called, ip_process generates an ipp_packet_t structure
13489  * which holds the state information for this packet and invokes the
13490  * the classifier (via ipp_packet_process). The classification, depending on
13491  * configured filters, results in a list of actions for this packet. Invoking
13492  * an action may cause the packet to be dropped, in which case we return NULL.
13493  * proc indicates the callout position for
13494  * this packet and ill is the interface this packet arrived on or will leave
13495  * on (inbound and outbound resp.).
13496  *
13497  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13498  * on the ill corrsponding to the destination IP address.
13499  */
13500 mblk_t *
13501 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13502 {
13503 	ip_priv_t	*priv;
13504 	ipp_action_id_t	aid;
13505 	int		rc = 0;
13506 	ipp_packet_t	*pp;
13507 
13508 	/* If the classifier is not loaded, return  */
13509 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13510 		return (mp);
13511 	}
13512 
13513 	ASSERT(mp != NULL);
13514 
13515 	/* Allocate the packet structure */
13516 	rc = ipp_packet_alloc(&pp, "ip", aid);
13517 	if (rc != 0)
13518 		goto drop;
13519 
13520 	/* Allocate the private structure */
13521 	rc = ip_priv_alloc((void **)&priv);
13522 	if (rc != 0) {
13523 		ipp_packet_free(pp);
13524 		goto drop;
13525 	}
13526 	priv->proc = proc;
13527 	priv->ill_index = ill_get_upper_ifindex(rill);
13528 
13529 	ipp_packet_set_private(pp, priv, ip_priv_free);
13530 	ipp_packet_set_data(pp, mp);
13531 
13532 	/* Invoke the classifier */
13533 	rc = ipp_packet_process(&pp);
13534 	if (pp != NULL) {
13535 		mp = ipp_packet_get_data(pp);
13536 		ipp_packet_free(pp);
13537 		if (rc != 0)
13538 			goto drop;
13539 		return (mp);
13540 	} else {
13541 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13542 		mp = NULL;
13543 	}
13544 drop:
13545 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13546 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13547 		ip_drop_input("ip_process", mp, ill);
13548 	} else {
13549 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13550 		ip_drop_output("ip_process", mp, ill);
13551 	}
13552 	freemsg(mp);
13553 	return (NULL);
13554 }
13555 
13556 /*
13557  * Propagate a multicast group membership operation (add/drop) on
13558  * all the interfaces crossed by the related multirt routes.
13559  * The call is considered successful if the operation succeeds
13560  * on at least one interface.
13561  *
13562  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13563  * multicast addresses with the ire argument being the first one.
13564  * We walk the bucket to find all the of those.
13565  *
13566  * Common to IPv4 and IPv6.
13567  */
13568 static int
13569 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13570     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13571     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13572     mcast_record_t fmode, const in6_addr_t *v6src)
13573 {
13574 	ire_t		*ire_gw;
13575 	irb_t		*irb;
13576 	int		ifindex;
13577 	int		error = 0;
13578 	int		result;
13579 	ip_stack_t	*ipst = ire->ire_ipst;
13580 	ipaddr_t	group;
13581 	boolean_t	isv6;
13582 	int		match_flags;
13583 
13584 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13585 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13586 		isv6 = B_FALSE;
13587 	} else {
13588 		isv6 = B_TRUE;
13589 	}
13590 
13591 	irb = ire->ire_bucket;
13592 	ASSERT(irb != NULL);
13593 
13594 	result = 0;
13595 	irb_refhold(irb);
13596 	for (; ire != NULL; ire = ire->ire_next) {
13597 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13598 			continue;
13599 
13600 		/* We handle -ifp routes by matching on the ill if set */
13601 		match_flags = MATCH_IRE_TYPE;
13602 		if (ire->ire_ill != NULL)
13603 			match_flags |= MATCH_IRE_ILL;
13604 
13605 		if (isv6) {
13606 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13607 				continue;
13608 
13609 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13610 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13611 			    match_flags, 0, ipst, NULL);
13612 		} else {
13613 			if (ire->ire_addr != group)
13614 				continue;
13615 
13616 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13617 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13618 			    match_flags, 0, ipst, NULL);
13619 		}
13620 		/* No interface route exists for the gateway; skip this ire. */
13621 		if (ire_gw == NULL)
13622 			continue;
13623 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13624 			ire_refrele(ire_gw);
13625 			continue;
13626 		}
13627 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13628 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13629 
13630 		/*
13631 		 * The operation is considered a success if
13632 		 * it succeeds at least once on any one interface.
13633 		 */
13634 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13635 		    fmode, v6src);
13636 		if (error == 0)
13637 			result = CGTP_MCAST_SUCCESS;
13638 
13639 		ire_refrele(ire_gw);
13640 	}
13641 	irb_refrele(irb);
13642 	/*
13643 	 * Consider the call as successful if we succeeded on at least
13644 	 * one interface. Otherwise, return the last encountered error.
13645 	 */
13646 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13647 }
13648 
13649 /*
13650  * Return the expected CGTP hooks version number.
13651  */
13652 int
13653 ip_cgtp_filter_supported(void)
13654 {
13655 	return (ip_cgtp_filter_rev);
13656 }
13657 
13658 /*
13659  * CGTP hooks can be registered by invoking this function.
13660  * Checks that the version number matches.
13661  */
13662 int
13663 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13664 {
13665 	netstack_t *ns;
13666 	ip_stack_t *ipst;
13667 
13668 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13669 		return (ENOTSUP);
13670 
13671 	ns = netstack_find_by_stackid(stackid);
13672 	if (ns == NULL)
13673 		return (EINVAL);
13674 	ipst = ns->netstack_ip;
13675 	ASSERT(ipst != NULL);
13676 
13677 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13678 		netstack_rele(ns);
13679 		return (EALREADY);
13680 	}
13681 
13682 	ipst->ips_ip_cgtp_filter_ops = ops;
13683 
13684 	ill_set_inputfn_all(ipst);
13685 
13686 	netstack_rele(ns);
13687 	return (0);
13688 }
13689 
13690 /*
13691  * CGTP hooks can be unregistered by invoking this function.
13692  * Returns ENXIO if there was no registration.
13693  * Returns EBUSY if the ndd variable has not been turned off.
13694  */
13695 int
13696 ip_cgtp_filter_unregister(netstackid_t stackid)
13697 {
13698 	netstack_t *ns;
13699 	ip_stack_t *ipst;
13700 
13701 	ns = netstack_find_by_stackid(stackid);
13702 	if (ns == NULL)
13703 		return (EINVAL);
13704 	ipst = ns->netstack_ip;
13705 	ASSERT(ipst != NULL);
13706 
13707 	if (ipst->ips_ip_cgtp_filter) {
13708 		netstack_rele(ns);
13709 		return (EBUSY);
13710 	}
13711 
13712 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13713 		netstack_rele(ns);
13714 		return (ENXIO);
13715 	}
13716 	ipst->ips_ip_cgtp_filter_ops = NULL;
13717 
13718 	ill_set_inputfn_all(ipst);
13719 
13720 	netstack_rele(ns);
13721 	return (0);
13722 }
13723 
13724 /*
13725  * Check whether there is a CGTP filter registration.
13726  * Returns non-zero if there is a registration, otherwise returns zero.
13727  * Note: returns zero if bad stackid.
13728  */
13729 int
13730 ip_cgtp_filter_is_registered(netstackid_t stackid)
13731 {
13732 	netstack_t *ns;
13733 	ip_stack_t *ipst;
13734 	int ret;
13735 
13736 	ns = netstack_find_by_stackid(stackid);
13737 	if (ns == NULL)
13738 		return (0);
13739 	ipst = ns->netstack_ip;
13740 	ASSERT(ipst != NULL);
13741 
13742 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13743 		ret = 1;
13744 	else
13745 		ret = 0;
13746 
13747 	netstack_rele(ns);
13748 	return (ret);
13749 }
13750 
13751 static int
13752 ip_squeue_switch(int val)
13753 {
13754 	int rval;
13755 
13756 	switch (val) {
13757 	case IP_SQUEUE_ENTER_NODRAIN:
13758 		rval = SQ_NODRAIN;
13759 		break;
13760 	case IP_SQUEUE_ENTER:
13761 		rval = SQ_PROCESS;
13762 		break;
13763 	case IP_SQUEUE_FILL:
13764 	default:
13765 		rval = SQ_FILL;
13766 		break;
13767 	}
13768 	return (rval);
13769 }
13770 
13771 static void *
13772 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13773 {
13774 	kstat_t *ksp;
13775 
13776 	ip_stat_t template = {
13777 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
13778 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
13779 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
13780 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13781 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13782 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13783 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13784 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13785 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13786 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13787 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13788 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13789 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13790 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13791 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13792 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13793 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13794 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13795 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13796 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13797 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13798 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13799 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13800 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13801 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13802 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13803 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13804 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13805 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13806 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13807 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
13808 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
13809 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
13810 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
13811 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
13812 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
13813 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
13814 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
13815 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
13816 	};
13817 
13818 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13819 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13820 	    KSTAT_FLAG_VIRTUAL, stackid);
13821 
13822 	if (ksp == NULL)
13823 		return (NULL);
13824 
13825 	bcopy(&template, ip_statisticsp, sizeof (template));
13826 	ksp->ks_data = (void *)ip_statisticsp;
13827 	ksp->ks_private = (void *)(uintptr_t)stackid;
13828 
13829 	kstat_install(ksp);
13830 	return (ksp);
13831 }
13832 
13833 static void
13834 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13835 {
13836 	if (ksp != NULL) {
13837 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13838 		kstat_delete_netstack(ksp, stackid);
13839 	}
13840 }
13841 
13842 static void *
13843 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13844 {
13845 	kstat_t	*ksp;
13846 
13847 	ip_named_kstat_t template = {
13848 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
13849 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
13850 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
13851 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
13852 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
13853 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
13854 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
13855 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
13856 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
13857 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
13858 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
13859 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
13860 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
13861 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
13862 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
13863 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
13864 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
13865 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
13866 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
13867 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
13868 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
13869 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
13870 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
13871 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
13872 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
13873 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
13874 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
13875 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
13876 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
13877 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
13878 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
13879 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
13880 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
13881 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
13882 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
13883 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
13884 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
13885 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
13886 	};
13887 
13888 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
13889 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
13890 	if (ksp == NULL || ksp->ks_data == NULL)
13891 		return (NULL);
13892 
13893 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
13894 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
13895 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
13896 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
13897 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
13898 
13899 	template.netToMediaEntrySize.value.i32 =
13900 	    sizeof (mib2_ipNetToMediaEntry_t);
13901 
13902 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
13903 
13904 	bcopy(&template, ksp->ks_data, sizeof (template));
13905 	ksp->ks_update = ip_kstat_update;
13906 	ksp->ks_private = (void *)(uintptr_t)stackid;
13907 
13908 	kstat_install(ksp);
13909 	return (ksp);
13910 }
13911 
13912 static void
13913 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
13914 {
13915 	if (ksp != NULL) {
13916 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13917 		kstat_delete_netstack(ksp, stackid);
13918 	}
13919 }
13920 
13921 static int
13922 ip_kstat_update(kstat_t *kp, int rw)
13923 {
13924 	ip_named_kstat_t *ipkp;
13925 	mib2_ipIfStatsEntry_t ipmib;
13926 	ill_walk_context_t ctx;
13927 	ill_t *ill;
13928 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
13929 	netstack_t	*ns;
13930 	ip_stack_t	*ipst;
13931 
13932 	if (kp == NULL || kp->ks_data == NULL)
13933 		return (EIO);
13934 
13935 	if (rw == KSTAT_WRITE)
13936 		return (EACCES);
13937 
13938 	ns = netstack_find_by_stackid(stackid);
13939 	if (ns == NULL)
13940 		return (-1);
13941 	ipst = ns->netstack_ip;
13942 	if (ipst == NULL) {
13943 		netstack_rele(ns);
13944 		return (-1);
13945 	}
13946 	ipkp = (ip_named_kstat_t *)kp->ks_data;
13947 
13948 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
13949 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
13950 	ill = ILL_START_WALK_V4(&ctx, ipst);
13951 	for (; ill != NULL; ill = ill_next(&ctx, ill))
13952 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
13953 	rw_exit(&ipst->ips_ill_g_lock);
13954 
13955 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
13956 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
13957 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
13958 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
13959 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
13960 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
13961 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
13962 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
13963 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
13964 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
13965 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
13966 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
13967 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
13968 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
13969 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
13970 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
13971 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
13972 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
13973 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
13974 
13975 	ipkp->routingDiscards.value.ui32 =	0;
13976 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
13977 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
13978 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
13979 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
13980 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
13981 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
13982 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
13983 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
13984 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
13985 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
13986 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
13987 
13988 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
13989 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
13990 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
13991 
13992 	netstack_rele(ns);
13993 
13994 	return (0);
13995 }
13996 
13997 static void *
13998 icmp_kstat_init(netstackid_t stackid)
13999 {
14000 	kstat_t	*ksp;
14001 
14002 	icmp_named_kstat_t template = {
14003 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14004 		{ "inErrors",		KSTAT_DATA_UINT32 },
14005 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14006 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14007 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14008 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14009 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14010 		{ "inEchos",		KSTAT_DATA_UINT32 },
14011 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14012 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14013 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14014 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14015 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14016 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14017 		{ "outErrors",		KSTAT_DATA_UINT32 },
14018 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14019 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14020 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14021 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14022 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14023 		{ "outEchos",		KSTAT_DATA_UINT32 },
14024 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14025 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14026 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14027 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14028 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14029 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14030 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14031 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14032 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14033 		{ "outDrops",		KSTAT_DATA_UINT32 },
14034 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14035 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14036 	};
14037 
14038 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14039 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14040 	if (ksp == NULL || ksp->ks_data == NULL)
14041 		return (NULL);
14042 
14043 	bcopy(&template, ksp->ks_data, sizeof (template));
14044 
14045 	ksp->ks_update = icmp_kstat_update;
14046 	ksp->ks_private = (void *)(uintptr_t)stackid;
14047 
14048 	kstat_install(ksp);
14049 	return (ksp);
14050 }
14051 
14052 static void
14053 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14054 {
14055 	if (ksp != NULL) {
14056 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14057 		kstat_delete_netstack(ksp, stackid);
14058 	}
14059 }
14060 
14061 static int
14062 icmp_kstat_update(kstat_t *kp, int rw)
14063 {
14064 	icmp_named_kstat_t *icmpkp;
14065 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14066 	netstack_t	*ns;
14067 	ip_stack_t	*ipst;
14068 
14069 	if ((kp == NULL) || (kp->ks_data == NULL))
14070 		return (EIO);
14071 
14072 	if (rw == KSTAT_WRITE)
14073 		return (EACCES);
14074 
14075 	ns = netstack_find_by_stackid(stackid);
14076 	if (ns == NULL)
14077 		return (-1);
14078 	ipst = ns->netstack_ip;
14079 	if (ipst == NULL) {
14080 		netstack_rele(ns);
14081 		return (-1);
14082 	}
14083 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14084 
14085 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14086 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14087 	icmpkp->inDestUnreachs.value.ui32 =
14088 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14089 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14090 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14091 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14092 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14093 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14094 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14095 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14096 	icmpkp->inTimestampReps.value.ui32 =
14097 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14098 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14099 	icmpkp->inAddrMaskReps.value.ui32 =
14100 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14101 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14102 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14103 	icmpkp->outDestUnreachs.value.ui32 =
14104 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14105 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14106 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14107 	icmpkp->outSrcQuenchs.value.ui32 =
14108 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14109 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14110 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14111 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14112 	icmpkp->outTimestamps.value.ui32 =
14113 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14114 	icmpkp->outTimestampReps.value.ui32 =
14115 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14116 	icmpkp->outAddrMasks.value.ui32 =
14117 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14118 	icmpkp->outAddrMaskReps.value.ui32 =
14119 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14120 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14121 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14122 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14123 	icmpkp->outFragNeeded.value.ui32 =
14124 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14125 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14126 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14127 	icmpkp->inBadRedirects.value.ui32 =
14128 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14129 
14130 	netstack_rele(ns);
14131 	return (0);
14132 }
14133 
14134 /*
14135  * This is the fanout function for raw socket opened for SCTP.  Note
14136  * that it is called after SCTP checks that there is no socket which
14137  * wants a packet.  Then before SCTP handles this out of the blue packet,
14138  * this function is called to see if there is any raw socket for SCTP.
14139  * If there is and it is bound to the correct address, the packet will
14140  * be sent to that socket.  Note that only one raw socket can be bound to
14141  * a port.  This is assured in ipcl_sctp_hash_insert();
14142  */
14143 void
14144 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14145     ip_recv_attr_t *ira)
14146 {
14147 	conn_t		*connp;
14148 	queue_t		*rq;
14149 	boolean_t	secure;
14150 	ill_t		*ill = ira->ira_ill;
14151 	ip_stack_t	*ipst = ill->ill_ipst;
14152 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14153 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14154 	iaflags_t	iraflags = ira->ira_flags;
14155 	ill_t		*rill = ira->ira_rill;
14156 
14157 	secure = iraflags & IRAF_IPSEC_SECURE;
14158 
14159 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14160 	    ira, ipst);
14161 	if (connp == NULL) {
14162 		/*
14163 		 * Although raw sctp is not summed, OOB chunks must be.
14164 		 * Drop the packet here if the sctp checksum failed.
14165 		 */
14166 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14167 			SCTPS_BUMP_MIB(sctps, sctpChecksumError);
14168 			freemsg(mp);
14169 			return;
14170 		}
14171 		ira->ira_ill = ira->ira_rill = NULL;
14172 		sctp_ootb_input(mp, ira, ipst);
14173 		ira->ira_ill = ill;
14174 		ira->ira_rill = rill;
14175 		return;
14176 	}
14177 	rq = connp->conn_rq;
14178 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14179 		CONN_DEC_REF(connp);
14180 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14181 		freemsg(mp);
14182 		return;
14183 	}
14184 	if (((iraflags & IRAF_IS_IPV4) ?
14185 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14186 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14187 	    secure) {
14188 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14189 		    ip6h, ira);
14190 		if (mp == NULL) {
14191 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14192 			/* Note that mp is NULL */
14193 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14194 			CONN_DEC_REF(connp);
14195 			return;
14196 		}
14197 	}
14198 
14199 	if (iraflags & IRAF_ICMP_ERROR) {
14200 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14201 	} else {
14202 		ill_t *rill = ira->ira_rill;
14203 
14204 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14205 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14206 		ira->ira_ill = ira->ira_rill = NULL;
14207 		(connp->conn_recv)(connp, mp, NULL, ira);
14208 		ira->ira_ill = ill;
14209 		ira->ira_rill = rill;
14210 	}
14211 	CONN_DEC_REF(connp);
14212 }
14213 
14214 /*
14215  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14216  * header before the ip payload.
14217  */
14218 static void
14219 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14220 {
14221 	int len = (mp->b_wptr - mp->b_rptr);
14222 	mblk_t *ip_mp;
14223 
14224 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14225 	if (is_fp_mp || len != fp_mp_len) {
14226 		if (len > fp_mp_len) {
14227 			/*
14228 			 * fastpath header and ip header in the first mblk
14229 			 */
14230 			mp->b_rptr += fp_mp_len;
14231 		} else {
14232 			/*
14233 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14234 			 * attach the fastpath header before ip header.
14235 			 */
14236 			ip_mp = mp->b_cont;
14237 			freeb(mp);
14238 			mp = ip_mp;
14239 			mp->b_rptr += (fp_mp_len - len);
14240 		}
14241 	} else {
14242 		ip_mp = mp->b_cont;
14243 		freeb(mp);
14244 		mp = ip_mp;
14245 	}
14246 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14247 	freemsg(mp);
14248 }
14249 
14250 /*
14251  * Normal post fragmentation function.
14252  *
14253  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14254  * using the same state machine.
14255  *
14256  * We return an error on failure. In particular we return EWOULDBLOCK
14257  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14258  * (currently by canputnext failure resulting in backenabling from GLD.)
14259  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14260  * indication that they can flow control until ip_wsrv() tells then to restart.
14261  *
14262  * If the nce passed by caller is incomplete, this function
14263  * queues the packet and if necessary, sends ARP request and bails.
14264  * If the Neighbor Cache passed is fully resolved, we simply prepend
14265  * the link-layer header to the packet, do ipsec hw acceleration
14266  * work if necessary, and send the packet out on the wire.
14267  */
14268 /* ARGSUSED6 */
14269 int
14270 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14271     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14272 {
14273 	queue_t		*wq;
14274 	ill_t		*ill = nce->nce_ill;
14275 	ip_stack_t	*ipst = ill->ill_ipst;
14276 	uint64_t	delta;
14277 	boolean_t	isv6 = ill->ill_isv6;
14278 	boolean_t	fp_mp;
14279 	ncec_t		*ncec = nce->nce_common;
14280 	int64_t		now = LBOLT_FASTPATH64;
14281 	boolean_t	is_probe;
14282 
14283 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14284 
14285 	ASSERT(mp != NULL);
14286 	ASSERT(mp->b_datap->db_type == M_DATA);
14287 	ASSERT(pkt_len == msgdsize(mp));
14288 
14289 	/*
14290 	 * If we have already been here and are coming back after ARP/ND.
14291 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14292 	 * in that case since they have seen the packet when it came here
14293 	 * the first time.
14294 	 */
14295 	if (ixaflags & IXAF_NO_TRACE)
14296 		goto sendit;
14297 
14298 	if (ixaflags & IXAF_IS_IPV4) {
14299 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14300 
14301 		ASSERT(!isv6);
14302 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14303 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14304 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14305 			int	error;
14306 
14307 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14308 			    ipst->ips_ipv4firewall_physical_out,
14309 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14310 			DTRACE_PROBE1(ip4__physical__out__end,
14311 			    mblk_t *, mp);
14312 			if (mp == NULL)
14313 				return (error);
14314 
14315 			/* The length could have changed */
14316 			pkt_len = msgdsize(mp);
14317 		}
14318 		if (ipst->ips_ip4_observe.he_interested) {
14319 			/*
14320 			 * Note that for TX the zoneid is the sending
14321 			 * zone, whether or not MLP is in play.
14322 			 * Since the szone argument is the IP zoneid (i.e.,
14323 			 * zero for exclusive-IP zones) and ipobs wants
14324 			 * the system zoneid, we map it here.
14325 			 */
14326 			szone = IP_REAL_ZONEID(szone, ipst);
14327 
14328 			/*
14329 			 * On the outbound path the destination zone will be
14330 			 * unknown as we're sending this packet out on the
14331 			 * wire.
14332 			 */
14333 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14334 			    ill, ipst);
14335 		}
14336 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14337 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14338 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14339 	} else {
14340 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14341 
14342 		ASSERT(isv6);
14343 		ASSERT(pkt_len ==
14344 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14345 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14346 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14347 			int	error;
14348 
14349 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14350 			    ipst->ips_ipv6firewall_physical_out,
14351 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14352 			DTRACE_PROBE1(ip6__physical__out__end,
14353 			    mblk_t *, mp);
14354 			if (mp == NULL)
14355 				return (error);
14356 
14357 			/* The length could have changed */
14358 			pkt_len = msgdsize(mp);
14359 		}
14360 		if (ipst->ips_ip6_observe.he_interested) {
14361 			/* See above */
14362 			szone = IP_REAL_ZONEID(szone, ipst);
14363 
14364 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14365 			    ill, ipst);
14366 		}
14367 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14368 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14369 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14370 	}
14371 
14372 sendit:
14373 	/*
14374 	 * We check the state without a lock because the state can never
14375 	 * move "backwards" to initial or incomplete.
14376 	 */
14377 	switch (ncec->ncec_state) {
14378 	case ND_REACHABLE:
14379 	case ND_STALE:
14380 	case ND_DELAY:
14381 	case ND_PROBE:
14382 		mp = ip_xmit_attach_llhdr(mp, nce);
14383 		if (mp == NULL) {
14384 			/*
14385 			 * ip_xmit_attach_llhdr has increased
14386 			 * ipIfStatsOutDiscards and called ip_drop_output()
14387 			 */
14388 			return (ENOBUFS);
14389 		}
14390 		/*
14391 		 * check if nce_fastpath completed and we tagged on a
14392 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14393 		 */
14394 		fp_mp = (mp->b_datap->db_type == M_DATA);
14395 
14396 		if (fp_mp &&
14397 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14398 			ill_dld_direct_t *idd;
14399 
14400 			idd = &ill->ill_dld_capab->idc_direct;
14401 			/*
14402 			 * Send the packet directly to DLD, where it
14403 			 * may be queued depending on the availability
14404 			 * of transmit resources at the media layer.
14405 			 * Return value should be taken into
14406 			 * account and flow control the TCP.
14407 			 */
14408 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14409 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14410 			    pkt_len);
14411 
14412 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14413 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14414 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14415 			} else {
14416 				uintptr_t cookie;
14417 
14418 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14419 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14420 					if (ixacookie != NULL)
14421 						*ixacookie = cookie;
14422 					return (EWOULDBLOCK);
14423 				}
14424 			}
14425 		} else {
14426 			wq = ill->ill_wq;
14427 
14428 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14429 			    !canputnext(wq)) {
14430 				if (ixacookie != NULL)
14431 					*ixacookie = 0;
14432 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14433 				    nce->nce_fp_mp != NULL ?
14434 				    MBLKL(nce->nce_fp_mp) : 0);
14435 				return (EWOULDBLOCK);
14436 			}
14437 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14438 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14439 			    pkt_len);
14440 			putnext(wq, mp);
14441 		}
14442 
14443 		/*
14444 		 * The rest of this function implements Neighbor Unreachability
14445 		 * detection. Determine if the ncec is eligible for NUD.
14446 		 */
14447 		if (ncec->ncec_flags & NCE_F_NONUD)
14448 			return (0);
14449 
14450 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14451 
14452 		/*
14453 		 * Check for upper layer advice
14454 		 */
14455 		if (ixaflags & IXAF_REACH_CONF) {
14456 			timeout_id_t tid;
14457 
14458 			/*
14459 			 * It should be o.k. to check the state without
14460 			 * a lock here, at most we lose an advice.
14461 			 */
14462 			ncec->ncec_last = TICK_TO_MSEC(now);
14463 			if (ncec->ncec_state != ND_REACHABLE) {
14464 				mutex_enter(&ncec->ncec_lock);
14465 				ncec->ncec_state = ND_REACHABLE;
14466 				tid = ncec->ncec_timeout_id;
14467 				ncec->ncec_timeout_id = 0;
14468 				mutex_exit(&ncec->ncec_lock);
14469 				(void) untimeout(tid);
14470 				if (ip_debug > 2) {
14471 					/* ip1dbg */
14472 					pr_addr_dbg("ip_xmit: state"
14473 					    " for %s changed to"
14474 					    " REACHABLE\n", AF_INET6,
14475 					    &ncec->ncec_addr);
14476 				}
14477 			}
14478 			return (0);
14479 		}
14480 
14481 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14482 		ip1dbg(("ip_xmit: delta = %" PRId64
14483 		    " ill_reachable_time = %d \n", delta,
14484 		    ill->ill_reachable_time));
14485 		if (delta > (uint64_t)ill->ill_reachable_time) {
14486 			mutex_enter(&ncec->ncec_lock);
14487 			switch (ncec->ncec_state) {
14488 			case ND_REACHABLE:
14489 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14490 				/* FALLTHROUGH */
14491 			case ND_STALE:
14492 				/*
14493 				 * ND_REACHABLE is identical to
14494 				 * ND_STALE in this specific case. If
14495 				 * reachable time has expired for this
14496 				 * neighbor (delta is greater than
14497 				 * reachable time), conceptually, the
14498 				 * neighbor cache is no longer in
14499 				 * REACHABLE state, but already in
14500 				 * STALE state.  So the correct
14501 				 * transition here is to ND_DELAY.
14502 				 */
14503 				ncec->ncec_state = ND_DELAY;
14504 				mutex_exit(&ncec->ncec_lock);
14505 				nce_restart_timer(ncec,
14506 				    ipst->ips_delay_first_probe_time);
14507 				if (ip_debug > 3) {
14508 					/* ip2dbg */
14509 					pr_addr_dbg("ip_xmit: state"
14510 					    " for %s changed to"
14511 					    " DELAY\n", AF_INET6,
14512 					    &ncec->ncec_addr);
14513 				}
14514 				break;
14515 			case ND_DELAY:
14516 			case ND_PROBE:
14517 				mutex_exit(&ncec->ncec_lock);
14518 				/* Timers have already started */
14519 				break;
14520 			case ND_UNREACHABLE:
14521 				/*
14522 				 * nce_timer has detected that this ncec
14523 				 * is unreachable and initiated deleting
14524 				 * this ncec.
14525 				 * This is a harmless race where we found the
14526 				 * ncec before it was deleted and have
14527 				 * just sent out a packet using this
14528 				 * unreachable ncec.
14529 				 */
14530 				mutex_exit(&ncec->ncec_lock);
14531 				break;
14532 			default:
14533 				ASSERT(0);
14534 				mutex_exit(&ncec->ncec_lock);
14535 			}
14536 		}
14537 		return (0);
14538 
14539 	case ND_INCOMPLETE:
14540 		/*
14541 		 * the state could have changed since we didn't hold the lock.
14542 		 * Re-verify state under lock.
14543 		 */
14544 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14545 		mutex_enter(&ncec->ncec_lock);
14546 		if (NCE_ISREACHABLE(ncec)) {
14547 			mutex_exit(&ncec->ncec_lock);
14548 			goto sendit;
14549 		}
14550 		/* queue the packet */
14551 		nce_queue_mp(ncec, mp, is_probe);
14552 		mutex_exit(&ncec->ncec_lock);
14553 		DTRACE_PROBE2(ip__xmit__incomplete,
14554 		    (ncec_t *), ncec, (mblk_t *), mp);
14555 		return (0);
14556 
14557 	case ND_INITIAL:
14558 		/*
14559 		 * State could have changed since we didn't hold the lock, so
14560 		 * re-verify state.
14561 		 */
14562 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14563 		mutex_enter(&ncec->ncec_lock);
14564 		if (NCE_ISREACHABLE(ncec))  {
14565 			mutex_exit(&ncec->ncec_lock);
14566 			goto sendit;
14567 		}
14568 		nce_queue_mp(ncec, mp, is_probe);
14569 		if (ncec->ncec_state == ND_INITIAL) {
14570 			ncec->ncec_state = ND_INCOMPLETE;
14571 			mutex_exit(&ncec->ncec_lock);
14572 			/*
14573 			 * figure out the source we want to use
14574 			 * and resolve it.
14575 			 */
14576 			ip_ndp_resolve(ncec);
14577 		} else  {
14578 			mutex_exit(&ncec->ncec_lock);
14579 		}
14580 		return (0);
14581 
14582 	case ND_UNREACHABLE:
14583 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14584 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14585 		    mp, ill);
14586 		freemsg(mp);
14587 		return (0);
14588 
14589 	default:
14590 		ASSERT(0);
14591 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14592 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14593 		    mp, ill);
14594 		freemsg(mp);
14595 		return (ENETUNREACH);
14596 	}
14597 }
14598 
14599 /*
14600  * Return B_TRUE if the buffers differ in length or content.
14601  * This is used for comparing extension header buffers.
14602  * Note that an extension header would be declared different
14603  * even if all that changed was the next header value in that header i.e.
14604  * what really changed is the next extension header.
14605  */
14606 boolean_t
14607 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14608     uint_t blen)
14609 {
14610 	if (!b_valid)
14611 		blen = 0;
14612 
14613 	if (alen != blen)
14614 		return (B_TRUE);
14615 	if (alen == 0)
14616 		return (B_FALSE);	/* Both zero length */
14617 	return (bcmp(abuf, bbuf, alen));
14618 }
14619 
14620 /*
14621  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14622  * Return B_FALSE if memory allocation fails - don't change any state!
14623  */
14624 boolean_t
14625 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14626     const void *src, uint_t srclen)
14627 {
14628 	void *dst;
14629 
14630 	if (!src_valid)
14631 		srclen = 0;
14632 
14633 	ASSERT(*dstlenp == 0);
14634 	if (src != NULL && srclen != 0) {
14635 		dst = mi_alloc(srclen, BPRI_MED);
14636 		if (dst == NULL)
14637 			return (B_FALSE);
14638 	} else {
14639 		dst = NULL;
14640 	}
14641 	if (*dstp != NULL)
14642 		mi_free(*dstp);
14643 	*dstp = dst;
14644 	*dstlenp = dst == NULL ? 0 : srclen;
14645 	return (B_TRUE);
14646 }
14647 
14648 /*
14649  * Replace what is in *dst, *dstlen with the source.
14650  * Assumes ip_allocbuf has already been called.
14651  */
14652 void
14653 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14654     const void *src, uint_t srclen)
14655 {
14656 	if (!src_valid)
14657 		srclen = 0;
14658 
14659 	ASSERT(*dstlenp == srclen);
14660 	if (src != NULL && srclen != 0)
14661 		bcopy(src, *dstp, srclen);
14662 }
14663 
14664 /*
14665  * Free the storage pointed to by the members of an ip_pkt_t.
14666  */
14667 void
14668 ip_pkt_free(ip_pkt_t *ipp)
14669 {
14670 	uint_t	fields = ipp->ipp_fields;
14671 
14672 	if (fields & IPPF_HOPOPTS) {
14673 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14674 		ipp->ipp_hopopts = NULL;
14675 		ipp->ipp_hopoptslen = 0;
14676 	}
14677 	if (fields & IPPF_RTHDRDSTOPTS) {
14678 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14679 		ipp->ipp_rthdrdstopts = NULL;
14680 		ipp->ipp_rthdrdstoptslen = 0;
14681 	}
14682 	if (fields & IPPF_DSTOPTS) {
14683 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14684 		ipp->ipp_dstopts = NULL;
14685 		ipp->ipp_dstoptslen = 0;
14686 	}
14687 	if (fields & IPPF_RTHDR) {
14688 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14689 		ipp->ipp_rthdr = NULL;
14690 		ipp->ipp_rthdrlen = 0;
14691 	}
14692 	if (fields & IPPF_IPV4_OPTIONS) {
14693 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14694 		ipp->ipp_ipv4_options = NULL;
14695 		ipp->ipp_ipv4_options_len = 0;
14696 	}
14697 	if (fields & IPPF_LABEL_V4) {
14698 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14699 		ipp->ipp_label_v4 = NULL;
14700 		ipp->ipp_label_len_v4 = 0;
14701 	}
14702 	if (fields & IPPF_LABEL_V6) {
14703 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14704 		ipp->ipp_label_v6 = NULL;
14705 		ipp->ipp_label_len_v6 = 0;
14706 	}
14707 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14708 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14709 }
14710 
14711 /*
14712  * Copy from src to dst and allocate as needed.
14713  * Returns zero or ENOMEM.
14714  *
14715  * The caller must initialize dst to zero.
14716  */
14717 int
14718 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14719 {
14720 	uint_t	fields = src->ipp_fields;
14721 
14722 	/* Start with fields that don't require memory allocation */
14723 	dst->ipp_fields = fields &
14724 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14725 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14726 
14727 	dst->ipp_addr = src->ipp_addr;
14728 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14729 	dst->ipp_hoplimit = src->ipp_hoplimit;
14730 	dst->ipp_tclass = src->ipp_tclass;
14731 	dst->ipp_type_of_service = src->ipp_type_of_service;
14732 
14733 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14734 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14735 		return (0);
14736 
14737 	if (fields & IPPF_HOPOPTS) {
14738 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14739 		if (dst->ipp_hopopts == NULL) {
14740 			ip_pkt_free(dst);
14741 			return (ENOMEM);
14742 		}
14743 		dst->ipp_fields |= IPPF_HOPOPTS;
14744 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14745 		    src->ipp_hopoptslen);
14746 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14747 	}
14748 	if (fields & IPPF_RTHDRDSTOPTS) {
14749 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14750 		    kmflag);
14751 		if (dst->ipp_rthdrdstopts == NULL) {
14752 			ip_pkt_free(dst);
14753 			return (ENOMEM);
14754 		}
14755 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14756 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14757 		    src->ipp_rthdrdstoptslen);
14758 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14759 	}
14760 	if (fields & IPPF_DSTOPTS) {
14761 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14762 		if (dst->ipp_dstopts == NULL) {
14763 			ip_pkt_free(dst);
14764 			return (ENOMEM);
14765 		}
14766 		dst->ipp_fields |= IPPF_DSTOPTS;
14767 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14768 		    src->ipp_dstoptslen);
14769 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14770 	}
14771 	if (fields & IPPF_RTHDR) {
14772 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14773 		if (dst->ipp_rthdr == NULL) {
14774 			ip_pkt_free(dst);
14775 			return (ENOMEM);
14776 		}
14777 		dst->ipp_fields |= IPPF_RTHDR;
14778 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14779 		    src->ipp_rthdrlen);
14780 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14781 	}
14782 	if (fields & IPPF_IPV4_OPTIONS) {
14783 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14784 		    kmflag);
14785 		if (dst->ipp_ipv4_options == NULL) {
14786 			ip_pkt_free(dst);
14787 			return (ENOMEM);
14788 		}
14789 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14790 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14791 		    src->ipp_ipv4_options_len);
14792 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14793 	}
14794 	if (fields & IPPF_LABEL_V4) {
14795 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14796 		if (dst->ipp_label_v4 == NULL) {
14797 			ip_pkt_free(dst);
14798 			return (ENOMEM);
14799 		}
14800 		dst->ipp_fields |= IPPF_LABEL_V4;
14801 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14802 		    src->ipp_label_len_v4);
14803 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14804 	}
14805 	if (fields & IPPF_LABEL_V6) {
14806 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14807 		if (dst->ipp_label_v6 == NULL) {
14808 			ip_pkt_free(dst);
14809 			return (ENOMEM);
14810 		}
14811 		dst->ipp_fields |= IPPF_LABEL_V6;
14812 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14813 		    src->ipp_label_len_v6);
14814 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14815 	}
14816 	if (fields & IPPF_FRAGHDR) {
14817 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14818 		if (dst->ipp_fraghdr == NULL) {
14819 			ip_pkt_free(dst);
14820 			return (ENOMEM);
14821 		}
14822 		dst->ipp_fields |= IPPF_FRAGHDR;
14823 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14824 		    src->ipp_fraghdrlen);
14825 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14826 	}
14827 	return (0);
14828 }
14829 
14830 /*
14831  * Returns INADDR_ANY if no source route
14832  */
14833 ipaddr_t
14834 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14835 {
14836 	ipaddr_t	nexthop = INADDR_ANY;
14837 	ipoptp_t	opts;
14838 	uchar_t		*opt;
14839 	uint8_t		optval;
14840 	uint8_t		optlen;
14841 	uint32_t	totallen;
14842 
14843 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14844 		return (INADDR_ANY);
14845 
14846 	totallen = ipp->ipp_ipv4_options_len;
14847 	if (totallen & 0x3)
14848 		return (INADDR_ANY);
14849 
14850 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14851 	    optval != IPOPT_EOL;
14852 	    optval = ipoptp_next(&opts)) {
14853 		opt = opts.ipoptp_cur;
14854 		switch (optval) {
14855 			uint8_t off;
14856 		case IPOPT_SSRR:
14857 		case IPOPT_LSRR:
14858 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14859 				break;
14860 			}
14861 			optlen = opts.ipoptp_len;
14862 			off = opt[IPOPT_OFFSET];
14863 			off--;
14864 			if (optlen < IP_ADDR_LEN ||
14865 			    off > optlen - IP_ADDR_LEN) {
14866 				/* End of source route */
14867 				break;
14868 			}
14869 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
14870 			if (nexthop == htonl(INADDR_LOOPBACK)) {
14871 				/* Ignore */
14872 				nexthop = INADDR_ANY;
14873 				break;
14874 			}
14875 			break;
14876 		}
14877 	}
14878 	return (nexthop);
14879 }
14880 
14881 /*
14882  * Reverse a source route.
14883  */
14884 void
14885 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
14886 {
14887 	ipaddr_t	tmp;
14888 	ipoptp_t	opts;
14889 	uchar_t		*opt;
14890 	uint8_t		optval;
14891 	uint32_t	totallen;
14892 
14893 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14894 		return;
14895 
14896 	totallen = ipp->ipp_ipv4_options_len;
14897 	if (totallen & 0x3)
14898 		return;
14899 
14900 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14901 	    optval != IPOPT_EOL;
14902 	    optval = ipoptp_next(&opts)) {
14903 		uint8_t off1, off2;
14904 
14905 		opt = opts.ipoptp_cur;
14906 		switch (optval) {
14907 		case IPOPT_SSRR:
14908 		case IPOPT_LSRR:
14909 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14910 				break;
14911 			}
14912 			off1 = IPOPT_MINOFF_SR - 1;
14913 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
14914 			while (off2 > off1) {
14915 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
14916 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
14917 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
14918 				off2 -= IP_ADDR_LEN;
14919 				off1 += IP_ADDR_LEN;
14920 			}
14921 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
14922 			break;
14923 		}
14924 	}
14925 }
14926 
14927 /*
14928  * Returns NULL if no routing header
14929  */
14930 in6_addr_t *
14931 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
14932 {
14933 	in6_addr_t	*nexthop = NULL;
14934 	ip6_rthdr0_t	*rthdr;
14935 
14936 	if (!(ipp->ipp_fields & IPPF_RTHDR))
14937 		return (NULL);
14938 
14939 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
14940 	if (rthdr->ip6r0_segleft == 0)
14941 		return (NULL);
14942 
14943 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
14944 	return (nexthop);
14945 }
14946 
14947 zoneid_t
14948 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
14949     zoneid_t lookup_zoneid)
14950 {
14951 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
14952 	ire_t		*ire;
14953 	int		ire_flags = MATCH_IRE_TYPE;
14954 	zoneid_t	zoneid = ALL_ZONES;
14955 
14956 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
14957 		return (ALL_ZONES);
14958 
14959 	if (lookup_zoneid != ALL_ZONES)
14960 		ire_flags |= MATCH_IRE_ZONEONLY;
14961 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
14962 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
14963 	if (ire != NULL) {
14964 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
14965 		ire_refrele(ire);
14966 	}
14967 	return (zoneid);
14968 }
14969 
14970 zoneid_t
14971 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
14972     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
14973 {
14974 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
14975 	ire_t		*ire;
14976 	int		ire_flags = MATCH_IRE_TYPE;
14977 	zoneid_t	zoneid = ALL_ZONES;
14978 
14979 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
14980 		return (ALL_ZONES);
14981 
14982 	if (IN6_IS_ADDR_LINKLOCAL(addr))
14983 		ire_flags |= MATCH_IRE_ILL;
14984 
14985 	if (lookup_zoneid != ALL_ZONES)
14986 		ire_flags |= MATCH_IRE_ZONEONLY;
14987 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
14988 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
14989 	if (ire != NULL) {
14990 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
14991 		ire_refrele(ire);
14992 	}
14993 	return (zoneid);
14994 }
14995 
14996 /*
14997  * IP obserability hook support functions.
14998  */
14999 static void
15000 ipobs_init(ip_stack_t *ipst)
15001 {
15002 	netid_t id;
15003 
15004 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15005 
15006 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15007 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15008 
15009 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15010 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15011 }
15012 
15013 static void
15014 ipobs_fini(ip_stack_t *ipst)
15015 {
15016 
15017 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15018 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15019 }
15020 
15021 /*
15022  * hook_pkt_observe_t is composed in network byte order so that the
15023  * entire mblk_t chain handed into hook_run can be used as-is.
15024  * The caveat is that use of the fields, such as the zone fields,
15025  * requires conversion into host byte order first.
15026  */
15027 void
15028 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15029     const ill_t *ill, ip_stack_t *ipst)
15030 {
15031 	hook_pkt_observe_t *hdr;
15032 	uint64_t grifindex;
15033 	mblk_t *imp;
15034 
15035 	imp = allocb(sizeof (*hdr), BPRI_HI);
15036 	if (imp == NULL)
15037 		return;
15038 
15039 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15040 	/*
15041 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15042 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15043 	 */
15044 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15045 	imp->b_cont = mp;
15046 
15047 	ASSERT(DB_TYPE(mp) == M_DATA);
15048 
15049 	if (IS_UNDER_IPMP(ill))
15050 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15051 	else
15052 		grifindex = 0;
15053 
15054 	hdr->hpo_version = 1;
15055 	hdr->hpo_htype = htons(htype);
15056 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15057 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15058 	hdr->hpo_grifindex = htonl(grifindex);
15059 	hdr->hpo_zsrc = htonl(zsrc);
15060 	hdr->hpo_zdst = htonl(zdst);
15061 	hdr->hpo_pkt = imp;
15062 	hdr->hpo_ctx = ipst->ips_netstack;
15063 
15064 	if (ill->ill_isv6) {
15065 		hdr->hpo_family = AF_INET6;
15066 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15067 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15068 	} else {
15069 		hdr->hpo_family = AF_INET;
15070 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15071 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15072 	}
15073 
15074 	imp->b_cont = NULL;
15075 	freemsg(imp);
15076 }
15077 
15078 /*
15079  * Utility routine that checks if `v4srcp' is a valid address on underlying
15080  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15081  * associated with `v4srcp' on success.  NOTE: if this is not called from
15082  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15083  * group during or after this lookup.
15084  */
15085 boolean_t
15086 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15087 {
15088 	ipif_t *ipif;
15089 
15090 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15091 	if (ipif != NULL) {
15092 		if (ipifp != NULL)
15093 			*ipifp = ipif;
15094 		else
15095 			ipif_refrele(ipif);
15096 		return (B_TRUE);
15097 	}
15098 
15099 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15100 	    *v4srcp));
15101 	return (B_FALSE);
15102 }
15103 
15104 /*
15105  * Transport protocol call back function for CPU state change.
15106  */
15107 /* ARGSUSED */
15108 static int
15109 ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
15110 {
15111 	processorid_t cpu_seqid;
15112 	netstack_handle_t nh;
15113 	netstack_t *ns;
15114 
15115 	ASSERT(MUTEX_HELD(&cpu_lock));
15116 	cpu_seqid = cpu[id]->cpu_seqid;
15117 
15118 	switch (what) {
15119 	case CPU_CONFIG:
15120 	case CPU_ON:
15121 	case CPU_INIT:
15122 	case CPU_CPUPART_IN:
15123 		netstack_next_init(&nh);
15124 		while ((ns = netstack_next(&nh)) != NULL) {
15125 			tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
15126 			sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
15127 			udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
15128 			netstack_rele(ns);
15129 		}
15130 		netstack_next_fini(&nh);
15131 		break;
15132 	case CPU_UNCONFIG:
15133 	case CPU_OFF:
15134 	case CPU_CPUPART_OUT:
15135 		/*
15136 		 * Nothing to do.  We don't remove the per CPU stats from
15137 		 * the IP stack even when the CPU goes offline.
15138 		 */
15139 		break;
15140 	default:
15141 		break;
15142 	}
15143 	return (0);
15144 }
15145