xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 6e0cbcaa0c6f2bc34634a4cc17b099f9ecef03d1)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 1990 Mentat Inc.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/stream.h>
29 #include <sys/dlpi.h>
30 #include <sys/stropts.h>
31 #include <sys/sysmacros.h>
32 #include <sys/strsubr.h>
33 #include <sys/strlog.h>
34 #include <sys/strsun.h>
35 #include <sys/zone.h>
36 #define	_SUN_TPI_VERSION 2
37 #include <sys/tihdr.h>
38 #include <sys/xti_inet.h>
39 #include <sys/ddi.h>
40 #include <sys/suntpi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/sadb.h>
98 #include <inet/ipsec_impl.h>
99 #include <inet/iptun/iptun_impl.h>
100 #include <inet/ipdrop.h>
101 #include <inet/ip_netinfo.h>
102 #include <inet/ilb_ip.h>
103 
104 #include <sys/ethernet.h>
105 #include <net/if_types.h>
106 #include <sys/cpuvar.h>
107 
108 #include <ipp/ipp.h>
109 #include <ipp/ipp_impl.h>
110 #include <ipp/ipgpc/ipgpc.h>
111 
112 #include <sys/pattr.h>
113 #include <inet/ipclassifier.h>
114 #include <inet/sctp_ip.h>
115 #include <inet/sctp/sctp_impl.h>
116 #include <inet/udp_impl.h>
117 #include <inet/rawip_impl.h>
118 #include <inet/rts_impl.h>
119 
120 #include <sys/tsol/label.h>
121 #include <sys/tsol/tnet.h>
122 
123 #include <sys/squeue_impl.h>
124 #include <inet/ip_arp.h>
125 
126 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
131  * IP_SQUEUE_ENTER: SQ_PROCESS
132  * IP_SQUEUE_FILL: SQ_FILL
133  */
134 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
135 
136 int ip_squeue_flag;
137 
138 /*
139  * Setable in /etc/system
140  */
141 int ip_poll_normal_ms = 100;
142 int ip_poll_normal_ticks = 0;
143 int ip_modclose_ackwait_ms = 3000;
144 
145 /*
146  * It would be nice to have these present only in DEBUG systems, but the
147  * current design of the global symbol checking logic requires them to be
148  * unconditionally present.
149  */
150 uint_t ip_thread_data;			/* TSD key for debug support */
151 krwlock_t ip_thread_rwlock;
152 list_t	ip_thread_list;
153 
154 /*
155  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
156  */
157 
158 struct listptr_s {
159 	mblk_t	*lp_head;	/* pointer to the head of the list */
160 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
161 };
162 
163 typedef struct listptr_s listptr_t;
164 
165 /*
166  * This is used by ip_snmp_get_mib2_ip_route_media and
167  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
168  */
169 typedef struct iproutedata_s {
170 	uint_t		ird_idx;
171 	uint_t		ird_flags;	/* see below */
172 	listptr_t	ird_route;	/* ipRouteEntryTable */
173 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
174 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
175 } iproutedata_t;
176 
177 /* Include ire_testhidden and IRE_IF_CLONE routes */
178 #define	IRD_REPORT_ALL	0x01
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
199     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
200     void *args) = NULL;
201 
202 /*
203  * Hook function to generate cluster wide SPI.
204  */
205 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
206     void *) = NULL;
207 
208 /*
209  * Hook function to verify if the SPI is already utlized.
210  */
211 
212 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
213 
214 /*
215  * Hook function to delete the SPI from the cluster wide repository.
216  */
217 
218 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
219 
220 /*
221  * Hook function to inform the cluster when packet received on an IDLE SA
222  */
223 
224 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
225     in6_addr_t, in6_addr_t, void *) = NULL;
226 
227 /*
228  * Synchronization notes:
229  *
230  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
231  * MT level protection given by STREAMS. IP uses a combination of its own
232  * internal serialization mechanism and standard Solaris locking techniques.
233  * The internal serialization is per phyint.  This is used to serialize
234  * plumbing operations, IPMP operations, most set ioctls, etc.
235  *
236  * Plumbing is a long sequence of operations involving message
237  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
238  * involved in plumbing operations. A natural model is to serialize these
239  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
240  * parallel without any interference. But various set ioctls on hme0 are best
241  * serialized, along with IPMP operations and processing of DLPI control
242  * messages received from drivers on a per phyint basis. This serialization is
243  * provided by the ipsq_t and primitives operating on this. Details can
244  * be found in ip_if.c above the core primitives operating on ipsq_t.
245  *
246  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
247  * Simiarly lookup of an ire by a thread also returns a refheld ire.
248  * In addition ipif's and ill's referenced by the ire are also indirectly
249  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
250  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
251  * address of an ipif has to go through the ipsq_t. This ensures that only
252  * one such exclusive operation proceeds at any time on the ipif. It then
253  * waits for all refcnts
254  * associated with this ipif to come down to zero. The address is changed
255  * only after the ipif has been quiesced. Then the ipif is brought up again.
256  * More details are described above the comment in ip_sioctl_flags.
257  *
258  * Packet processing is based mostly on IREs and are fully multi-threaded
259  * using standard Solaris MT techniques.
260  *
261  * There are explicit locks in IP to handle:
262  * - The ip_g_head list maintained by mi_open_link() and friends.
263  *
264  * - The reassembly data structures (one lock per hash bucket)
265  *
266  * - conn_lock is meant to protect conn_t fields. The fields actually
267  *   protected by conn_lock are documented in the conn_t definition.
268  *
269  * - ire_lock to protect some of the fields of the ire, IRE tables
270  *   (one lock per hash bucket). Refer to ip_ire.c for details.
271  *
272  * - ndp_g_lock and ncec_lock for protecting NCEs.
273  *
274  * - ill_lock protects fields of the ill and ipif. Details in ip.h
275  *
276  * - ill_g_lock: This is a global reader/writer lock. Protects the following
277  *	* The AVL tree based global multi list of all ills.
278  *	* The linked list of all ipifs of an ill
279  *	* The <ipsq-xop> mapping
280  *	* <ill-phyint> association
281  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
282  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
283  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
284  *   writer for the actual duration of the insertion/deletion/change.
285  *
286  * - ill_lock:  This is a per ill mutex.
287  *   It protects some members of the ill_t struct; see ip.h for details.
288  *   It also protects the <ill-phyint> assoc.
289  *   It also protects the list of ipifs hanging off the ill.
290  *
291  * - ipsq_lock: This is a per ipsq_t mutex lock.
292  *   This protects some members of the ipsq_t struct; see ip.h for details.
293  *   It also protects the <ipsq-ipxop> mapping
294  *
295  * - ipx_lock: This is a per ipxop_t mutex lock.
296  *   This protects some members of the ipxop_t struct; see ip.h for details.
297  *
298  * - phyint_lock: This is a per phyint mutex lock. Protects just the
299  *   phyint_flags
300  *
301  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
302  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
303  *   uniqueness check also done atomically.
304  *
305  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
306  *   group list linked by ill_usesrc_grp_next. It also protects the
307  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
308  *   group is being added or deleted.  This lock is taken as a reader when
309  *   walking the list/group(eg: to get the number of members in a usesrc group).
310  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
311  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
312  *   example, it is not necessary to take this lock in the initial portion
313  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
314  *   operations are executed exclusively and that ensures that the "usesrc
315  *   group state" cannot change. The "usesrc group state" change can happen
316  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ipsq-xop> assocications:
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ipsq-xop> association, the ill_g_lock must be held as
325  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
326  * This is only done when ills are added or removed from IPMP groups.
327  *
328  * To add or delete an ipif from the list of ipifs hanging off the ill,
329  * ill_g_lock (writer) and ill_lock must be held and the thread must be
330  * a writer on the associated ipsq.
331  *
332  * To add or delete an ill to the system, the ill_g_lock must be held as
333  * writer and the thread must be a writer on the associated ipsq.
334  *
335  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
336  * must be a writer on the associated ipsq.
337  *
338  * Lock hierarchy
339  *
340  * Some lock hierarchy scenarios are listed below.
341  *
342  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
343  * ill_g_lock -> ill_lock(s) -> phyint_lock
344  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
345  * ill_g_lock -> ip_addr_avail_lock
346  * conn_lock -> irb_lock -> ill_lock -> ire_lock
347  * ill_g_lock -> ip_g_nd_lock
348  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
350  * arl_lock -> ill_lock
351  * ips_ire_dep_lock -> irb_lock
352  *
353  * When more than 1 ill lock is needed to be held, all ill lock addresses
354  * are sorted on address and locked starting from highest addressed lock
355  * downward.
356  *
357  * Multicast scenarios
358  * ips_ill_g_lock -> ill_mcast_lock
359  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
360  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
361  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
362  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
363  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
364  *
365  * IPsec scenarios
366  *
367  * ipsa_lock -> ill_g_lock -> ill_lock
368  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
369  *
370  * Trusted Solaris scenarios
371  *
372  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
373  * igsa_lock -> gcdb_lock
374  * gcgrp_rwlock -> ire_lock
375  * gcgrp_rwlock -> gcdb_lock
376  *
377  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
378  *
379  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
380  * sq_lock -> conn_lock -> QLOCK(q)
381  * ill_lock -> ft_lock -> fe_lock
382  *
383  * Routing/forwarding table locking notes:
384  *
385  * Lock acquisition order: Radix tree lock, irb_lock.
386  * Requirements:
387  * i.  Walker must not hold any locks during the walker callback.
388  * ii  Walker must not see a truncated tree during the walk because of any node
389  *     deletion.
390  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
391  *     in many places in the code to walk the irb list. Thus even if all the
392  *     ires in a bucket have been deleted, we still can't free the radix node
393  *     until the ires have actually been inactive'd (freed).
394  *
395  * Tree traversal - Need to hold the global tree lock in read mode.
396  * Before dropping the global tree lock, need to either increment the ire_refcnt
397  * to ensure that the radix node can't be deleted.
398  *
399  * Tree add - Need to hold the global tree lock in write mode to add a
400  * radix node. To prevent the node from being deleted, increment the
401  * irb_refcnt, after the node is added to the tree. The ire itself is
402  * added later while holding the irb_lock, but not the tree lock.
403  *
404  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
405  * All associated ires must be inactive (i.e. freed), and irb_refcnt
406  * must be zero.
407  *
408  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
409  * global tree lock (read mode) for traversal.
410  *
411  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
412  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
413  *
414  * IPsec notes :
415  *
416  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
417  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
418  * ip_xmit_attr_t has the
419  * information used by the IPsec code for applying the right level of
420  * protection. The information initialized by IP in the ip_xmit_attr_t
421  * is determined by the per-socket policy or global policy in the system.
422  * For inbound datagrams, the ip_recv_attr_t
423  * starts out with nothing in it. It gets filled
424  * with the right information if it goes through the AH/ESP code, which
425  * happens if the incoming packet is secure. The information initialized
426  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
427  * the policy requirements needed by per-socket policy or global policy
428  * is met or not.
429  *
430  * For fully connected sockets i.e dst, src [addr, port] is known,
431  * conn_policy_cached is set indicating that policy has been cached.
432  * conn_in_enforce_policy may or may not be set depending on whether
433  * there is a global policy match or per-socket policy match.
434  * Policy inheriting happpens in ip_policy_set once the destination is known.
435  * Once the right policy is set on the conn_t, policy cannot change for
436  * this socket. This makes life simpler for TCP (UDP ?) where
437  * re-transmissions go out with the same policy. For symmetry, policy
438  * is cached for fully connected UDP sockets also. Thus if policy is cached,
439  * it also implies that policy is latched i.e policy cannot change
440  * on these sockets. As we have the right policy on the conn, we don't
441  * have to lookup global policy for every outbound and inbound datagram
442  * and thus serving as an optimization. Note that a global policy change
443  * does not affect fully connected sockets if they have policy. If fully
444  * connected sockets did not have any policy associated with it, global
445  * policy change may affect them.
446  *
447  * IP Flow control notes:
448  * ---------------------
449  * Non-TCP streams are flow controlled by IP. The way this is accomplished
450  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
451  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
452  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
453  * functions.
454  *
455  * Per Tx ring udp flow control:
456  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
457  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
458  *
459  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
460  * To achieve best performance, outgoing traffic need to be fanned out among
461  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
462  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
463  * the address of connp as fanout hint to mac_tx(). Under flow controlled
464  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
465  * cookie points to a specific Tx ring that is blocked. The cookie is used to
466  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
467  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
468  * connp's. The drain list is not a single list but a configurable number of
469  * lists.
470  *
471  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
472  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
473  * which is equal to 128. This array in turn contains a pointer to idl_t[],
474  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
475  * list will point to the list of connp's that are flow controlled.
476  *
477  *                      ---------------   -------   -------   -------
478  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
479  *                   |  ---------------   -------   -------   -------
480  *                   |  ---------------   -------   -------   -------
481  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
482  * ----------------  |  ---------------   -------   -------   -------
483  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
484  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   .        .              .         .         .
487  *                   |  ---------------   -------   -------   -------
488  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
489  *                      ---------------   -------   -------   -------
490  *                      ---------------   -------   -------   -------
491  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
492  *                   |  ---------------   -------   -------   -------
493  *                   |  ---------------   -------   -------   -------
494  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
495  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
496  * ----------------  |        .              .         .         .
497  *                   |  ---------------   -------   -------   -------
498  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
499  *                      ---------------   -------   -------   -------
500  *     .....
501  * ----------------
502  * |idl_tx_list[n]|-> ...
503  * ----------------
504  *
505  * When mac_tx() returns a cookie, the cookie is hashed into an index into
506  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
507  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
508  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
509  * Further, conn_blocked is set to indicate that the conn is blocked.
510  *
511  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
512  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
513  * is again hashed to locate the appropriate idl_tx_list, which is then
514  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
515  * the drain list and calls conn_drain_remove() to clear flow control (via
516  * calling su_txq_full() or clearing QFULL), and remove the conn from the
517  * drain list.
518  *
519  * Note that the drain list is not a single list but a (configurable) array of
520  * lists (8 elements by default).  Synchronization between drain insertion and
521  * flow control wakeup is handled by using idl_txl->txl_lock, and only
522  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
523  *
524  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
525  * On the send side, if the packet cannot be sent down to the driver by IP
526  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
527  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
528  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
529  * control has been relieved, the blocked conns in the 0'th drain list are
530  * drained as in the non-STREAMS case.
531  *
532  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
533  * is done when the conn is inserted into the drain list (conn_drain_insert())
534  * and cleared when the conn is removed from the it (conn_drain_remove()).
535  *
536  * IPQOS notes:
537  *
538  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
539  * and IPQoS modules. IPPF includes hooks in IP at different control points
540  * (callout positions) which direct packets to IPQoS modules for policy
541  * processing. Policies, if present, are global.
542  *
543  * The callout positions are located in the following paths:
544  *		o local_in (packets destined for this host)
545  *		o local_out (packets orginating from this host )
546  *		o fwd_in  (packets forwarded by this m/c - inbound)
547  *		o fwd_out (packets forwarded by this m/c - outbound)
548  * Hooks at these callout points can be enabled/disabled using the ndd variable
549  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
550  * By default all the callout positions are enabled.
551  *
552  * Outbound (local_out)
553  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
554  *
555  * Inbound (local_in)
556  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
557  *
558  * Forwarding (in and out)
559  * Hooks are placed in ire_recv_forward_v4/v6.
560  *
561  * IP Policy Framework processing (IPPF processing)
562  * Policy processing for a packet is initiated by ip_process, which ascertains
563  * that the classifier (ipgpc) is loaded and configured, failing which the
564  * packet resumes normal processing in IP. If the clasifier is present, the
565  * packet is acted upon by one or more IPQoS modules (action instances), per
566  * filters configured in ipgpc and resumes normal IP processing thereafter.
567  * An action instance can drop a packet in course of its processing.
568  *
569  * Zones notes:
570  *
571  * The partitioning rules for networking are as follows:
572  * 1) Packets coming from a zone must have a source address belonging to that
573  * zone.
574  * 2) Packets coming from a zone can only be sent on a physical interface on
575  * which the zone has an IP address.
576  * 3) Between two zones on the same machine, packet delivery is only allowed if
577  * there's a matching route for the destination and zone in the forwarding
578  * table.
579  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
580  * different zones can bind to the same port with the wildcard address
581  * (INADDR_ANY).
582  *
583  * The granularity of interface partitioning is at the logical interface level.
584  * Therefore, every zone has its own IP addresses, and incoming packets can be
585  * attributed to a zone unambiguously. A logical interface is placed into a zone
586  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
587  * structure. Rule (1) is implemented by modifying the source address selection
588  * algorithm so that the list of eligible addresses is filtered based on the
589  * sending process zone.
590  *
591  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
592  * across all zones, depending on their type. Here is the break-up:
593  *
594  * IRE type				Shared/exclusive
595  * --------				----------------
596  * IRE_BROADCAST			Exclusive
597  * IRE_DEFAULT (default routes)		Shared (*)
598  * IRE_LOCAL				Exclusive (x)
599  * IRE_LOOPBACK				Exclusive
600  * IRE_PREFIX (net routes)		Shared (*)
601  * IRE_IF_NORESOLVER (interface routes)	Exclusive
602  * IRE_IF_RESOLVER (interface routes)	Exclusive
603  * IRE_IF_CLONE (interface routes)	Exclusive
604  * IRE_HOST (host routes)		Shared (*)
605  *
606  * (*) A zone can only use a default or off-subnet route if the gateway is
607  * directly reachable from the zone, that is, if the gateway's address matches
608  * one of the zone's logical interfaces.
609  *
610  * (x) IRE_LOCAL are handled a bit differently.
611  * When ip_restrict_interzone_loopback is set (the default),
612  * ire_route_recursive restricts loopback using an IRE_LOCAL
613  * between zone to the case when L2 would have conceptually looped the packet
614  * back, i.e. the loopback which is required since neither Ethernet drivers
615  * nor Ethernet hardware loops them back. This is the case when the normal
616  * routes (ignoring IREs with different zoneids) would send out the packet on
617  * the same ill as the ill with which is IRE_LOCAL is associated.
618  *
619  * Multiple zones can share a common broadcast address; typically all zones
620  * share the 255.255.255.255 address. Incoming as well as locally originated
621  * broadcast packets must be dispatched to all the zones on the broadcast
622  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
623  * since some zones may not be on the 10.16.72/24 network. To handle this, each
624  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
625  * sent to every zone that has an IRE_BROADCAST entry for the destination
626  * address on the input ill, see ip_input_broadcast().
627  *
628  * Applications in different zones can join the same multicast group address.
629  * The same logic applies for multicast as for broadcast. ip_input_multicast
630  * dispatches packets to all zones that have members on the physical interface.
631  */
632 
633 /*
634  * Squeue Fanout flags:
635  *	0: No fanout.
636  *	1: Fanout across all squeues
637  */
638 boolean_t	ip_squeue_fanout = 0;
639 
640 /*
641  * Maximum dups allowed per packet.
642  */
643 uint_t ip_max_frag_dups = 10;
644 
645 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
646 		    cred_t *credp, boolean_t isv6);
647 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
648 
649 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
650 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
651 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
652     ip_recv_attr_t *);
653 static void	icmp_options_update(ipha_t *);
654 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
655 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
656 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
657 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
658     ip_recv_attr_t *);
659 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
660 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
661     ip_recv_attr_t *);
662 
663 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
664 char		*ip_dot_addr(ipaddr_t, char *);
665 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
666 int		ip_close(queue_t *, int);
667 static char	*ip_dot_saddr(uchar_t *, char *);
668 static void	ip_lrput(queue_t *, mblk_t *);
669 ipaddr_t	ip_net_mask(ipaddr_t);
670 char		*ip_nv_lookup(nv_t *, int);
671 void	ip_rput(queue_t *, mblk_t *);
672 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
673 		    void *dummy_arg);
674 int		ip_snmp_get(queue_t *, mblk_t *, int);
675 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
676 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
678 		    ip_stack_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
680 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
703 		    ip_stack_t *ipst);
704 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
705 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
706 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
707 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
708 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
709 
710 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
711 		    mblk_t *);
712 
713 static void	conn_drain_init(ip_stack_t *);
714 static void	conn_drain_fini(ip_stack_t *);
715 static void	conn_drain(conn_t *connp, boolean_t closing);
716 
717 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
718 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
719 
720 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
721 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
722 static void	ip_stack_fini(netstackid_t stackid, void *arg);
723 
724 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
725     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
726     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
727     const in6_addr_t *);
728 
729 static int	ip_squeue_switch(int);
730 
731 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
732 static void	ip_kstat_fini(netstackid_t, kstat_t *);
733 static int	ip_kstat_update(kstat_t *kp, int rw);
734 static void	*icmp_kstat_init(netstackid_t);
735 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
736 static int	icmp_kstat_update(kstat_t *kp, int rw);
737 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
738 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
739 
740 static void	ipobs_init(ip_stack_t *);
741 static void	ipobs_fini(ip_stack_t *);
742 
743 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
744 
745 static long ip_rput_pullups;
746 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
747 
748 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
749 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
750 
751 int	ip_debug;
752 
753 /*
754  * Multirouting/CGTP stuff
755  */
756 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
757 
758 /*
759  * IP tunables related declarations. Definitions are in ip_tunables.c
760  */
761 extern mod_prop_info_t ip_propinfo_tbl[];
762 extern int ip_propinfo_count;
763 
764 /*
765  * Table of IP ioctls encoding the various properties of the ioctl and
766  * indexed based on the last byte of the ioctl command. Occasionally there
767  * is a clash, and there is more than 1 ioctl with the same last byte.
768  * In such a case 1 ioctl is encoded in the ndx table and the remaining
769  * ioctls are encoded in the misc table. An entry in the ndx table is
770  * retrieved by indexing on the last byte of the ioctl command and comparing
771  * the ioctl command with the value in the ndx table. In the event of a
772  * mismatch the misc table is then searched sequentially for the desired
773  * ioctl command.
774  *
775  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
776  */
777 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
778 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
779 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
780 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
781 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
782 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
783 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
784 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
785 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
786 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
787 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
788 
789 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
790 			MISC_CMD, ip_siocaddrt, NULL },
791 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
792 			MISC_CMD, ip_siocdelrt, NULL },
793 
794 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
795 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
796 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
797 			IF_CMD, ip_sioctl_get_addr, NULL },
798 
799 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
800 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
801 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
802 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
803 
804 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
805 			IPI_PRIV | IPI_WR,
806 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
807 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
808 			IPI_MODOK | IPI_GET_CMD,
809 			IF_CMD, ip_sioctl_get_flags, NULL },
810 
811 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
812 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
813 
814 	/* copyin size cannot be coded for SIOCGIFCONF */
815 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
816 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
817 
818 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
819 			IF_CMD, ip_sioctl_mtu, NULL },
820 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
821 			IF_CMD, ip_sioctl_get_mtu, NULL },
822 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
823 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
824 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
825 			IF_CMD, ip_sioctl_brdaddr, NULL },
826 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
827 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
828 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
829 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
830 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
831 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
832 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
833 			IF_CMD, ip_sioctl_metric, NULL },
834 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
835 
836 	/* See 166-168 below for extended SIOC*XARP ioctls */
837 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
838 			ARP_CMD, ip_sioctl_arp, NULL },
839 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
840 			ARP_CMD, ip_sioctl_arp, NULL },
841 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
842 			ARP_CMD, ip_sioctl_arp, NULL },
843 
844 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
845 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
846 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
847 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
848 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
849 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
850 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
851 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
852 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
853 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
854 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
855 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
856 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
857 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
858 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
859 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
860 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
861 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
862 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
863 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
864 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
865 
866 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
867 			MISC_CMD, if_unitsel, if_unitsel_restart },
868 
869 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
870 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
871 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
872 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
873 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
874 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
875 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
876 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
877 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
878 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
879 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
880 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
881 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
882 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
883 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
884 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
885 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
886 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
887 
888 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
889 			IPI_PRIV | IPI_WR | IPI_MODOK,
890 			IF_CMD, ip_sioctl_sifname, NULL },
891 
892 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
893 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
894 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
895 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
896 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
897 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
898 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
899 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
900 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
901 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
902 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
903 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
904 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
905 
906 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
907 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
908 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
909 			IF_CMD, ip_sioctl_get_muxid, NULL },
910 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
911 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
912 
913 	/* Both if and lif variants share same func */
914 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
915 			IF_CMD, ip_sioctl_get_lifindex, NULL },
916 	/* Both if and lif variants share same func */
917 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
918 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
919 
920 	/* copyin size cannot be coded for SIOCGIFCONF */
921 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
922 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
923 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
924 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
925 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
926 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
927 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
928 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
929 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
930 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
931 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
932 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
933 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
934 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
935 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
936 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
937 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
938 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
939 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
940 
941 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
942 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
943 			ip_sioctl_removeif_restart },
944 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
945 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
946 			LIF_CMD, ip_sioctl_addif, NULL },
947 #define	SIOCLIFADDR_NDX 112
948 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
949 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
950 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
951 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
952 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
953 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
954 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
955 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
956 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
957 			IPI_PRIV | IPI_WR,
958 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
959 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
960 			IPI_GET_CMD | IPI_MODOK,
961 			LIF_CMD, ip_sioctl_get_flags, NULL },
962 
963 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
964 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
965 
966 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
967 			ip_sioctl_get_lifconf, NULL },
968 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
969 			LIF_CMD, ip_sioctl_mtu, NULL },
970 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
971 			LIF_CMD, ip_sioctl_get_mtu, NULL },
972 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
973 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
974 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
975 			LIF_CMD, ip_sioctl_brdaddr, NULL },
976 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
977 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
978 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
979 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
980 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
981 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
982 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
983 			LIF_CMD, ip_sioctl_metric, NULL },
984 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
985 			IPI_PRIV | IPI_WR | IPI_MODOK,
986 			LIF_CMD, ip_sioctl_slifname,
987 			ip_sioctl_slifname_restart },
988 
989 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
990 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
991 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
992 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
993 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
994 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
995 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
996 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
997 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
998 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
999 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1000 			LIF_CMD, ip_sioctl_token, NULL },
1001 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1002 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1003 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1004 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1005 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1006 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1007 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1008 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1009 
1010 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1011 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1012 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1013 			LIF_CMD, ip_siocdelndp_v6, NULL },
1014 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1015 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1016 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1017 			LIF_CMD, ip_siocsetndp_v6, NULL },
1018 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1019 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1020 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1021 			MISC_CMD, ip_sioctl_tonlink, NULL },
1022 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1023 			MISC_CMD, ip_sioctl_tmysite, NULL },
1024 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1027 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1028 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1029 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1030 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1031 
1032 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 
1034 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1035 			LIF_CMD, ip_sioctl_get_binding, NULL },
1036 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1037 			IPI_PRIV | IPI_WR,
1038 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1039 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1040 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1041 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1042 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1043 
1044 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1045 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 
1049 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 
1051 	/* These are handled in ip_sioctl_copyin_setup itself */
1052 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1053 			MISC_CMD, NULL, NULL },
1054 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1055 			MISC_CMD, NULL, NULL },
1056 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1057 
1058 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1059 			ip_sioctl_get_lifconf, NULL },
1060 
1061 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1062 			XARP_CMD, ip_sioctl_arp, NULL },
1063 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1064 			XARP_CMD, ip_sioctl_arp, NULL },
1065 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1066 			XARP_CMD, ip_sioctl_arp, NULL },
1067 
1068 	/* SIOCPOPSOCKFS is not handled by IP */
1069 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1070 
1071 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1072 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1073 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1074 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1075 			ip_sioctl_slifzone_restart },
1076 	/* 172-174 are SCTP ioctls and not handled by IP */
1077 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1081 			IPI_GET_CMD, LIF_CMD,
1082 			ip_sioctl_get_lifusesrc, 0 },
1083 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1084 			IPI_PRIV | IPI_WR,
1085 			LIF_CMD, ip_sioctl_slifusesrc,
1086 			NULL },
1087 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1088 			ip_sioctl_get_lifsrcof, NULL },
1089 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1090 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1091 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1092 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1093 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1094 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1095 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1096 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1097 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* SIOCSENABLESDP is handled by SDP */
1099 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1100 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1101 	/* 185 */ { IPI_DONTCARE /* SIOCGIFHWADDR */, 0, 0, 0, NULL, NULL },
1102 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1103 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1104 			ip_sioctl_ilb_cmd, NULL },
1105 	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1106 	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1107 	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1108 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1109 	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1110 			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart }
1111 };
1112 
1113 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1114 
1115 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1116 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1117 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1118 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1119 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1120 	{ ND_GET,	0, 0, 0, NULL, NULL },
1121 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1122 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1123 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1124 		MISC_CMD, mrt_ioctl},
1125 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1126 		MISC_CMD, mrt_ioctl},
1127 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1128 		MISC_CMD, mrt_ioctl}
1129 };
1130 
1131 int ip_misc_ioctl_count =
1132     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1133 
1134 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1135 					/* Settable in /etc/system */
1136 /* Defined in ip_ire.c */
1137 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1138 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1139 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1140 
1141 static nv_t	ire_nv_arr[] = {
1142 	{ IRE_BROADCAST, "BROADCAST" },
1143 	{ IRE_LOCAL, "LOCAL" },
1144 	{ IRE_LOOPBACK, "LOOPBACK" },
1145 	{ IRE_DEFAULT, "DEFAULT" },
1146 	{ IRE_PREFIX, "PREFIX" },
1147 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1148 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1149 	{ IRE_IF_CLONE, "IF_CLONE" },
1150 	{ IRE_HOST, "HOST" },
1151 	{ IRE_MULTICAST, "MULTICAST" },
1152 	{ IRE_NOROUTE, "NOROUTE" },
1153 	{ 0 }
1154 };
1155 
1156 nv_t	*ire_nv_tbl = ire_nv_arr;
1157 
1158 /* Simple ICMP IP Header Template */
1159 static ipha_t icmp_ipha = {
1160 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1161 };
1162 
1163 struct module_info ip_mod_info = {
1164 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1165 	IP_MOD_LOWAT
1166 };
1167 
1168 /*
1169  * Duplicate static symbols within a module confuses mdb; so we avoid the
1170  * problem by making the symbols here distinct from those in udp.c.
1171  */
1172 
1173 /*
1174  * Entry points for IP as a device and as a module.
1175  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1176  */
1177 static struct qinit iprinitv4 = {
1178 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1179 	&ip_mod_info
1180 };
1181 
1182 struct qinit iprinitv6 = {
1183 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1184 	&ip_mod_info
1185 };
1186 
1187 static struct qinit ipwinit = {
1188 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1189 	&ip_mod_info
1190 };
1191 
1192 static struct qinit iplrinit = {
1193 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1194 	&ip_mod_info
1195 };
1196 
1197 static struct qinit iplwinit = {
1198 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1199 	&ip_mod_info
1200 };
1201 
1202 /* For AF_INET aka /dev/ip */
1203 struct streamtab ipinfov4 = {
1204 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1205 };
1206 
1207 /* For AF_INET6 aka /dev/ip6 */
1208 struct streamtab ipinfov6 = {
1209 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1210 };
1211 
1212 #ifdef	DEBUG
1213 boolean_t skip_sctp_cksum = B_FALSE;
1214 #endif
1215 
1216 /*
1217  * Generate an ICMP fragmentation needed message.
1218  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1219  * constructed by the caller.
1220  */
1221 void
1222 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1223 {
1224 	icmph_t	icmph;
1225 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1226 
1227 	mp = icmp_pkt_err_ok(mp, ira);
1228 	if (mp == NULL)
1229 		return;
1230 
1231 	bzero(&icmph, sizeof (icmph_t));
1232 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1233 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1234 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1235 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1236 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1237 
1238 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1239 }
1240 
1241 /*
1242  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1243  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1244  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1245  * Likewise, if the ICMP error is misformed (too short, etc), then it
1246  * returns NULL. The caller uses this to determine whether or not to send
1247  * to raw sockets.
1248  *
1249  * All error messages are passed to the matching transport stream.
1250  *
1251  * The following cases are handled by icmp_inbound:
1252  * 1) It needs to send a reply back and possibly delivering it
1253  *    to the "interested" upper clients.
1254  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1255  * 3) It needs to change some values in IP only.
1256  * 4) It needs to change some values in IP and upper layers e.g TCP
1257  *    by delivering an error to the upper layers.
1258  *
1259  * We handle the above three cases in the context of IPsec in the
1260  * following way :
1261  *
1262  * 1) Send the reply back in the same way as the request came in.
1263  *    If it came in encrypted, it goes out encrypted. If it came in
1264  *    clear, it goes out in clear. Thus, this will prevent chosen
1265  *    plain text attack.
1266  * 2) The client may or may not expect things to come in secure.
1267  *    If it comes in secure, the policy constraints are checked
1268  *    before delivering it to the upper layers. If it comes in
1269  *    clear, ipsec_inbound_accept_clear will decide whether to
1270  *    accept this in clear or not. In both the cases, if the returned
1271  *    message (IP header + 8 bytes) that caused the icmp message has
1272  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1273  *    sending up. If there are only 8 bytes of returned message, then
1274  *    upper client will not be notified.
1275  * 3) Check with global policy to see whether it matches the constaints.
1276  *    But this will be done only if icmp_accept_messages_in_clear is
1277  *    zero.
1278  * 4) If we need to change both in IP and ULP, then the decision taken
1279  *    while affecting the values in IP and while delivering up to TCP
1280  *    should be the same.
1281  *
1282  * 	There are two cases.
1283  *
1284  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1285  *	   failed), we will not deliver it to the ULP, even though they
1286  *	   are *willing* to accept in *clear*. This is fine as our global
1287  *	   disposition to icmp messages asks us reject the datagram.
1288  *
1289  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1290  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1291  *	   to deliver it to ULP (policy failed), it can lead to
1292  *	   consistency problems. The cases known at this time are
1293  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1294  *	   values :
1295  *
1296  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1297  *	     and Upper layer rejects. Then the communication will
1298  *	     come to a stop. This is solved by making similar decisions
1299  *	     at both levels. Currently, when we are unable to deliver
1300  *	     to the Upper Layer (due to policy failures) while IP has
1301  *	     adjusted dce_pmtu, the next outbound datagram would
1302  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1303  *	     will be with the right level of protection. Thus the right
1304  *	     value will be communicated even if we are not able to
1305  *	     communicate when we get from the wire initially. But this
1306  *	     assumes there would be at least one outbound datagram after
1307  *	     IP has adjusted its dce_pmtu value. To make things
1308  *	     simpler, we accept in clear after the validation of
1309  *	     AH/ESP headers.
1310  *
1311  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1312  *	     upper layer depending on the level of protection the upper
1313  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1314  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1315  *	     should be accepted in clear when the Upper layer expects secure.
1316  *	     Thus the communication may get aborted by some bad ICMP
1317  *	     packets.
1318  */
1319 mblk_t *
1320 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1321 {
1322 	icmph_t		*icmph;
1323 	ipha_t		*ipha;		/* Outer header */
1324 	int		ip_hdr_length;	/* Outer header length */
1325 	boolean_t	interested;
1326 	ipif_t		*ipif;
1327 	uint32_t	ts;
1328 	uint32_t	*tsp;
1329 	timestruc_t	now;
1330 	ill_t		*ill = ira->ira_ill;
1331 	ip_stack_t	*ipst = ill->ill_ipst;
1332 	zoneid_t	zoneid = ira->ira_zoneid;
1333 	int		len_needed;
1334 	mblk_t		*mp_ret = NULL;
1335 
1336 	ipha = (ipha_t *)mp->b_rptr;
1337 
1338 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1339 
1340 	ip_hdr_length = ira->ira_ip_hdr_length;
1341 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1342 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1343 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1344 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1345 			freemsg(mp);
1346 			return (NULL);
1347 		}
1348 		/* Last chance to get real. */
1349 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1350 		if (ipha == NULL) {
1351 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1352 			freemsg(mp);
1353 			return (NULL);
1354 		}
1355 	}
1356 
1357 	/* The IP header will always be a multiple of four bytes */
1358 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1359 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1360 	    icmph->icmph_code));
1361 
1362 	/*
1363 	 * We will set "interested" to "true" if we should pass a copy to
1364 	 * the transport or if we handle the packet locally.
1365 	 */
1366 	interested = B_FALSE;
1367 	switch (icmph->icmph_type) {
1368 	case ICMP_ECHO_REPLY:
1369 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1370 		break;
1371 	case ICMP_DEST_UNREACHABLE:
1372 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1373 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1374 		interested = B_TRUE;	/* Pass up to transport */
1375 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1376 		break;
1377 	case ICMP_SOURCE_QUENCH:
1378 		interested = B_TRUE;	/* Pass up to transport */
1379 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1380 		break;
1381 	case ICMP_REDIRECT:
1382 		if (!ipst->ips_ip_ignore_redirect)
1383 			interested = B_TRUE;
1384 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1385 		break;
1386 	case ICMP_ECHO_REQUEST:
1387 		/*
1388 		 * Whether to respond to echo requests that come in as IP
1389 		 * broadcasts or as IP multicast is subject to debate
1390 		 * (what isn't?).  We aim to please, you pick it.
1391 		 * Default is do it.
1392 		 */
1393 		if (ira->ira_flags & IRAF_MULTICAST) {
1394 			/* multicast: respond based on tunable */
1395 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1396 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1397 			/* broadcast: respond based on tunable */
1398 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1399 		} else {
1400 			/* unicast: always respond */
1401 			interested = B_TRUE;
1402 		}
1403 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1404 		if (!interested) {
1405 			/* We never pass these to RAW sockets */
1406 			freemsg(mp);
1407 			return (NULL);
1408 		}
1409 
1410 		/* Check db_ref to make sure we can modify the packet. */
1411 		if (mp->b_datap->db_ref > 1) {
1412 			mblk_t	*mp1;
1413 
1414 			mp1 = copymsg(mp);
1415 			freemsg(mp);
1416 			if (!mp1) {
1417 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1418 				return (NULL);
1419 			}
1420 			mp = mp1;
1421 			ipha = (ipha_t *)mp->b_rptr;
1422 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1423 		}
1424 		icmph->icmph_type = ICMP_ECHO_REPLY;
1425 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1426 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1427 		return (NULL);
1428 
1429 	case ICMP_ROUTER_ADVERTISEMENT:
1430 	case ICMP_ROUTER_SOLICITATION:
1431 		break;
1432 	case ICMP_TIME_EXCEEDED:
1433 		interested = B_TRUE;	/* Pass up to transport */
1434 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1435 		break;
1436 	case ICMP_PARAM_PROBLEM:
1437 		interested = B_TRUE;	/* Pass up to transport */
1438 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1439 		break;
1440 	case ICMP_TIME_STAMP_REQUEST:
1441 		/* Response to Time Stamp Requests is local policy. */
1442 		if (ipst->ips_ip_g_resp_to_timestamp) {
1443 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1444 				interested =
1445 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1446 			else
1447 				interested = B_TRUE;
1448 		}
1449 		if (!interested) {
1450 			/* We never pass these to RAW sockets */
1451 			freemsg(mp);
1452 			return (NULL);
1453 		}
1454 
1455 		/* Make sure we have enough of the packet */
1456 		len_needed = ip_hdr_length + ICMPH_SIZE +
1457 		    3 * sizeof (uint32_t);
1458 
1459 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1460 			ipha = ip_pullup(mp, len_needed, ira);
1461 			if (ipha == NULL) {
1462 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1463 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1464 				    mp, ill);
1465 				freemsg(mp);
1466 				return (NULL);
1467 			}
1468 			/* Refresh following the pullup. */
1469 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1470 		}
1471 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1472 		/* Check db_ref to make sure we can modify the packet. */
1473 		if (mp->b_datap->db_ref > 1) {
1474 			mblk_t	*mp1;
1475 
1476 			mp1 = copymsg(mp);
1477 			freemsg(mp);
1478 			if (!mp1) {
1479 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1480 				return (NULL);
1481 			}
1482 			mp = mp1;
1483 			ipha = (ipha_t *)mp->b_rptr;
1484 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1485 		}
1486 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1487 		tsp = (uint32_t *)&icmph[1];
1488 		tsp++;		/* Skip past 'originate time' */
1489 		/* Compute # of milliseconds since midnight */
1490 		gethrestime(&now);
1491 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1492 		    now.tv_nsec / (NANOSEC / MILLISEC);
1493 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1494 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1495 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1496 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1497 		return (NULL);
1498 
1499 	case ICMP_TIME_STAMP_REPLY:
1500 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1501 		break;
1502 	case ICMP_INFO_REQUEST:
1503 		/* Per RFC 1122 3.2.2.7, ignore this. */
1504 	case ICMP_INFO_REPLY:
1505 		break;
1506 	case ICMP_ADDRESS_MASK_REQUEST:
1507 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1508 			interested =
1509 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1510 		} else {
1511 			interested = B_TRUE;
1512 		}
1513 		if (!interested) {
1514 			/* We never pass these to RAW sockets */
1515 			freemsg(mp);
1516 			return (NULL);
1517 		}
1518 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1519 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1520 			ipha = ip_pullup(mp, len_needed, ira);
1521 			if (ipha == NULL) {
1522 				BUMP_MIB(ill->ill_ip_mib,
1523 				    ipIfStatsInTruncatedPkts);
1524 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1525 				    ill);
1526 				freemsg(mp);
1527 				return (NULL);
1528 			}
1529 			/* Refresh following the pullup. */
1530 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1531 		}
1532 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1533 		/* Check db_ref to make sure we can modify the packet. */
1534 		if (mp->b_datap->db_ref > 1) {
1535 			mblk_t	*mp1;
1536 
1537 			mp1 = copymsg(mp);
1538 			freemsg(mp);
1539 			if (!mp1) {
1540 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1541 				return (NULL);
1542 			}
1543 			mp = mp1;
1544 			ipha = (ipha_t *)mp->b_rptr;
1545 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1546 		}
1547 		/*
1548 		 * Need the ipif with the mask be the same as the source
1549 		 * address of the mask reply. For unicast we have a specific
1550 		 * ipif. For multicast/broadcast we only handle onlink
1551 		 * senders, and use the source address to pick an ipif.
1552 		 */
1553 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1554 		if (ipif == NULL) {
1555 			/* Broadcast or multicast */
1556 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1557 			if (ipif == NULL) {
1558 				freemsg(mp);
1559 				return (NULL);
1560 			}
1561 		}
1562 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1563 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1564 		ipif_refrele(ipif);
1565 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1566 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1567 		return (NULL);
1568 
1569 	case ICMP_ADDRESS_MASK_REPLY:
1570 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1571 		break;
1572 	default:
1573 		interested = B_TRUE;	/* Pass up to transport */
1574 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1575 		break;
1576 	}
1577 	/*
1578 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1579 	 * if there isn't one.
1580 	 */
1581 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1582 		/* If there is an ICMP client and we want one too, copy it. */
1583 
1584 		if (!interested) {
1585 			/* Caller will deliver to RAW sockets */
1586 			return (mp);
1587 		}
1588 		mp_ret = copymsg(mp);
1589 		if (mp_ret == NULL) {
1590 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1591 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1592 		}
1593 	} else if (!interested) {
1594 		/* Neither we nor raw sockets are interested. Drop packet now */
1595 		freemsg(mp);
1596 		return (NULL);
1597 	}
1598 
1599 	/*
1600 	 * ICMP error or redirect packet. Make sure we have enough of
1601 	 * the header and that db_ref == 1 since we might end up modifying
1602 	 * the packet.
1603 	 */
1604 	if (mp->b_cont != NULL) {
1605 		if (ip_pullup(mp, -1, ira) == NULL) {
1606 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1607 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1608 			    mp, ill);
1609 			freemsg(mp);
1610 			return (mp_ret);
1611 		}
1612 	}
1613 
1614 	if (mp->b_datap->db_ref > 1) {
1615 		mblk_t	*mp1;
1616 
1617 		mp1 = copymsg(mp);
1618 		if (mp1 == NULL) {
1619 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1620 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1621 			freemsg(mp);
1622 			return (mp_ret);
1623 		}
1624 		freemsg(mp);
1625 		mp = mp1;
1626 	}
1627 
1628 	/*
1629 	 * In case mp has changed, verify the message before any further
1630 	 * processes.
1631 	 */
1632 	ipha = (ipha_t *)mp->b_rptr;
1633 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1634 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1635 		freemsg(mp);
1636 		return (mp_ret);
1637 	}
1638 
1639 	switch (icmph->icmph_type) {
1640 	case ICMP_REDIRECT:
1641 		icmp_redirect_v4(mp, ipha, icmph, ira);
1642 		break;
1643 	case ICMP_DEST_UNREACHABLE:
1644 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1645 			/* Update DCE and adjust MTU is icmp header if needed */
1646 			icmp_inbound_too_big_v4(icmph, ira);
1647 		}
1648 		/* FALLTHRU */
1649 	default:
1650 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1651 		break;
1652 	}
1653 	return (mp_ret);
1654 }
1655 
1656 /*
1657  * Send an ICMP echo, timestamp or address mask reply.
1658  * The caller has already updated the payload part of the packet.
1659  * We handle the ICMP checksum, IP source address selection and feed
1660  * the packet into ip_output_simple.
1661  */
1662 static void
1663 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1664     ip_recv_attr_t *ira)
1665 {
1666 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1667 	ill_t		*ill = ira->ira_ill;
1668 	ip_stack_t	*ipst = ill->ill_ipst;
1669 	ip_xmit_attr_t	ixas;
1670 
1671 	/* Send out an ICMP packet */
1672 	icmph->icmph_checksum = 0;
1673 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1674 	/* Reset time to live. */
1675 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1676 	{
1677 		/* Swap source and destination addresses */
1678 		ipaddr_t tmp;
1679 
1680 		tmp = ipha->ipha_src;
1681 		ipha->ipha_src = ipha->ipha_dst;
1682 		ipha->ipha_dst = tmp;
1683 	}
1684 	ipha->ipha_ident = 0;
1685 	if (!IS_SIMPLE_IPH(ipha))
1686 		icmp_options_update(ipha);
1687 
1688 	bzero(&ixas, sizeof (ixas));
1689 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1690 	ixas.ixa_zoneid = ira->ira_zoneid;
1691 	ixas.ixa_cred = kcred;
1692 	ixas.ixa_cpid = NOPID;
1693 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1694 	ixas.ixa_ifindex = 0;
1695 	ixas.ixa_ipst = ipst;
1696 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1697 
1698 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1699 		/*
1700 		 * This packet should go out the same way as it
1701 		 * came in i.e in clear, independent of the IPsec policy
1702 		 * for transmitting packets.
1703 		 */
1704 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1705 	} else {
1706 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1707 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1708 			/* Note: mp already consumed and ip_drop_packet done */
1709 			return;
1710 		}
1711 	}
1712 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1713 		/*
1714 		 * Not one or our addresses (IRE_LOCALs), thus we let
1715 		 * ip_output_simple pick the source.
1716 		 */
1717 		ipha->ipha_src = INADDR_ANY;
1718 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1719 	}
1720 	/* Should we send with DF and use dce_pmtu? */
1721 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1722 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1723 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1724 	}
1725 
1726 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1727 
1728 	(void) ip_output_simple(mp, &ixas);
1729 	ixa_cleanup(&ixas);
1730 }
1731 
1732 /*
1733  * Verify the ICMP messages for either for ICMP error or redirect packet.
1734  * The caller should have fully pulled up the message. If it's a redirect
1735  * packet, only basic checks on IP header will be done; otherwise, verify
1736  * the packet by looking at the included ULP header.
1737  *
1738  * Called before icmp_inbound_error_fanout_v4 is called.
1739  */
1740 static boolean_t
1741 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1742 {
1743 	ill_t		*ill = ira->ira_ill;
1744 	int		hdr_length;
1745 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1746 	conn_t		*connp;
1747 	ipha_t		*ipha;	/* Inner IP header */
1748 
1749 	ipha = (ipha_t *)&icmph[1];
1750 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1751 		goto truncated;
1752 
1753 	hdr_length = IPH_HDR_LENGTH(ipha);
1754 
1755 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1756 		goto discard_pkt;
1757 
1758 	if (hdr_length < sizeof (ipha_t))
1759 		goto truncated;
1760 
1761 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1762 		goto truncated;
1763 
1764 	/*
1765 	 * Stop here for ICMP_REDIRECT.
1766 	 */
1767 	if (icmph->icmph_type == ICMP_REDIRECT)
1768 		return (B_TRUE);
1769 
1770 	/*
1771 	 * ICMP errors only.
1772 	 */
1773 	switch (ipha->ipha_protocol) {
1774 	case IPPROTO_UDP:
1775 		/*
1776 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1777 		 * transport header.
1778 		 */
1779 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1780 		    mp->b_wptr)
1781 			goto truncated;
1782 		break;
1783 	case IPPROTO_TCP: {
1784 		tcpha_t		*tcpha;
1785 
1786 		/*
1787 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1788 		 * transport header.
1789 		 */
1790 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1791 		    mp->b_wptr)
1792 			goto truncated;
1793 
1794 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1795 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1796 		    ipst);
1797 		if (connp == NULL)
1798 			goto discard_pkt;
1799 
1800 		if ((connp->conn_verifyicmp != NULL) &&
1801 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1802 			CONN_DEC_REF(connp);
1803 			goto discard_pkt;
1804 		}
1805 		CONN_DEC_REF(connp);
1806 		break;
1807 	}
1808 	case IPPROTO_SCTP:
1809 		/*
1810 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1811 		 * transport header.
1812 		 */
1813 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1814 		    mp->b_wptr)
1815 			goto truncated;
1816 		break;
1817 	case IPPROTO_ESP:
1818 	case IPPROTO_AH:
1819 		break;
1820 	case IPPROTO_ENCAP:
1821 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1822 		    mp->b_wptr)
1823 			goto truncated;
1824 		break;
1825 	default:
1826 		break;
1827 	}
1828 
1829 	return (B_TRUE);
1830 
1831 discard_pkt:
1832 	/* Bogus ICMP error. */
1833 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1834 	return (B_FALSE);
1835 
1836 truncated:
1837 	/* We pulled up everthing already. Must be truncated */
1838 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1839 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1840 	return (B_FALSE);
1841 }
1842 
1843 /* Table from RFC 1191 */
1844 static int icmp_frag_size_table[] =
1845 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1846 
1847 /*
1848  * Process received ICMP Packet too big.
1849  * Just handles the DCE create/update, including using the above table of
1850  * PMTU guesses. The caller is responsible for validating the packet before
1851  * passing it in and also to fanout the ICMP error to any matching transport
1852  * conns. Assumes the message has been fully pulled up and verified.
1853  *
1854  * Before getting here, the caller has called icmp_inbound_verify_v4()
1855  * that should have verified with ULP to prevent undoing the changes we're
1856  * going to make to DCE. For example, TCP might have verified that the packet
1857  * which generated error is in the send window.
1858  *
1859  * In some cases modified this MTU in the ICMP header packet; the caller
1860  * should pass to the matching ULP after this returns.
1861  */
1862 static void
1863 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1864 {
1865 	dce_t		*dce;
1866 	int		old_mtu;
1867 	int		mtu, orig_mtu;
1868 	ipaddr_t	dst;
1869 	boolean_t	disable_pmtud;
1870 	ill_t		*ill = ira->ira_ill;
1871 	ip_stack_t	*ipst = ill->ill_ipst;
1872 	uint_t		hdr_length;
1873 	ipha_t		*ipha;
1874 
1875 	/* Caller already pulled up everything. */
1876 	ipha = (ipha_t *)&icmph[1];
1877 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1878 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1879 	ASSERT(ill != NULL);
1880 
1881 	hdr_length = IPH_HDR_LENGTH(ipha);
1882 
1883 	/*
1884 	 * We handle path MTU for source routed packets since the DCE
1885 	 * is looked up using the final destination.
1886 	 */
1887 	dst = ip_get_dst(ipha);
1888 
1889 	dce = dce_lookup_and_add_v4(dst, ipst);
1890 	if (dce == NULL) {
1891 		/* Couldn't add a unique one - ENOMEM */
1892 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1893 		    ntohl(dst)));
1894 		return;
1895 	}
1896 
1897 	/* Check for MTU discovery advice as described in RFC 1191 */
1898 	mtu = ntohs(icmph->icmph_du_mtu);
1899 	orig_mtu = mtu;
1900 	disable_pmtud = B_FALSE;
1901 
1902 	mutex_enter(&dce->dce_lock);
1903 	if (dce->dce_flags & DCEF_PMTU)
1904 		old_mtu = dce->dce_pmtu;
1905 	else
1906 		old_mtu = ill->ill_mtu;
1907 
1908 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1909 		uint32_t length;
1910 		int	i;
1911 
1912 		/*
1913 		 * Use the table from RFC 1191 to figure out
1914 		 * the next "plateau" based on the length in
1915 		 * the original IP packet.
1916 		 */
1917 		length = ntohs(ipha->ipha_length);
1918 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1919 		    uint32_t, length);
1920 		if (old_mtu <= length &&
1921 		    old_mtu >= length - hdr_length) {
1922 			/*
1923 			 * Handle broken BSD 4.2 systems that
1924 			 * return the wrong ipha_length in ICMP
1925 			 * errors.
1926 			 */
1927 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1928 			    length, old_mtu));
1929 			length -= hdr_length;
1930 		}
1931 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1932 			if (length > icmp_frag_size_table[i])
1933 				break;
1934 		}
1935 		if (i == A_CNT(icmp_frag_size_table)) {
1936 			/* Smaller than IP_MIN_MTU! */
1937 			ip1dbg(("Too big for packet size %d\n",
1938 			    length));
1939 			disable_pmtud = B_TRUE;
1940 			mtu = ipst->ips_ip_pmtu_min;
1941 		} else {
1942 			mtu = icmp_frag_size_table[i];
1943 			ip1dbg(("Calculated mtu %d, packet size %d, "
1944 			    "before %d\n", mtu, length, old_mtu));
1945 			if (mtu < ipst->ips_ip_pmtu_min) {
1946 				mtu = ipst->ips_ip_pmtu_min;
1947 				disable_pmtud = B_TRUE;
1948 			}
1949 		}
1950 	}
1951 	if (disable_pmtud)
1952 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1953 	else
1954 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1955 
1956 	dce->dce_pmtu = MIN(old_mtu, mtu);
1957 	/* Prepare to send the new max frag size for the ULP. */
1958 	icmph->icmph_du_zero = 0;
1959 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1960 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1961 	    dce, int, orig_mtu, int, mtu);
1962 
1963 	/* We now have a PMTU for sure */
1964 	dce->dce_flags |= DCEF_PMTU;
1965 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1966 	mutex_exit(&dce->dce_lock);
1967 	/*
1968 	 * After dropping the lock the new value is visible to everyone.
1969 	 * Then we bump the generation number so any cached values reinspect
1970 	 * the dce_t.
1971 	 */
1972 	dce_increment_generation(dce);
1973 	dce_refrele(dce);
1974 }
1975 
1976 /*
1977  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1978  * calls this function.
1979  */
1980 static mblk_t *
1981 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1982 {
1983 	int length;
1984 
1985 	ASSERT(mp->b_datap->db_type == M_DATA);
1986 
1987 	/* icmp_inbound_v4 has already pulled up the whole error packet */
1988 	ASSERT(mp->b_cont == NULL);
1989 
1990 	/*
1991 	 * The length that we want to overlay is the inner header
1992 	 * and what follows it.
1993 	 */
1994 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
1995 
1996 	/*
1997 	 * Overlay the inner header and whatever follows it over the
1998 	 * outer header.
1999 	 */
2000 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2001 
2002 	/* Adjust for what we removed */
2003 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2004 	return (mp);
2005 }
2006 
2007 /*
2008  * Try to pass the ICMP message upstream in case the ULP cares.
2009  *
2010  * If the packet that caused the ICMP error is secure, we send
2011  * it to AH/ESP to make sure that the attached packet has a
2012  * valid association. ipha in the code below points to the
2013  * IP header of the packet that caused the error.
2014  *
2015  * For IPsec cases, we let the next-layer-up (which has access to
2016  * cached policy on the conn_t, or can query the SPD directly)
2017  * subtract out any IPsec overhead if they must.  We therefore make no
2018  * adjustments here for IPsec overhead.
2019  *
2020  * IFN could have been generated locally or by some router.
2021  *
2022  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2023  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2024  *	    This happens because IP adjusted its value of MTU on an
2025  *	    earlier IFN message and could not tell the upper layer,
2026  *	    the new adjusted value of MTU e.g. Packet was encrypted
2027  *	    or there was not enough information to fanout to upper
2028  *	    layers. Thus on the next outbound datagram, ire_send_wire
2029  *	    generates the IFN, where IPsec processing has *not* been
2030  *	    done.
2031  *
2032  *	    Note that we retain ixa_fragsize across IPsec thus once
2033  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2034  *	    no change the fragsize even if the path MTU changes before
2035  *	    we reach ip_output_post_ipsec.
2036  *
2037  *	    In the local case, IRAF_LOOPBACK will be set indicating
2038  *	    that IFN was generated locally.
2039  *
2040  * ROUTER : IFN could be secure or non-secure.
2041  *
2042  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2043  *	      packet in error has AH/ESP headers to validate the AH/ESP
2044  *	      headers. AH/ESP will verify whether there is a valid SA or
2045  *	      not and send it back. We will fanout again if we have more
2046  *	      data in the packet.
2047  *
2048  *	      If the packet in error does not have AH/ESP, we handle it
2049  *	      like any other case.
2050  *
2051  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2052  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2053  *	      valid SA or not and send it back. We will fanout again if
2054  *	      we have more data in the packet.
2055  *
2056  *	      If the packet in error does not have AH/ESP, we handle it
2057  *	      like any other case.
2058  *
2059  * The caller must have called icmp_inbound_verify_v4.
2060  */
2061 static void
2062 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2063 {
2064 	uint16_t	*up;	/* Pointer to ports in ULP header */
2065 	uint32_t	ports;	/* reversed ports for fanout */
2066 	ipha_t		ripha;	/* With reversed addresses */
2067 	ipha_t		*ipha;  /* Inner IP header */
2068 	uint_t		hdr_length; /* Inner IP header length */
2069 	tcpha_t		*tcpha;
2070 	conn_t		*connp;
2071 	ill_t		*ill = ira->ira_ill;
2072 	ip_stack_t	*ipst = ill->ill_ipst;
2073 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2074 	ill_t		*rill = ira->ira_rill;
2075 
2076 	/* Caller already pulled up everything. */
2077 	ipha = (ipha_t *)&icmph[1];
2078 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2079 	ASSERT(mp->b_cont == NULL);
2080 
2081 	hdr_length = IPH_HDR_LENGTH(ipha);
2082 	ira->ira_protocol = ipha->ipha_protocol;
2083 
2084 	/*
2085 	 * We need a separate IP header with the source and destination
2086 	 * addresses reversed to do fanout/classification because the ipha in
2087 	 * the ICMP error is in the form we sent it out.
2088 	 */
2089 	ripha.ipha_src = ipha->ipha_dst;
2090 	ripha.ipha_dst = ipha->ipha_src;
2091 	ripha.ipha_protocol = ipha->ipha_protocol;
2092 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2093 
2094 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2095 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2096 	    ntohl(ipha->ipha_dst),
2097 	    icmph->icmph_type, icmph->icmph_code));
2098 
2099 	switch (ipha->ipha_protocol) {
2100 	case IPPROTO_UDP:
2101 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2102 
2103 		/* Attempt to find a client stream based on port. */
2104 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2105 		    ntohs(up[0]), ntohs(up[1])));
2106 
2107 		/* Note that we send error to all matches. */
2108 		ira->ira_flags |= IRAF_ICMP_ERROR;
2109 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2110 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2111 		return;
2112 
2113 	case IPPROTO_TCP:
2114 		/*
2115 		 * Find a TCP client stream for this packet.
2116 		 * Note that we do a reverse lookup since the header is
2117 		 * in the form we sent it out.
2118 		 */
2119 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2120 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2121 		    ipst);
2122 		if (connp == NULL)
2123 			goto discard_pkt;
2124 
2125 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2126 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2127 			mp = ipsec_check_inbound_policy(mp, connp,
2128 			    ipha, NULL, ira);
2129 			if (mp == NULL) {
2130 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2131 				/* Note that mp is NULL */
2132 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2133 				CONN_DEC_REF(connp);
2134 				return;
2135 			}
2136 		}
2137 
2138 		ira->ira_flags |= IRAF_ICMP_ERROR;
2139 		ira->ira_ill = ira->ira_rill = NULL;
2140 		if (IPCL_IS_TCP(connp)) {
2141 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2142 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2143 			    SQTAG_TCP_INPUT_ICMP_ERR);
2144 		} else {
2145 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2146 			(connp->conn_recv)(connp, mp, NULL, ira);
2147 			CONN_DEC_REF(connp);
2148 		}
2149 		ira->ira_ill = ill;
2150 		ira->ira_rill = rill;
2151 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2152 		return;
2153 
2154 	case IPPROTO_SCTP:
2155 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2156 		/* Find a SCTP client stream for this packet. */
2157 		((uint16_t *)&ports)[0] = up[1];
2158 		((uint16_t *)&ports)[1] = up[0];
2159 
2160 		ira->ira_flags |= IRAF_ICMP_ERROR;
2161 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2162 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2163 		return;
2164 
2165 	case IPPROTO_ESP:
2166 	case IPPROTO_AH:
2167 		if (!ipsec_loaded(ipss)) {
2168 			ip_proto_not_sup(mp, ira);
2169 			return;
2170 		}
2171 
2172 		if (ipha->ipha_protocol == IPPROTO_ESP)
2173 			mp = ipsecesp_icmp_error(mp, ira);
2174 		else
2175 			mp = ipsecah_icmp_error(mp, ira);
2176 		if (mp == NULL)
2177 			return;
2178 
2179 		/* Just in case ipsec didn't preserve the NULL b_cont */
2180 		if (mp->b_cont != NULL) {
2181 			if (!pullupmsg(mp, -1))
2182 				goto discard_pkt;
2183 		}
2184 
2185 		/*
2186 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2187 		 * correct, but we don't use them any more here.
2188 		 *
2189 		 * If succesful, the mp has been modified to not include
2190 		 * the ESP/AH header so we can fanout to the ULP's icmp
2191 		 * error handler.
2192 		 */
2193 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2194 			goto truncated;
2195 
2196 		/* Verify the modified message before any further processes. */
2197 		ipha = (ipha_t *)mp->b_rptr;
2198 		hdr_length = IPH_HDR_LENGTH(ipha);
2199 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2200 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2201 			freemsg(mp);
2202 			return;
2203 		}
2204 
2205 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2206 		return;
2207 
2208 	case IPPROTO_ENCAP: {
2209 		/* Look for self-encapsulated packets that caused an error */
2210 		ipha_t *in_ipha;
2211 
2212 		/*
2213 		 * Caller has verified that length has to be
2214 		 * at least the size of IP header.
2215 		 */
2216 		ASSERT(hdr_length >= sizeof (ipha_t));
2217 		/*
2218 		 * Check the sanity of the inner IP header like
2219 		 * we did for the outer header.
2220 		 */
2221 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2222 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2223 			goto discard_pkt;
2224 		}
2225 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2226 			goto discard_pkt;
2227 		}
2228 		/* Check for Self-encapsulated tunnels */
2229 		if (in_ipha->ipha_src == ipha->ipha_src &&
2230 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2231 
2232 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2233 			    in_ipha);
2234 			if (mp == NULL)
2235 				goto discard_pkt;
2236 
2237 			/*
2238 			 * Just in case self_encap didn't preserve the NULL
2239 			 * b_cont
2240 			 */
2241 			if (mp->b_cont != NULL) {
2242 				if (!pullupmsg(mp, -1))
2243 					goto discard_pkt;
2244 			}
2245 			/*
2246 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2247 			 * longer correct, but we don't use them any more here.
2248 			 */
2249 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2250 				goto truncated;
2251 
2252 			/*
2253 			 * Verify the modified message before any further
2254 			 * processes.
2255 			 */
2256 			ipha = (ipha_t *)mp->b_rptr;
2257 			hdr_length = IPH_HDR_LENGTH(ipha);
2258 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2259 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2260 				freemsg(mp);
2261 				return;
2262 			}
2263 
2264 			/*
2265 			 * The packet in error is self-encapsualted.
2266 			 * And we are finding it further encapsulated
2267 			 * which we could not have possibly generated.
2268 			 */
2269 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2270 				goto discard_pkt;
2271 			}
2272 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2273 			return;
2274 		}
2275 		/* No self-encapsulated */
2276 		/* FALLTHRU */
2277 	}
2278 	case IPPROTO_IPV6:
2279 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2280 		    &ripha.ipha_dst, ipst)) != NULL) {
2281 			ira->ira_flags |= IRAF_ICMP_ERROR;
2282 			connp->conn_recvicmp(connp, mp, NULL, ira);
2283 			CONN_DEC_REF(connp);
2284 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2285 			return;
2286 		}
2287 		/*
2288 		 * No IP tunnel is interested, fallthrough and see
2289 		 * if a raw socket will want it.
2290 		 */
2291 		/* FALLTHRU */
2292 	default:
2293 		ira->ira_flags |= IRAF_ICMP_ERROR;
2294 		ip_fanout_proto_v4(mp, &ripha, ira);
2295 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2296 		return;
2297 	}
2298 	/* NOTREACHED */
2299 discard_pkt:
2300 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2301 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2302 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2303 	freemsg(mp);
2304 	return;
2305 
2306 truncated:
2307 	/* We pulled up everthing already. Must be truncated */
2308 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2309 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2310 	freemsg(mp);
2311 }
2312 
2313 /*
2314  * Common IP options parser.
2315  *
2316  * Setup routine: fill in *optp with options-parsing state, then
2317  * tail-call ipoptp_next to return the first option.
2318  */
2319 uint8_t
2320 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2321 {
2322 	uint32_t totallen; /* total length of all options */
2323 
2324 	totallen = ipha->ipha_version_and_hdr_length -
2325 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2326 	totallen <<= 2;
2327 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2328 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2329 	optp->ipoptp_flags = 0;
2330 	return (ipoptp_next(optp));
2331 }
2332 
2333 /* Like above but without an ipha_t */
2334 uint8_t
2335 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2336 {
2337 	optp->ipoptp_next = opt;
2338 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2339 	optp->ipoptp_flags = 0;
2340 	return (ipoptp_next(optp));
2341 }
2342 
2343 /*
2344  * Common IP options parser: extract next option.
2345  */
2346 uint8_t
2347 ipoptp_next(ipoptp_t *optp)
2348 {
2349 	uint8_t *end = optp->ipoptp_end;
2350 	uint8_t *cur = optp->ipoptp_next;
2351 	uint8_t opt, len, pointer;
2352 
2353 	/*
2354 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2355 	 * has been corrupted.
2356 	 */
2357 	ASSERT(cur <= end);
2358 
2359 	if (cur == end)
2360 		return (IPOPT_EOL);
2361 
2362 	opt = cur[IPOPT_OPTVAL];
2363 
2364 	/*
2365 	 * Skip any NOP options.
2366 	 */
2367 	while (opt == IPOPT_NOP) {
2368 		cur++;
2369 		if (cur == end)
2370 			return (IPOPT_EOL);
2371 		opt = cur[IPOPT_OPTVAL];
2372 	}
2373 
2374 	if (opt == IPOPT_EOL)
2375 		return (IPOPT_EOL);
2376 
2377 	/*
2378 	 * Option requiring a length.
2379 	 */
2380 	if ((cur + 1) >= end) {
2381 		optp->ipoptp_flags |= IPOPTP_ERROR;
2382 		return (IPOPT_EOL);
2383 	}
2384 	len = cur[IPOPT_OLEN];
2385 	if (len < 2) {
2386 		optp->ipoptp_flags |= IPOPTP_ERROR;
2387 		return (IPOPT_EOL);
2388 	}
2389 	optp->ipoptp_cur = cur;
2390 	optp->ipoptp_len = len;
2391 	optp->ipoptp_next = cur + len;
2392 	if (cur + len > end) {
2393 		optp->ipoptp_flags |= IPOPTP_ERROR;
2394 		return (IPOPT_EOL);
2395 	}
2396 
2397 	/*
2398 	 * For the options which require a pointer field, make sure
2399 	 * its there, and make sure it points to either something
2400 	 * inside this option, or the end of the option.
2401 	 */
2402 	switch (opt) {
2403 	case IPOPT_RR:
2404 	case IPOPT_TS:
2405 	case IPOPT_LSRR:
2406 	case IPOPT_SSRR:
2407 		if (len <= IPOPT_OFFSET) {
2408 			optp->ipoptp_flags |= IPOPTP_ERROR;
2409 			return (opt);
2410 		}
2411 		pointer = cur[IPOPT_OFFSET];
2412 		if (pointer - 1 > len) {
2413 			optp->ipoptp_flags |= IPOPTP_ERROR;
2414 			return (opt);
2415 		}
2416 		break;
2417 	}
2418 
2419 	/*
2420 	 * Sanity check the pointer field based on the type of the
2421 	 * option.
2422 	 */
2423 	switch (opt) {
2424 	case IPOPT_RR:
2425 	case IPOPT_SSRR:
2426 	case IPOPT_LSRR:
2427 		if (pointer < IPOPT_MINOFF_SR)
2428 			optp->ipoptp_flags |= IPOPTP_ERROR;
2429 		break;
2430 	case IPOPT_TS:
2431 		if (pointer < IPOPT_MINOFF_IT)
2432 			optp->ipoptp_flags |= IPOPTP_ERROR;
2433 		/*
2434 		 * Note that the Internet Timestamp option also
2435 		 * contains two four bit fields (the Overflow field,
2436 		 * and the Flag field), which follow the pointer
2437 		 * field.  We don't need to check that these fields
2438 		 * fall within the length of the option because this
2439 		 * was implicitely done above.  We've checked that the
2440 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2441 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2442 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2443 		 */
2444 		ASSERT(len > IPOPT_POS_OV_FLG);
2445 		break;
2446 	}
2447 
2448 	return (opt);
2449 }
2450 
2451 /*
2452  * Use the outgoing IP header to create an IP_OPTIONS option the way
2453  * it was passed down from the application.
2454  *
2455  * This is compatible with BSD in that it returns
2456  * the reverse source route with the final destination
2457  * as the last entry. The first 4 bytes of the option
2458  * will contain the final destination.
2459  */
2460 int
2461 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2462 {
2463 	ipoptp_t	opts;
2464 	uchar_t		*opt;
2465 	uint8_t		optval;
2466 	uint8_t		optlen;
2467 	uint32_t	len = 0;
2468 	uchar_t		*buf1 = buf;
2469 	uint32_t	totallen;
2470 	ipaddr_t	dst;
2471 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2472 
2473 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2474 		return (0);
2475 
2476 	totallen = ipp->ipp_ipv4_options_len;
2477 	if (totallen & 0x3)
2478 		return (0);
2479 
2480 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2481 	len += IP_ADDR_LEN;
2482 	bzero(buf1, IP_ADDR_LEN);
2483 
2484 	dst = connp->conn_faddr_v4;
2485 
2486 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2487 	    optval != IPOPT_EOL;
2488 	    optval = ipoptp_next(&opts)) {
2489 		int	off;
2490 
2491 		opt = opts.ipoptp_cur;
2492 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2493 			break;
2494 		}
2495 		optlen = opts.ipoptp_len;
2496 
2497 		switch (optval) {
2498 		case IPOPT_SSRR:
2499 		case IPOPT_LSRR:
2500 
2501 			/*
2502 			 * Insert destination as the first entry in the source
2503 			 * route and move down the entries on step.
2504 			 * The last entry gets placed at buf1.
2505 			 */
2506 			buf[IPOPT_OPTVAL] = optval;
2507 			buf[IPOPT_OLEN] = optlen;
2508 			buf[IPOPT_OFFSET] = optlen;
2509 
2510 			off = optlen - IP_ADDR_LEN;
2511 			if (off < 0) {
2512 				/* No entries in source route */
2513 				break;
2514 			}
2515 			/* Last entry in source route if not already set */
2516 			if (dst == INADDR_ANY)
2517 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2518 			off -= IP_ADDR_LEN;
2519 
2520 			while (off > 0) {
2521 				bcopy(opt + off,
2522 				    buf + off + IP_ADDR_LEN,
2523 				    IP_ADDR_LEN);
2524 				off -= IP_ADDR_LEN;
2525 			}
2526 			/* ipha_dst into first slot */
2527 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2528 			    IP_ADDR_LEN);
2529 			buf += optlen;
2530 			len += optlen;
2531 			break;
2532 
2533 		default:
2534 			bcopy(opt, buf, optlen);
2535 			buf += optlen;
2536 			len += optlen;
2537 			break;
2538 		}
2539 	}
2540 done:
2541 	/* Pad the resulting options */
2542 	while (len & 0x3) {
2543 		*buf++ = IPOPT_EOL;
2544 		len++;
2545 	}
2546 	return (len);
2547 }
2548 
2549 /*
2550  * Update any record route or timestamp options to include this host.
2551  * Reverse any source route option.
2552  * This routine assumes that the options are well formed i.e. that they
2553  * have already been checked.
2554  */
2555 static void
2556 icmp_options_update(ipha_t *ipha)
2557 {
2558 	ipoptp_t	opts;
2559 	uchar_t		*opt;
2560 	uint8_t		optval;
2561 	ipaddr_t	src;		/* Our local address */
2562 	ipaddr_t	dst;
2563 
2564 	ip2dbg(("icmp_options_update\n"));
2565 	src = ipha->ipha_src;
2566 	dst = ipha->ipha_dst;
2567 
2568 	for (optval = ipoptp_first(&opts, ipha);
2569 	    optval != IPOPT_EOL;
2570 	    optval = ipoptp_next(&opts)) {
2571 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2572 		opt = opts.ipoptp_cur;
2573 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2574 		    optval, opts.ipoptp_len));
2575 		switch (optval) {
2576 			int off1, off2;
2577 		case IPOPT_SSRR:
2578 		case IPOPT_LSRR:
2579 			/*
2580 			 * Reverse the source route.  The first entry
2581 			 * should be the next to last one in the current
2582 			 * source route (the last entry is our address).
2583 			 * The last entry should be the final destination.
2584 			 */
2585 			off1 = IPOPT_MINOFF_SR - 1;
2586 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2587 			if (off2 < 0) {
2588 				/* No entries in source route */
2589 				ip1dbg((
2590 				    "icmp_options_update: bad src route\n"));
2591 				break;
2592 			}
2593 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2594 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2595 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2596 			off2 -= IP_ADDR_LEN;
2597 
2598 			while (off1 < off2) {
2599 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2600 				bcopy((char *)opt + off2, (char *)opt + off1,
2601 				    IP_ADDR_LEN);
2602 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2603 				off1 += IP_ADDR_LEN;
2604 				off2 -= IP_ADDR_LEN;
2605 			}
2606 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2607 			break;
2608 		}
2609 	}
2610 }
2611 
2612 /*
2613  * Process received ICMP Redirect messages.
2614  * Assumes the caller has verified that the headers are in the pulled up mblk.
2615  * Consumes mp.
2616  */
2617 static void
2618 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2619 {
2620 	ire_t		*ire, *nire;
2621 	ire_t		*prev_ire;
2622 	ipaddr_t  	src, dst, gateway;
2623 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2624 	ipha_t		*inner_ipha;	/* Inner IP header */
2625 
2626 	/* Caller already pulled up everything. */
2627 	inner_ipha = (ipha_t *)&icmph[1];
2628 	src = ipha->ipha_src;
2629 	dst = inner_ipha->ipha_dst;
2630 	gateway = icmph->icmph_rd_gateway;
2631 	/* Make sure the new gateway is reachable somehow. */
2632 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2633 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2634 	/*
2635 	 * Make sure we had a route for the dest in question and that
2636 	 * that route was pointing to the old gateway (the source of the
2637 	 * redirect packet.)
2638 	 * We do longest match and then compare ire_gateway_addr below.
2639 	 */
2640 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2641 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2642 	/*
2643 	 * Check that
2644 	 *	the redirect was not from ourselves
2645 	 *	the new gateway and the old gateway are directly reachable
2646 	 */
2647 	if (prev_ire == NULL || ire == NULL ||
2648 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2649 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2650 	    !(ire->ire_type & IRE_IF_ALL) ||
2651 	    prev_ire->ire_gateway_addr != src) {
2652 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2653 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2654 		freemsg(mp);
2655 		if (ire != NULL)
2656 			ire_refrele(ire);
2657 		if (prev_ire != NULL)
2658 			ire_refrele(prev_ire);
2659 		return;
2660 	}
2661 
2662 	ire_refrele(prev_ire);
2663 	ire_refrele(ire);
2664 
2665 	/*
2666 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2667 	 * require TOS routing
2668 	 */
2669 	switch (icmph->icmph_code) {
2670 	case 0:
2671 	case 1:
2672 		/* TODO: TOS specificity for cases 2 and 3 */
2673 	case 2:
2674 	case 3:
2675 		break;
2676 	default:
2677 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2678 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2679 		freemsg(mp);
2680 		return;
2681 	}
2682 	/*
2683 	 * Create a Route Association.  This will allow us to remember that
2684 	 * someone we believe told us to use the particular gateway.
2685 	 */
2686 	ire = ire_create(
2687 	    (uchar_t *)&dst,			/* dest addr */
2688 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2689 	    (uchar_t *)&gateway,		/* gateway addr */
2690 	    IRE_HOST,
2691 	    NULL,				/* ill */
2692 	    ALL_ZONES,
2693 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2694 	    NULL,				/* tsol_gc_t */
2695 	    ipst);
2696 
2697 	if (ire == NULL) {
2698 		freemsg(mp);
2699 		return;
2700 	}
2701 	nire = ire_add(ire);
2702 	/* Check if it was a duplicate entry */
2703 	if (nire != NULL && nire != ire) {
2704 		ASSERT(nire->ire_identical_ref > 1);
2705 		ire_delete(nire);
2706 		ire_refrele(nire);
2707 		nire = NULL;
2708 	}
2709 	ire = nire;
2710 	if (ire != NULL) {
2711 		ire_refrele(ire);		/* Held in ire_add */
2712 
2713 		/* tell routing sockets that we received a redirect */
2714 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2715 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2716 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2717 	}
2718 
2719 	/*
2720 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2721 	 * This together with the added IRE has the effect of
2722 	 * modifying an existing redirect.
2723 	 */
2724 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2725 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2726 	if (prev_ire != NULL) {
2727 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2728 			ire_delete(prev_ire);
2729 		ire_refrele(prev_ire);
2730 	}
2731 
2732 	freemsg(mp);
2733 }
2734 
2735 /*
2736  * Generate an ICMP parameter problem message.
2737  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2738  * constructed by the caller.
2739  */
2740 static void
2741 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2742 {
2743 	icmph_t	icmph;
2744 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2745 
2746 	mp = icmp_pkt_err_ok(mp, ira);
2747 	if (mp == NULL)
2748 		return;
2749 
2750 	bzero(&icmph, sizeof (icmph_t));
2751 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2752 	icmph.icmph_pp_ptr = ptr;
2753 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2754 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2755 }
2756 
2757 /*
2758  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2759  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2760  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2761  * an icmp error packet can be sent.
2762  * Assigns an appropriate source address to the packet. If ipha_dst is
2763  * one of our addresses use it for source. Otherwise let ip_output_simple
2764  * pick the source address.
2765  */
2766 static void
2767 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2768 {
2769 	ipaddr_t dst;
2770 	icmph_t	*icmph;
2771 	ipha_t	*ipha;
2772 	uint_t	len_needed;
2773 	size_t	msg_len;
2774 	mblk_t	*mp1;
2775 	ipaddr_t src;
2776 	ire_t	*ire;
2777 	ip_xmit_attr_t ixas;
2778 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2779 
2780 	ipha = (ipha_t *)mp->b_rptr;
2781 
2782 	bzero(&ixas, sizeof (ixas));
2783 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2784 	ixas.ixa_zoneid = ira->ira_zoneid;
2785 	ixas.ixa_ifindex = 0;
2786 	ixas.ixa_ipst = ipst;
2787 	ixas.ixa_cred = kcred;
2788 	ixas.ixa_cpid = NOPID;
2789 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2790 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2791 
2792 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2793 		/*
2794 		 * Apply IPsec based on how IPsec was applied to
2795 		 * the packet that had the error.
2796 		 *
2797 		 * If it was an outbound packet that caused the ICMP
2798 		 * error, then the caller will have setup the IRA
2799 		 * appropriately.
2800 		 */
2801 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2802 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2803 			/* Note: mp already consumed and ip_drop_packet done */
2804 			return;
2805 		}
2806 	} else {
2807 		/*
2808 		 * This is in clear. The icmp message we are building
2809 		 * here should go out in clear, independent of our policy.
2810 		 */
2811 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2812 	}
2813 
2814 	/* Remember our eventual destination */
2815 	dst = ipha->ipha_src;
2816 
2817 	/*
2818 	 * If the packet was for one of our unicast addresses, make
2819 	 * sure we respond with that as the source. Otherwise
2820 	 * have ip_output_simple pick the source address.
2821 	 */
2822 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2823 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2824 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2825 	if (ire != NULL) {
2826 		ire_refrele(ire);
2827 		src = ipha->ipha_dst;
2828 	} else {
2829 		src = INADDR_ANY;
2830 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2831 	}
2832 
2833 	/*
2834 	 * Check if we can send back more then 8 bytes in addition to
2835 	 * the IP header.  We try to send 64 bytes of data and the internal
2836 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2837 	 */
2838 	len_needed = IPH_HDR_LENGTH(ipha);
2839 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2840 	    ipha->ipha_protocol == IPPROTO_IPV6) {
2841 		if (!pullupmsg(mp, -1)) {
2842 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2843 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2844 			freemsg(mp);
2845 			return;
2846 		}
2847 		ipha = (ipha_t *)mp->b_rptr;
2848 
2849 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2850 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2851 			    len_needed));
2852 		} else {
2853 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2854 
2855 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2856 			len_needed += ip_hdr_length_v6(mp, ip6h);
2857 		}
2858 	}
2859 	len_needed += ipst->ips_ip_icmp_return;
2860 	msg_len = msgdsize(mp);
2861 	if (msg_len > len_needed) {
2862 		(void) adjmsg(mp, len_needed - msg_len);
2863 		msg_len = len_needed;
2864 	}
2865 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2866 	if (mp1 == NULL) {
2867 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2868 		freemsg(mp);
2869 		return;
2870 	}
2871 	mp1->b_cont = mp;
2872 	mp = mp1;
2873 
2874 	/*
2875 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2876 	 * node generates be accepted in peace by all on-host destinations.
2877 	 * If we do NOT assume that all on-host destinations trust
2878 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2879 	 * (Look for IXAF_TRUSTED_ICMP).
2880 	 */
2881 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2882 
2883 	ipha = (ipha_t *)mp->b_rptr;
2884 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2885 	*ipha = icmp_ipha;
2886 	ipha->ipha_src = src;
2887 	ipha->ipha_dst = dst;
2888 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2889 	msg_len += sizeof (icmp_ipha) + len;
2890 	if (msg_len > IP_MAXPACKET) {
2891 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
2892 		msg_len = IP_MAXPACKET;
2893 	}
2894 	ipha->ipha_length = htons((uint16_t)msg_len);
2895 	icmph = (icmph_t *)&ipha[1];
2896 	bcopy(stuff, icmph, len);
2897 	icmph->icmph_checksum = 0;
2898 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2899 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2900 
2901 	(void) ip_output_simple(mp, &ixas);
2902 	ixa_cleanup(&ixas);
2903 }
2904 
2905 /*
2906  * Determine if an ICMP error packet can be sent given the rate limit.
2907  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2908  * in milliseconds) and a burst size. Burst size number of packets can
2909  * be sent arbitrarely closely spaced.
2910  * The state is tracked using two variables to implement an approximate
2911  * token bucket filter:
2912  *	icmp_pkt_err_last - lbolt value when the last burst started
2913  *	icmp_pkt_err_sent - number of packets sent in current burst
2914  */
2915 boolean_t
2916 icmp_err_rate_limit(ip_stack_t *ipst)
2917 {
2918 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2919 	uint_t refilled; /* Number of packets refilled in tbf since last */
2920 	/* Guard against changes by loading into local variable */
2921 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2922 
2923 	if (err_interval == 0)
2924 		return (B_FALSE);
2925 
2926 	if (ipst->ips_icmp_pkt_err_last > now) {
2927 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2928 		ipst->ips_icmp_pkt_err_last = 0;
2929 		ipst->ips_icmp_pkt_err_sent = 0;
2930 	}
2931 	/*
2932 	 * If we are in a burst update the token bucket filter.
2933 	 * Update the "last" time to be close to "now" but make sure
2934 	 * we don't loose precision.
2935 	 */
2936 	if (ipst->ips_icmp_pkt_err_sent != 0) {
2937 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2938 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
2939 			ipst->ips_icmp_pkt_err_sent = 0;
2940 		} else {
2941 			ipst->ips_icmp_pkt_err_sent -= refilled;
2942 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2943 		}
2944 	}
2945 	if (ipst->ips_icmp_pkt_err_sent == 0) {
2946 		/* Start of new burst */
2947 		ipst->ips_icmp_pkt_err_last = now;
2948 	}
2949 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2950 		ipst->ips_icmp_pkt_err_sent++;
2951 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2952 		    ipst->ips_icmp_pkt_err_sent));
2953 		return (B_FALSE);
2954 	}
2955 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
2956 	return (B_TRUE);
2957 }
2958 
2959 /*
2960  * Check if it is ok to send an IPv4 ICMP error packet in
2961  * response to the IPv4 packet in mp.
2962  * Free the message and return null if no
2963  * ICMP error packet should be sent.
2964  */
2965 static mblk_t *
2966 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2967 {
2968 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2969 	icmph_t	*icmph;
2970 	ipha_t	*ipha;
2971 	uint_t	len_needed;
2972 
2973 	if (!mp)
2974 		return (NULL);
2975 	ipha = (ipha_t *)mp->b_rptr;
2976 	if (ip_csum_hdr(ipha)) {
2977 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2978 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2979 		freemsg(mp);
2980 		return (NULL);
2981 	}
2982 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2983 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2984 	    CLASSD(ipha->ipha_dst) ||
2985 	    CLASSD(ipha->ipha_src) ||
2986 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2987 		/* Note: only errors to the fragment with offset 0 */
2988 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2989 		freemsg(mp);
2990 		return (NULL);
2991 	}
2992 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
2993 		/*
2994 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
2995 		 * errors in response to any ICMP errors.
2996 		 */
2997 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
2998 		if (mp->b_wptr - mp->b_rptr < len_needed) {
2999 			if (!pullupmsg(mp, len_needed)) {
3000 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3001 				freemsg(mp);
3002 				return (NULL);
3003 			}
3004 			ipha = (ipha_t *)mp->b_rptr;
3005 		}
3006 		icmph = (icmph_t *)
3007 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3008 		switch (icmph->icmph_type) {
3009 		case ICMP_DEST_UNREACHABLE:
3010 		case ICMP_SOURCE_QUENCH:
3011 		case ICMP_TIME_EXCEEDED:
3012 		case ICMP_PARAM_PROBLEM:
3013 		case ICMP_REDIRECT:
3014 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3015 			freemsg(mp);
3016 			return (NULL);
3017 		default:
3018 			break;
3019 		}
3020 	}
3021 	/*
3022 	 * If this is a labeled system, then check to see if we're allowed to
3023 	 * send a response to this particular sender.  If not, then just drop.
3024 	 */
3025 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3026 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3027 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3028 		freemsg(mp);
3029 		return (NULL);
3030 	}
3031 	if (icmp_err_rate_limit(ipst)) {
3032 		/*
3033 		 * Only send ICMP error packets every so often.
3034 		 * This should be done on a per port/source basis,
3035 		 * but for now this will suffice.
3036 		 */
3037 		freemsg(mp);
3038 		return (NULL);
3039 	}
3040 	return (mp);
3041 }
3042 
3043 /*
3044  * Called when a packet was sent out the same link that it arrived on.
3045  * Check if it is ok to send a redirect and then send it.
3046  */
3047 void
3048 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3049     ip_recv_attr_t *ira)
3050 {
3051 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3052 	ipaddr_t	src, nhop;
3053 	mblk_t		*mp1;
3054 	ire_t		*nhop_ire;
3055 
3056 	/*
3057 	 * Check the source address to see if it originated
3058 	 * on the same logical subnet it is going back out on.
3059 	 * If so, we should be able to send it a redirect.
3060 	 * Avoid sending a redirect if the destination
3061 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3062 	 * or if the packet was source routed out this interface.
3063 	 *
3064 	 * We avoid sending a redirect if the
3065 	 * destination is directly connected
3066 	 * because it is possible that multiple
3067 	 * IP subnets may have been configured on
3068 	 * the link, and the source may not
3069 	 * be on the same subnet as ip destination,
3070 	 * even though they are on the same
3071 	 * physical link.
3072 	 */
3073 	if ((ire->ire_type & IRE_ONLINK) ||
3074 	    ip_source_routed(ipha, ipst))
3075 		return;
3076 
3077 	nhop_ire = ire_nexthop(ire);
3078 	if (nhop_ire == NULL)
3079 		return;
3080 
3081 	nhop = nhop_ire->ire_addr;
3082 
3083 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3084 		ire_t	*ire2;
3085 
3086 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3087 		mutex_enter(&nhop_ire->ire_lock);
3088 		ire2 = nhop_ire->ire_dep_parent;
3089 		if (ire2 != NULL)
3090 			ire_refhold(ire2);
3091 		mutex_exit(&nhop_ire->ire_lock);
3092 		ire_refrele(nhop_ire);
3093 		nhop_ire = ire2;
3094 	}
3095 	if (nhop_ire == NULL)
3096 		return;
3097 
3098 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3099 
3100 	src = ipha->ipha_src;
3101 
3102 	/*
3103 	 * We look at the interface ire for the nexthop,
3104 	 * to see if ipha_src is in the same subnet
3105 	 * as the nexthop.
3106 	 */
3107 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3108 		/*
3109 		 * The source is directly connected.
3110 		 */
3111 		mp1 = copymsg(mp);
3112 		if (mp1 != NULL) {
3113 			icmp_send_redirect(mp1, nhop, ira);
3114 		}
3115 	}
3116 	ire_refrele(nhop_ire);
3117 }
3118 
3119 /*
3120  * Generate an ICMP redirect message.
3121  */
3122 static void
3123 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3124 {
3125 	icmph_t	icmph;
3126 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3127 
3128 	mp = icmp_pkt_err_ok(mp, ira);
3129 	if (mp == NULL)
3130 		return;
3131 
3132 	bzero(&icmph, sizeof (icmph_t));
3133 	icmph.icmph_type = ICMP_REDIRECT;
3134 	icmph.icmph_code = 1;
3135 	icmph.icmph_rd_gateway = gateway;
3136 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3137 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3138 }
3139 
3140 /*
3141  * Generate an ICMP time exceeded message.
3142  */
3143 void
3144 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3145 {
3146 	icmph_t	icmph;
3147 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3148 
3149 	mp = icmp_pkt_err_ok(mp, ira);
3150 	if (mp == NULL)
3151 		return;
3152 
3153 	bzero(&icmph, sizeof (icmph_t));
3154 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3155 	icmph.icmph_code = code;
3156 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3157 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3158 }
3159 
3160 /*
3161  * Generate an ICMP unreachable message.
3162  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3163  * constructed by the caller.
3164  */
3165 void
3166 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3167 {
3168 	icmph_t	icmph;
3169 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3170 
3171 	mp = icmp_pkt_err_ok(mp, ira);
3172 	if (mp == NULL)
3173 		return;
3174 
3175 	bzero(&icmph, sizeof (icmph_t));
3176 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3177 	icmph.icmph_code = code;
3178 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3179 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3180 }
3181 
3182 /*
3183  * Latch in the IPsec state for a stream based the policy in the listener
3184  * and the actions in the ip_recv_attr_t.
3185  * Called directly from TCP and SCTP.
3186  */
3187 boolean_t
3188 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3189 {
3190 	ASSERT(lconnp->conn_policy != NULL);
3191 	ASSERT(connp->conn_policy == NULL);
3192 
3193 	IPPH_REFHOLD(lconnp->conn_policy);
3194 	connp->conn_policy = lconnp->conn_policy;
3195 
3196 	if (ira->ira_ipsec_action != NULL) {
3197 		if (connp->conn_latch == NULL) {
3198 			connp->conn_latch = iplatch_create();
3199 			if (connp->conn_latch == NULL)
3200 				return (B_FALSE);
3201 		}
3202 		ipsec_latch_inbound(connp, ira);
3203 	}
3204 	return (B_TRUE);
3205 }
3206 
3207 /*
3208  * Verify whether or not the IP address is a valid local address.
3209  * Could be a unicast, including one for a down interface.
3210  * If allow_mcbc then a multicast or broadcast address is also
3211  * acceptable.
3212  *
3213  * In the case of a broadcast/multicast address, however, the
3214  * upper protocol is expected to reset the src address
3215  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3216  * no packets are emitted with broadcast/multicast address as
3217  * source address (that violates hosts requirements RFC 1122)
3218  * The addresses valid for bind are:
3219  *	(1) - INADDR_ANY (0)
3220  *	(2) - IP address of an UP interface
3221  *	(3) - IP address of a DOWN interface
3222  *	(4) - valid local IP broadcast addresses. In this case
3223  *	the conn will only receive packets destined to
3224  *	the specified broadcast address.
3225  *	(5) - a multicast address. In this case
3226  *	the conn will only receive packets destined to
3227  *	the specified multicast address. Note: the
3228  *	application still has to issue an
3229  *	IP_ADD_MEMBERSHIP socket option.
3230  *
3231  * In all the above cases, the bound address must be valid in the current zone.
3232  * When the address is loopback, multicast or broadcast, there might be many
3233  * matching IREs so bind has to look up based on the zone.
3234  */
3235 ip_laddr_t
3236 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3237     ip_stack_t *ipst, boolean_t allow_mcbc)
3238 {
3239 	ire_t *src_ire;
3240 
3241 	ASSERT(src_addr != INADDR_ANY);
3242 
3243 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3244 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3245 
3246 	/*
3247 	 * If an address other than in6addr_any is requested,
3248 	 * we verify that it is a valid address for bind
3249 	 * Note: Following code is in if-else-if form for
3250 	 * readability compared to a condition check.
3251 	 */
3252 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3253 		/*
3254 		 * (2) Bind to address of local UP interface
3255 		 */
3256 		ire_refrele(src_ire);
3257 		return (IPVL_UNICAST_UP);
3258 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3259 		/*
3260 		 * (4) Bind to broadcast address
3261 		 */
3262 		ire_refrele(src_ire);
3263 		if (allow_mcbc)
3264 			return (IPVL_BCAST);
3265 		else
3266 			return (IPVL_BAD);
3267 	} else if (CLASSD(src_addr)) {
3268 		/* (5) bind to multicast address. */
3269 		if (src_ire != NULL)
3270 			ire_refrele(src_ire);
3271 
3272 		if (allow_mcbc)
3273 			return (IPVL_MCAST);
3274 		else
3275 			return (IPVL_BAD);
3276 	} else {
3277 		ipif_t *ipif;
3278 
3279 		/*
3280 		 * (3) Bind to address of local DOWN interface?
3281 		 * (ipif_lookup_addr() looks up all interfaces
3282 		 * but we do not get here for UP interfaces
3283 		 * - case (2) above)
3284 		 */
3285 		if (src_ire != NULL)
3286 			ire_refrele(src_ire);
3287 
3288 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3289 		if (ipif == NULL)
3290 			return (IPVL_BAD);
3291 
3292 		/* Not a useful source? */
3293 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3294 			ipif_refrele(ipif);
3295 			return (IPVL_BAD);
3296 		}
3297 		ipif_refrele(ipif);
3298 		return (IPVL_UNICAST_DOWN);
3299 	}
3300 }
3301 
3302 /*
3303  * Insert in the bind fanout for IPv4 and IPv6.
3304  * The caller should already have used ip_laddr_verify_v*() before calling
3305  * this.
3306  */
3307 int
3308 ip_laddr_fanout_insert(conn_t *connp)
3309 {
3310 	int		error;
3311 
3312 	/*
3313 	 * Allow setting new policies. For example, disconnects result
3314 	 * in us being called. As we would have set conn_policy_cached
3315 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3316 	 * can change after the disconnect.
3317 	 */
3318 	connp->conn_policy_cached = B_FALSE;
3319 
3320 	error = ipcl_bind_insert(connp);
3321 	if (error != 0) {
3322 		if (connp->conn_anon_port) {
3323 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3324 			    connp->conn_mlp_type, connp->conn_proto,
3325 			    ntohs(connp->conn_lport), B_FALSE);
3326 		}
3327 		connp->conn_mlp_type = mlptSingle;
3328 	}
3329 	return (error);
3330 }
3331 
3332 /*
3333  * Verify that both the source and destination addresses are valid. If
3334  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3335  * i.e. have no route to it.  Protocols like TCP want to verify destination
3336  * reachability, while tunnels do not.
3337  *
3338  * Determine the route, the interface, and (optionally) the source address
3339  * to use to reach a given destination.
3340  * Note that we allow connect to broadcast and multicast addresses when
3341  * IPDF_ALLOW_MCBC is set.
3342  * first_hop and dst_addr are normally the same, but if source routing
3343  * they will differ; in that case the first_hop is what we'll use for the
3344  * routing lookup but the dce and label checks will be done on dst_addr,
3345  *
3346  * If uinfo is set, then we fill in the best available information
3347  * we have for the destination. This is based on (in priority order) any
3348  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3349  * ill_mtu.
3350  *
3351  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3352  * always do the label check on dst_addr.
3353  */
3354 int
3355 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3356     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3357 {
3358 	ire_t		*ire = NULL;
3359 	int		error = 0;
3360 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3361 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3362 	ip_stack_t	*ipst = ixa->ixa_ipst;
3363 	dce_t		*dce;
3364 	uint_t		pmtu;
3365 	uint_t		generation;
3366 	nce_t		*nce;
3367 	ill_t		*ill = NULL;
3368 	boolean_t	multirt = B_FALSE;
3369 
3370 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3371 
3372 	/*
3373 	 * We never send to zero; the ULPs map it to the loopback address.
3374 	 * We can't allow it since we use zero to mean unitialized in some
3375 	 * places.
3376 	 */
3377 	ASSERT(dst_addr != INADDR_ANY);
3378 
3379 	if (is_system_labeled()) {
3380 		ts_label_t *tsl = NULL;
3381 
3382 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3383 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3384 		if (error != 0)
3385 			return (error);
3386 		if (tsl != NULL) {
3387 			/* Update the label */
3388 			ip_xmit_attr_replace_tsl(ixa, tsl);
3389 		}
3390 	}
3391 
3392 	setsrc = INADDR_ANY;
3393 	/*
3394 	 * Select a route; For IPMP interfaces, we would only select
3395 	 * a "hidden" route (i.e., going through a specific under_ill)
3396 	 * if ixa_ifindex has been specified.
3397 	 */
3398 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3399 	    &generation, &setsrc, &error, &multirt);
3400 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3401 	if (error != 0)
3402 		goto bad_addr;
3403 
3404 	/*
3405 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3406 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3407 	 * Otherwise the destination needn't be reachable.
3408 	 *
3409 	 * If we match on a reject or black hole, then we've got a
3410 	 * local failure.  May as well fail out the connect() attempt,
3411 	 * since it's never going to succeed.
3412 	 */
3413 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3414 		/*
3415 		 * If we're verifying destination reachability, we always want
3416 		 * to complain here.
3417 		 *
3418 		 * If we're not verifying destination reachability but the
3419 		 * destination has a route, we still want to fail on the
3420 		 * temporary address and broadcast address tests.
3421 		 *
3422 		 * In both cases do we let the code continue so some reasonable
3423 		 * information is returned to the caller. That enables the
3424 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3425 		 * use the generation mismatch path to check for the unreachable
3426 		 * case thereby avoiding any specific check in the main path.
3427 		 */
3428 		ASSERT(generation == IRE_GENERATION_VERIFY);
3429 		if (flags & IPDF_VERIFY_DST) {
3430 			/*
3431 			 * Set errno but continue to set up ixa_ire to be
3432 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3433 			 * That allows callers to use ip_output to get an
3434 			 * ICMP error back.
3435 			 */
3436 			if (!(ire->ire_type & IRE_HOST))
3437 				error = ENETUNREACH;
3438 			else
3439 				error = EHOSTUNREACH;
3440 		}
3441 	}
3442 
3443 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3444 	    !(flags & IPDF_ALLOW_MCBC)) {
3445 		ire_refrele(ire);
3446 		ire = ire_reject(ipst, B_FALSE);
3447 		generation = IRE_GENERATION_VERIFY;
3448 		error = ENETUNREACH;
3449 	}
3450 
3451 	/* Cache things */
3452 	if (ixa->ixa_ire != NULL)
3453 		ire_refrele_notr(ixa->ixa_ire);
3454 #ifdef DEBUG
3455 	ire_refhold_notr(ire);
3456 	ire_refrele(ire);
3457 #endif
3458 	ixa->ixa_ire = ire;
3459 	ixa->ixa_ire_generation = generation;
3460 
3461 	/*
3462 	 * Ensure that ixa_dce is always set any time that ixa_ire is set,
3463 	 * since some callers will send a packet to conn_ip_output() even if
3464 	 * there's an error.
3465 	 */
3466 	if (flags & IPDF_UNIQUE_DCE) {
3467 		/* Fallback to the default dce if allocation fails */
3468 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3469 		if (dce != NULL)
3470 			generation = dce->dce_generation;
3471 		else
3472 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3473 	} else {
3474 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3475 	}
3476 	ASSERT(dce != NULL);
3477 	if (ixa->ixa_dce != NULL)
3478 		dce_refrele_notr(ixa->ixa_dce);
3479 #ifdef DEBUG
3480 	dce_refhold_notr(dce);
3481 	dce_refrele(dce);
3482 #endif
3483 	ixa->ixa_dce = dce;
3484 	ixa->ixa_dce_generation = generation;
3485 
3486 	/*
3487 	 * For multicast with multirt we have a flag passed back from
3488 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3489 	 * possible multicast address.
3490 	 * We also need a flag for multicast since we can't check
3491 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3492 	 */
3493 	if (multirt) {
3494 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3495 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3496 	} else {
3497 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3498 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3499 	}
3500 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3501 		/* Get an nce to cache. */
3502 		nce = ire_to_nce(ire, firsthop, NULL);
3503 		if (nce == NULL) {
3504 			/* Allocation failure? */
3505 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3506 		} else {
3507 			if (ixa->ixa_nce != NULL)
3508 				nce_refrele(ixa->ixa_nce);
3509 			ixa->ixa_nce = nce;
3510 		}
3511 	}
3512 
3513 	/*
3514 	 * If the source address is a loopback address, the
3515 	 * destination had best be local or multicast.
3516 	 * If we are sending to an IRE_LOCAL using a loopback source then
3517 	 * it had better be the same zoneid.
3518 	 */
3519 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3520 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3521 			ire = NULL;	/* Stored in ixa_ire */
3522 			error = EADDRNOTAVAIL;
3523 			goto bad_addr;
3524 		}
3525 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3526 			ire = NULL;	/* Stored in ixa_ire */
3527 			error = EADDRNOTAVAIL;
3528 			goto bad_addr;
3529 		}
3530 	}
3531 	if (ire->ire_type & IRE_BROADCAST) {
3532 		/*
3533 		 * If the ULP didn't have a specified source, then we
3534 		 * make sure we reselect the source when sending
3535 		 * broadcasts out different interfaces.
3536 		 */
3537 		if (flags & IPDF_SELECT_SRC)
3538 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3539 		else
3540 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3541 	}
3542 
3543 	/*
3544 	 * Does the caller want us to pick a source address?
3545 	 */
3546 	if (flags & IPDF_SELECT_SRC) {
3547 		ipaddr_t	src_addr;
3548 
3549 		/*
3550 		 * We use use ire_nexthop_ill to avoid the under ipmp
3551 		 * interface for source address selection. Note that for ipmp
3552 		 * probe packets, ixa_ifindex would have been specified, and
3553 		 * the ip_select_route() invocation would have picked an ire
3554 		 * will ire_ill pointing at an under interface.
3555 		 */
3556 		ill = ire_nexthop_ill(ire);
3557 
3558 		/* If unreachable we have no ill but need some source */
3559 		if (ill == NULL) {
3560 			src_addr = htonl(INADDR_LOOPBACK);
3561 			/* Make sure we look for a better source address */
3562 			generation = SRC_GENERATION_VERIFY;
3563 		} else {
3564 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3565 			    ixa->ixa_multicast_ifaddr, zoneid,
3566 			    ipst, &src_addr, &generation, NULL);
3567 			if (error != 0) {
3568 				ire = NULL;	/* Stored in ixa_ire */
3569 				goto bad_addr;
3570 			}
3571 		}
3572 
3573 		/*
3574 		 * We allow the source address to to down.
3575 		 * However, we check that we don't use the loopback address
3576 		 * as a source when sending out on the wire.
3577 		 */
3578 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3579 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3580 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3581 			ire = NULL;	/* Stored in ixa_ire */
3582 			error = EADDRNOTAVAIL;
3583 			goto bad_addr;
3584 		}
3585 
3586 		*src_addrp = src_addr;
3587 		ixa->ixa_src_generation = generation;
3588 	}
3589 
3590 	/*
3591 	 * Make sure we don't leave an unreachable ixa_nce in place
3592 	 * since ip_select_route is used when we unplumb i.e., remove
3593 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3594 	 */
3595 	nce = ixa->ixa_nce;
3596 	if (nce != NULL && nce->nce_is_condemned) {
3597 		nce_refrele(nce);
3598 		ixa->ixa_nce = NULL;
3599 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3600 	}
3601 
3602 	/*
3603 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3604 	 * However, we can't do it for IPv4 multicast or broadcast.
3605 	 */
3606 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3607 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3608 
3609 	/*
3610 	 * Set initial value for fragmentation limit. Either conn_ip_output
3611 	 * or ULP might updates it when there are routing changes.
3612 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3613 	 */
3614 	pmtu = ip_get_pmtu(ixa);
3615 	ixa->ixa_fragsize = pmtu;
3616 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3617 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3618 		ixa->ixa_pmtu = pmtu;
3619 
3620 	/*
3621 	 * Extract information useful for some transports.
3622 	 * First we look for DCE metrics. Then we take what we have in
3623 	 * the metrics in the route, where the offlink is used if we have
3624 	 * one.
3625 	 */
3626 	if (uinfo != NULL) {
3627 		bzero(uinfo, sizeof (*uinfo));
3628 
3629 		if (dce->dce_flags & DCEF_UINFO)
3630 			*uinfo = dce->dce_uinfo;
3631 
3632 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3633 
3634 		/* Allow ire_metrics to decrease the path MTU from above */
3635 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3636 			uinfo->iulp_mtu = pmtu;
3637 
3638 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3639 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3640 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3641 	}
3642 
3643 	if (ill != NULL)
3644 		ill_refrele(ill);
3645 
3646 	return (error);
3647 
3648 bad_addr:
3649 	if (ire != NULL)
3650 		ire_refrele(ire);
3651 
3652 	if (ill != NULL)
3653 		ill_refrele(ill);
3654 
3655 	/*
3656 	 * Make sure we don't leave an unreachable ixa_nce in place
3657 	 * since ip_select_route is used when we unplumb i.e., remove
3658 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3659 	 */
3660 	nce = ixa->ixa_nce;
3661 	if (nce != NULL && nce->nce_is_condemned) {
3662 		nce_refrele(nce);
3663 		ixa->ixa_nce = NULL;
3664 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3665 	}
3666 
3667 	return (error);
3668 }
3669 
3670 
3671 /*
3672  * Get the base MTU for the case when path MTU discovery is not used.
3673  * Takes the MTU of the IRE into account.
3674  */
3675 uint_t
3676 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3677 {
3678 	uint_t mtu = ill->ill_mtu;
3679 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3680 
3681 	if (iremtu != 0 && iremtu < mtu)
3682 		mtu = iremtu;
3683 
3684 	return (mtu);
3685 }
3686 
3687 /*
3688  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3689  * Assumes that ixa_ire, dce, and nce have already been set up.
3690  *
3691  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3692  * We avoid path MTU discovery if it is disabled with ndd.
3693  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3694  *
3695  * NOTE: We also used to turn it off for source routed packets. That
3696  * is no longer required since the dce is per final destination.
3697  */
3698 uint_t
3699 ip_get_pmtu(ip_xmit_attr_t *ixa)
3700 {
3701 	ip_stack_t	*ipst = ixa->ixa_ipst;
3702 	dce_t		*dce;
3703 	nce_t		*nce;
3704 	ire_t		*ire;
3705 	uint_t		pmtu;
3706 
3707 	ire = ixa->ixa_ire;
3708 	dce = ixa->ixa_dce;
3709 	nce = ixa->ixa_nce;
3710 
3711 	/*
3712 	 * If path MTU discovery has been turned off by ndd, then we ignore
3713 	 * any dce_pmtu and for IPv4 we will not set DF.
3714 	 */
3715 	if (!ipst->ips_ip_path_mtu_discovery)
3716 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3717 
3718 	pmtu = IP_MAXPACKET;
3719 	/*
3720 	 * Decide whether whether IPv4 sets DF
3721 	 * For IPv6 "no DF" means to use the 1280 mtu
3722 	 */
3723 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3724 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3725 	} else {
3726 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3727 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3728 			pmtu = IPV6_MIN_MTU;
3729 	}
3730 
3731 	/* Check if the PMTU is to old before we use it */
3732 	if ((dce->dce_flags & DCEF_PMTU) &&
3733 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3734 	    ipst->ips_ip_pathmtu_interval) {
3735 		/*
3736 		 * Older than 20 minutes. Drop the path MTU information.
3737 		 */
3738 		mutex_enter(&dce->dce_lock);
3739 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3740 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3741 		mutex_exit(&dce->dce_lock);
3742 		dce_increment_generation(dce);
3743 	}
3744 
3745 	/* The metrics on the route can lower the path MTU */
3746 	if (ire->ire_metrics.iulp_mtu != 0 &&
3747 	    ire->ire_metrics.iulp_mtu < pmtu)
3748 		pmtu = ire->ire_metrics.iulp_mtu;
3749 
3750 	/*
3751 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3752 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3753 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3754 	 */
3755 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3756 		if (dce->dce_flags & DCEF_PMTU) {
3757 			if (dce->dce_pmtu < pmtu)
3758 				pmtu = dce->dce_pmtu;
3759 
3760 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3761 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3762 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3763 			} else {
3764 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3765 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3766 			}
3767 		} else {
3768 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3769 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3770 		}
3771 	}
3772 
3773 	/*
3774 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3775 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3776 	 * mtu as IRE_LOOPBACK.
3777 	 */
3778 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3779 		uint_t loopback_mtu;
3780 
3781 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3782 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3783 
3784 		if (loopback_mtu < pmtu)
3785 			pmtu = loopback_mtu;
3786 	} else if (nce != NULL) {
3787 		/*
3788 		 * Make sure we don't exceed the interface MTU.
3789 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3790 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3791 		 * to tell the transport something larger than zero.
3792 		 */
3793 		if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3794 			pmtu = nce->nce_common->ncec_ill->ill_mtu;
3795 		if (nce->nce_common->ncec_ill != nce->nce_ill &&
3796 		    nce->nce_ill->ill_mtu < pmtu) {
3797 			/*
3798 			 * for interfaces in an IPMP group, the mtu of
3799 			 * the nce_ill (under_ill) could be different
3800 			 * from the mtu of the ncec_ill, so we take the
3801 			 * min of the two.
3802 			 */
3803 			pmtu = nce->nce_ill->ill_mtu;
3804 		}
3805 	}
3806 
3807 	/*
3808 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3809 	 * Only applies to IPv6.
3810 	 */
3811 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3812 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3813 			switch (ixa->ixa_use_min_mtu) {
3814 			case IPV6_USE_MIN_MTU_MULTICAST:
3815 				if (ire->ire_type & IRE_MULTICAST)
3816 					pmtu = IPV6_MIN_MTU;
3817 				break;
3818 			case IPV6_USE_MIN_MTU_ALWAYS:
3819 				pmtu = IPV6_MIN_MTU;
3820 				break;
3821 			case IPV6_USE_MIN_MTU_NEVER:
3822 				break;
3823 			}
3824 		} else {
3825 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3826 			if (ire->ire_type & IRE_MULTICAST)
3827 				pmtu = IPV6_MIN_MTU;
3828 		}
3829 	}
3830 
3831 	/*
3832 	 * After receiving an ICMPv6 "packet too big" message with a
3833 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3834 	 * will insert a 8-byte fragment header in every packet. We compensate
3835 	 * for those cases by returning a smaller path MTU to the ULP.
3836 	 *
3837 	 * In the case of CGTP then ip_output will add a fragment header.
3838 	 * Make sure there is room for it by telling a smaller number
3839 	 * to the transport.
3840 	 *
3841 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3842 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3843 	 * which is the size of the packets it can send.
3844 	 */
3845 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3846 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
3847 		    (ire->ire_flags & RTF_MULTIRT) ||
3848 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3849 			pmtu -= sizeof (ip6_frag_t);
3850 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3851 		}
3852 	}
3853 
3854 	return (pmtu);
3855 }
3856 
3857 /*
3858  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3859  * the final piece where we don't.  Return a pointer to the first mblk in the
3860  * result, and update the pointer to the next mblk to chew on.  If anything
3861  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3862  * NULL pointer.
3863  */
3864 mblk_t *
3865 ip_carve_mp(mblk_t **mpp, ssize_t len)
3866 {
3867 	mblk_t	*mp0;
3868 	mblk_t	*mp1;
3869 	mblk_t	*mp2;
3870 
3871 	if (!len || !mpp || !(mp0 = *mpp))
3872 		return (NULL);
3873 	/* If we aren't going to consume the first mblk, we need a dup. */
3874 	if (mp0->b_wptr - mp0->b_rptr > len) {
3875 		mp1 = dupb(mp0);
3876 		if (mp1) {
3877 			/* Partition the data between the two mblks. */
3878 			mp1->b_wptr = mp1->b_rptr + len;
3879 			mp0->b_rptr = mp1->b_wptr;
3880 			/*
3881 			 * after adjustments if mblk not consumed is now
3882 			 * unaligned, try to align it. If this fails free
3883 			 * all messages and let upper layer recover.
3884 			 */
3885 			if (!OK_32PTR(mp0->b_rptr)) {
3886 				if (!pullupmsg(mp0, -1)) {
3887 					freemsg(mp0);
3888 					freemsg(mp1);
3889 					*mpp = NULL;
3890 					return (NULL);
3891 				}
3892 			}
3893 		}
3894 		return (mp1);
3895 	}
3896 	/* Eat through as many mblks as we need to get len bytes. */
3897 	len -= mp0->b_wptr - mp0->b_rptr;
3898 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3899 		if (mp2->b_wptr - mp2->b_rptr > len) {
3900 			/*
3901 			 * We won't consume the entire last mblk.  Like
3902 			 * above, dup and partition it.
3903 			 */
3904 			mp1->b_cont = dupb(mp2);
3905 			mp1 = mp1->b_cont;
3906 			if (!mp1) {
3907 				/*
3908 				 * Trouble.  Rather than go to a lot of
3909 				 * trouble to clean up, we free the messages.
3910 				 * This won't be any worse than losing it on
3911 				 * the wire.
3912 				 */
3913 				freemsg(mp0);
3914 				freemsg(mp2);
3915 				*mpp = NULL;
3916 				return (NULL);
3917 			}
3918 			mp1->b_wptr = mp1->b_rptr + len;
3919 			mp2->b_rptr = mp1->b_wptr;
3920 			/*
3921 			 * after adjustments if mblk not consumed is now
3922 			 * unaligned, try to align it. If this fails free
3923 			 * all messages and let upper layer recover.
3924 			 */
3925 			if (!OK_32PTR(mp2->b_rptr)) {
3926 				if (!pullupmsg(mp2, -1)) {
3927 					freemsg(mp0);
3928 					freemsg(mp2);
3929 					*mpp = NULL;
3930 					return (NULL);
3931 				}
3932 			}
3933 			*mpp = mp2;
3934 			return (mp0);
3935 		}
3936 		/* Decrement len by the amount we just got. */
3937 		len -= mp2->b_wptr - mp2->b_rptr;
3938 	}
3939 	/*
3940 	 * len should be reduced to zero now.  If not our caller has
3941 	 * screwed up.
3942 	 */
3943 	if (len) {
3944 		/* Shouldn't happen! */
3945 		freemsg(mp0);
3946 		*mpp = NULL;
3947 		return (NULL);
3948 	}
3949 	/*
3950 	 * We consumed up to exactly the end of an mblk.  Detach the part
3951 	 * we are returning from the rest of the chain.
3952 	 */
3953 	mp1->b_cont = NULL;
3954 	*mpp = mp2;
3955 	return (mp0);
3956 }
3957 
3958 /* The ill stream is being unplumbed. Called from ip_close */
3959 int
3960 ip_modclose(ill_t *ill)
3961 {
3962 	boolean_t success;
3963 	ipsq_t	*ipsq;
3964 	ipif_t	*ipif;
3965 	queue_t	*q = ill->ill_rq;
3966 	ip_stack_t	*ipst = ill->ill_ipst;
3967 	int	i;
3968 	arl_ill_common_t *ai = ill->ill_common;
3969 
3970 	/*
3971 	 * The punlink prior to this may have initiated a capability
3972 	 * negotiation. But ipsq_enter will block until that finishes or
3973 	 * times out.
3974 	 */
3975 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
3976 
3977 	/*
3978 	 * Open/close/push/pop is guaranteed to be single threaded
3979 	 * per stream by STREAMS. FS guarantees that all references
3980 	 * from top are gone before close is called. So there can't
3981 	 * be another close thread that has set CONDEMNED on this ill.
3982 	 * and cause ipsq_enter to return failure.
3983 	 */
3984 	ASSERT(success);
3985 	ipsq = ill->ill_phyint->phyint_ipsq;
3986 
3987 	/*
3988 	 * Mark it condemned. No new reference will be made to this ill.
3989 	 * Lookup functions will return an error. Threads that try to
3990 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
3991 	 * that the refcnt will drop down to zero.
3992 	 */
3993 	mutex_enter(&ill->ill_lock);
3994 	ill->ill_state_flags |= ILL_CONDEMNED;
3995 	for (ipif = ill->ill_ipif; ipif != NULL;
3996 	    ipif = ipif->ipif_next) {
3997 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
3998 	}
3999 	/*
4000 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4001 	 * returns  error if ILL_CONDEMNED is set
4002 	 */
4003 	cv_broadcast(&ill->ill_cv);
4004 	mutex_exit(&ill->ill_lock);
4005 
4006 	/*
4007 	 * Send all the deferred DLPI messages downstream which came in
4008 	 * during the small window right before ipsq_enter(). We do this
4009 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4010 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4011 	 */
4012 	ill_dlpi_send_deferred(ill);
4013 
4014 	/*
4015 	 * Shut down fragmentation reassembly.
4016 	 * ill_frag_timer won't start a timer again.
4017 	 * Now cancel any existing timer
4018 	 */
4019 	(void) untimeout(ill->ill_frag_timer_id);
4020 	(void) ill_frag_timeout(ill, 0);
4021 
4022 	/*
4023 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4024 	 * this ill. Then wait for the refcnts to drop to zero.
4025 	 * ill_is_freeable checks whether the ill is really quiescent.
4026 	 * Then make sure that threads that are waiting to enter the
4027 	 * ipsq have seen the error returned by ipsq_enter and have
4028 	 * gone away. Then we call ill_delete_tail which does the
4029 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4030 	 */
4031 	ill_delete(ill);
4032 	mutex_enter(&ill->ill_lock);
4033 	while (!ill_is_freeable(ill))
4034 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4035 
4036 	while (ill->ill_waiters)
4037 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4038 
4039 	mutex_exit(&ill->ill_lock);
4040 
4041 	/*
4042 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4043 	 * it held until the end of the function since the cleanup
4044 	 * below needs to be able to use the ip_stack_t.
4045 	 */
4046 	netstack_hold(ipst->ips_netstack);
4047 
4048 	/* qprocsoff is done via ill_delete_tail */
4049 	ill_delete_tail(ill);
4050 	/*
4051 	 * synchronously wait for arp stream to unbind. After this, we
4052 	 * cannot get any data packets up from the driver.
4053 	 */
4054 	arp_unbind_complete(ill);
4055 	ASSERT(ill->ill_ipst == NULL);
4056 
4057 	/*
4058 	 * Walk through all conns and qenable those that have queued data.
4059 	 * Close synchronization needs this to
4060 	 * be done to ensure that all upper layers blocked
4061 	 * due to flow control to the closing device
4062 	 * get unblocked.
4063 	 */
4064 	ip1dbg(("ip_wsrv: walking\n"));
4065 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4066 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4067 	}
4068 
4069 	/*
4070 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4071 	 * stream is being torn down before ARP was plumbed (e.g.,
4072 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4073 	 * an error
4074 	 */
4075 	if (ai != NULL) {
4076 		ASSERT(!ill->ill_isv6);
4077 		mutex_enter(&ai->ai_lock);
4078 		ai->ai_ill = NULL;
4079 		if (ai->ai_arl == NULL) {
4080 			mutex_destroy(&ai->ai_lock);
4081 			kmem_free(ai, sizeof (*ai));
4082 		} else {
4083 			cv_signal(&ai->ai_ill_unplumb_done);
4084 			mutex_exit(&ai->ai_lock);
4085 		}
4086 	}
4087 
4088 	mutex_enter(&ipst->ips_ip_mi_lock);
4089 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4090 	mutex_exit(&ipst->ips_ip_mi_lock);
4091 
4092 	/*
4093 	 * credp could be null if the open didn't succeed and ip_modopen
4094 	 * itself calls ip_close.
4095 	 */
4096 	if (ill->ill_credp != NULL)
4097 		crfree(ill->ill_credp);
4098 
4099 	mutex_destroy(&ill->ill_saved_ire_lock);
4100 	mutex_destroy(&ill->ill_lock);
4101 	rw_destroy(&ill->ill_mcast_lock);
4102 	mutex_destroy(&ill->ill_mcast_serializer);
4103 	list_destroy(&ill->ill_nce);
4104 
4105 	/*
4106 	 * Now we are done with the module close pieces that
4107 	 * need the netstack_t.
4108 	 */
4109 	netstack_rele(ipst->ips_netstack);
4110 
4111 	mi_close_free((IDP)ill);
4112 	q->q_ptr = WR(q)->q_ptr = NULL;
4113 
4114 	ipsq_exit(ipsq);
4115 
4116 	return (0);
4117 }
4118 
4119 /*
4120  * This is called as part of close() for IP, UDP, ICMP, and RTS
4121  * in order to quiesce the conn.
4122  */
4123 void
4124 ip_quiesce_conn(conn_t *connp)
4125 {
4126 	boolean_t	drain_cleanup_reqd = B_FALSE;
4127 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4128 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4129 	ip_stack_t	*ipst;
4130 
4131 	ASSERT(!IPCL_IS_TCP(connp));
4132 	ipst = connp->conn_netstack->netstack_ip;
4133 
4134 	/*
4135 	 * Mark the conn as closing, and this conn must not be
4136 	 * inserted in future into any list. Eg. conn_drain_insert(),
4137 	 * won't insert this conn into the conn_drain_list.
4138 	 *
4139 	 * conn_idl, and conn_ilg cannot get set henceforth.
4140 	 */
4141 	mutex_enter(&connp->conn_lock);
4142 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4143 	connp->conn_state_flags |= CONN_CLOSING;
4144 	if (connp->conn_idl != NULL)
4145 		drain_cleanup_reqd = B_TRUE;
4146 	if (connp->conn_oper_pending_ill != NULL)
4147 		conn_ioctl_cleanup_reqd = B_TRUE;
4148 	if (connp->conn_dhcpinit_ill != NULL) {
4149 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4150 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4151 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4152 		connp->conn_dhcpinit_ill = NULL;
4153 	}
4154 	if (connp->conn_ilg != NULL)
4155 		ilg_cleanup_reqd = B_TRUE;
4156 	mutex_exit(&connp->conn_lock);
4157 
4158 	if (conn_ioctl_cleanup_reqd)
4159 		conn_ioctl_cleanup(connp);
4160 
4161 	if (is_system_labeled() && connp->conn_anon_port) {
4162 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4163 		    connp->conn_mlp_type, connp->conn_proto,
4164 		    ntohs(connp->conn_lport), B_FALSE);
4165 		connp->conn_anon_port = 0;
4166 	}
4167 	connp->conn_mlp_type = mlptSingle;
4168 
4169 	/*
4170 	 * Remove this conn from any fanout list it is on.
4171 	 * and then wait for any threads currently operating
4172 	 * on this endpoint to finish
4173 	 */
4174 	ipcl_hash_remove(connp);
4175 
4176 	/*
4177 	 * Remove this conn from the drain list, and do any other cleanup that
4178 	 * may be required.  (TCP conns are never flow controlled, and
4179 	 * conn_idl will be NULL.)
4180 	 */
4181 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4182 		idl_t *idl = connp->conn_idl;
4183 
4184 		mutex_enter(&idl->idl_lock);
4185 		conn_drain(connp, B_TRUE);
4186 		mutex_exit(&idl->idl_lock);
4187 	}
4188 
4189 	if (connp == ipst->ips_ip_g_mrouter)
4190 		(void) ip_mrouter_done(ipst);
4191 
4192 	if (ilg_cleanup_reqd)
4193 		ilg_delete_all(connp);
4194 
4195 	/*
4196 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4197 	 * callers from write side can't be there now because close
4198 	 * is in progress. The only other caller is ipcl_walk
4199 	 * which checks for the condemned flag.
4200 	 */
4201 	mutex_enter(&connp->conn_lock);
4202 	connp->conn_state_flags |= CONN_CONDEMNED;
4203 	while (connp->conn_ref != 1)
4204 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4205 	connp->conn_state_flags |= CONN_QUIESCED;
4206 	mutex_exit(&connp->conn_lock);
4207 }
4208 
4209 /* ARGSUSED */
4210 int
4211 ip_close(queue_t *q, int flags)
4212 {
4213 	conn_t		*connp;
4214 
4215 	/*
4216 	 * Call the appropriate delete routine depending on whether this is
4217 	 * a module or device.
4218 	 */
4219 	if (WR(q)->q_next != NULL) {
4220 		/* This is a module close */
4221 		return (ip_modclose((ill_t *)q->q_ptr));
4222 	}
4223 
4224 	connp = q->q_ptr;
4225 	ip_quiesce_conn(connp);
4226 
4227 	qprocsoff(q);
4228 
4229 	/*
4230 	 * Now we are truly single threaded on this stream, and can
4231 	 * delete the things hanging off the connp, and finally the connp.
4232 	 * We removed this connp from the fanout list, it cannot be
4233 	 * accessed thru the fanouts, and we already waited for the
4234 	 * conn_ref to drop to 0. We are already in close, so
4235 	 * there cannot be any other thread from the top. qprocsoff
4236 	 * has completed, and service has completed or won't run in
4237 	 * future.
4238 	 */
4239 	ASSERT(connp->conn_ref == 1);
4240 
4241 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4242 
4243 	connp->conn_ref--;
4244 	ipcl_conn_destroy(connp);
4245 
4246 	q->q_ptr = WR(q)->q_ptr = NULL;
4247 	return (0);
4248 }
4249 
4250 /*
4251  * Wapper around putnext() so that ip_rts_request can merely use
4252  * conn_recv.
4253  */
4254 /*ARGSUSED2*/
4255 static void
4256 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4257 {
4258 	conn_t *connp = (conn_t *)arg1;
4259 
4260 	putnext(connp->conn_rq, mp);
4261 }
4262 
4263 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4264 /* ARGSUSED */
4265 static void
4266 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4267 {
4268 	freemsg(mp);
4269 }
4270 
4271 /*
4272  * Called when the module is about to be unloaded
4273  */
4274 void
4275 ip_ddi_destroy(void)
4276 {
4277 	tnet_fini();
4278 
4279 	icmp_ddi_g_destroy();
4280 	rts_ddi_g_destroy();
4281 	udp_ddi_g_destroy();
4282 	sctp_ddi_g_destroy();
4283 	tcp_ddi_g_destroy();
4284 	ilb_ddi_g_destroy();
4285 	dce_g_destroy();
4286 	ipsec_policy_g_destroy();
4287 	ipcl_g_destroy();
4288 	ip_net_g_destroy();
4289 	ip_ire_g_fini();
4290 	inet_minor_destroy(ip_minor_arena_sa);
4291 #if defined(_LP64)
4292 	inet_minor_destroy(ip_minor_arena_la);
4293 #endif
4294 
4295 #ifdef DEBUG
4296 	list_destroy(&ip_thread_list);
4297 	rw_destroy(&ip_thread_rwlock);
4298 	tsd_destroy(&ip_thread_data);
4299 #endif
4300 
4301 	netstack_unregister(NS_IP);
4302 }
4303 
4304 /*
4305  * First step in cleanup.
4306  */
4307 /* ARGSUSED */
4308 static void
4309 ip_stack_shutdown(netstackid_t stackid, void *arg)
4310 {
4311 	ip_stack_t *ipst = (ip_stack_t *)arg;
4312 
4313 #ifdef NS_DEBUG
4314 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4315 #endif
4316 
4317 	/*
4318 	 * Perform cleanup for special interfaces (loopback and IPMP).
4319 	 */
4320 	ip_interface_cleanup(ipst);
4321 
4322 	/*
4323 	 * The *_hook_shutdown()s start the process of notifying any
4324 	 * consumers that things are going away.... nothing is destroyed.
4325 	 */
4326 	ipv4_hook_shutdown(ipst);
4327 	ipv6_hook_shutdown(ipst);
4328 	arp_hook_shutdown(ipst);
4329 
4330 	mutex_enter(&ipst->ips_capab_taskq_lock);
4331 	ipst->ips_capab_taskq_quit = B_TRUE;
4332 	cv_signal(&ipst->ips_capab_taskq_cv);
4333 	mutex_exit(&ipst->ips_capab_taskq_lock);
4334 }
4335 
4336 /*
4337  * Free the IP stack instance.
4338  */
4339 static void
4340 ip_stack_fini(netstackid_t stackid, void *arg)
4341 {
4342 	ip_stack_t *ipst = (ip_stack_t *)arg;
4343 	int ret;
4344 
4345 #ifdef NS_DEBUG
4346 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4347 #endif
4348 	/*
4349 	 * At this point, all of the notifications that the events and
4350 	 * protocols are going away have been run, meaning that we can
4351 	 * now set about starting to clean things up.
4352 	 */
4353 	ipobs_fini(ipst);
4354 	ipv4_hook_destroy(ipst);
4355 	ipv6_hook_destroy(ipst);
4356 	arp_hook_destroy(ipst);
4357 	ip_net_destroy(ipst);
4358 
4359 	ipmp_destroy(ipst);
4360 
4361 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4362 	ipst->ips_ip_mibkp = NULL;
4363 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4364 	ipst->ips_icmp_mibkp = NULL;
4365 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4366 	ipst->ips_ip_kstat = NULL;
4367 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4368 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4369 	ipst->ips_ip6_kstat = NULL;
4370 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4371 
4372 	kmem_free(ipst->ips_propinfo_tbl,
4373 	    ip_propinfo_count * sizeof (mod_prop_info_t));
4374 	ipst->ips_propinfo_tbl = NULL;
4375 
4376 	dce_stack_destroy(ipst);
4377 	ip_mrouter_stack_destroy(ipst);
4378 
4379 	ret = untimeout(ipst->ips_igmp_timeout_id);
4380 	if (ret == -1) {
4381 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4382 	} else {
4383 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4384 		ipst->ips_igmp_timeout_id = 0;
4385 	}
4386 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4387 	if (ret == -1) {
4388 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4389 	} else {
4390 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4391 		ipst->ips_igmp_slowtimeout_id = 0;
4392 	}
4393 	ret = untimeout(ipst->ips_mld_timeout_id);
4394 	if (ret == -1) {
4395 		ASSERT(ipst->ips_mld_timeout_id == 0);
4396 	} else {
4397 		ASSERT(ipst->ips_mld_timeout_id != 0);
4398 		ipst->ips_mld_timeout_id = 0;
4399 	}
4400 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4401 	if (ret == -1) {
4402 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4403 	} else {
4404 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4405 		ipst->ips_mld_slowtimeout_id = 0;
4406 	}
4407 
4408 	ip_ire_fini(ipst);
4409 	ip6_asp_free(ipst);
4410 	conn_drain_fini(ipst);
4411 	ipcl_destroy(ipst);
4412 
4413 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4414 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4415 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4416 	ipst->ips_ndp4 = NULL;
4417 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4418 	ipst->ips_ndp6 = NULL;
4419 
4420 	if (ipst->ips_loopback_ksp != NULL) {
4421 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4422 		ipst->ips_loopback_ksp = NULL;
4423 	}
4424 
4425 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4426 	cv_destroy(&ipst->ips_capab_taskq_cv);
4427 
4428 	rw_destroy(&ipst->ips_srcid_lock);
4429 
4430 	mutex_destroy(&ipst->ips_ip_mi_lock);
4431 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4432 
4433 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4434 	mutex_destroy(&ipst->ips_mld_timer_lock);
4435 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4436 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4437 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4438 	rw_destroy(&ipst->ips_ill_g_lock);
4439 
4440 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4441 	ipst->ips_phyint_g_list = NULL;
4442 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4443 	ipst->ips_ill_g_heads = NULL;
4444 
4445 	ldi_ident_release(ipst->ips_ldi_ident);
4446 	kmem_free(ipst, sizeof (*ipst));
4447 }
4448 
4449 /*
4450  * This function is called from the TSD destructor, and is used to debug
4451  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4452  * details.
4453  */
4454 static void
4455 ip_thread_exit(void *phash)
4456 {
4457 	th_hash_t *thh = phash;
4458 
4459 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4460 	list_remove(&ip_thread_list, thh);
4461 	rw_exit(&ip_thread_rwlock);
4462 	mod_hash_destroy_hash(thh->thh_hash);
4463 	kmem_free(thh, sizeof (*thh));
4464 }
4465 
4466 /*
4467  * Called when the IP kernel module is loaded into the kernel
4468  */
4469 void
4470 ip_ddi_init(void)
4471 {
4472 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4473 
4474 	/*
4475 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4476 	 * initial devices: ip, ip6, tcp, tcp6.
4477 	 */
4478 	/*
4479 	 * If this is a 64-bit kernel, then create two separate arenas -
4480 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4481 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4482 	 */
4483 	ip_minor_arena_la = NULL;
4484 	ip_minor_arena_sa = NULL;
4485 #if defined(_LP64)
4486 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4487 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4488 		cmn_err(CE_PANIC,
4489 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4490 	}
4491 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4492 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4493 		cmn_err(CE_PANIC,
4494 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4495 	}
4496 #else
4497 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4498 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4499 		cmn_err(CE_PANIC,
4500 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4501 	}
4502 #endif
4503 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4504 
4505 	ipcl_g_init();
4506 	ip_ire_g_init();
4507 	ip_net_g_init();
4508 
4509 #ifdef DEBUG
4510 	tsd_create(&ip_thread_data, ip_thread_exit);
4511 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4512 	list_create(&ip_thread_list, sizeof (th_hash_t),
4513 	    offsetof(th_hash_t, thh_link));
4514 #endif
4515 	ipsec_policy_g_init();
4516 	tcp_ddi_g_init();
4517 	sctp_ddi_g_init();
4518 	dce_g_init();
4519 
4520 	/*
4521 	 * We want to be informed each time a stack is created or
4522 	 * destroyed in the kernel, so we can maintain the
4523 	 * set of udp_stack_t's.
4524 	 */
4525 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4526 	    ip_stack_fini);
4527 
4528 	tnet_init();
4529 
4530 	udp_ddi_g_init();
4531 	rts_ddi_g_init();
4532 	icmp_ddi_g_init();
4533 	ilb_ddi_g_init();
4534 }
4535 
4536 /*
4537  * Initialize the IP stack instance.
4538  */
4539 static void *
4540 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4541 {
4542 	ip_stack_t	*ipst;
4543 	size_t		arrsz;
4544 	major_t		major;
4545 
4546 #ifdef NS_DEBUG
4547 	printf("ip_stack_init(stack %d)\n", stackid);
4548 #endif
4549 
4550 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4551 	ipst->ips_netstack = ns;
4552 
4553 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4554 	    KM_SLEEP);
4555 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4556 	    KM_SLEEP);
4557 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4558 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4559 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4560 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4561 
4562 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4563 	ipst->ips_igmp_deferred_next = INFINITY;
4564 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4565 	ipst->ips_mld_deferred_next = INFINITY;
4566 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4567 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4568 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4569 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4570 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4571 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4572 
4573 	ipcl_init(ipst);
4574 	ip_ire_init(ipst);
4575 	ip6_asp_init(ipst);
4576 	ipif_init(ipst);
4577 	conn_drain_init(ipst);
4578 	ip_mrouter_stack_init(ipst);
4579 	dce_stack_init(ipst);
4580 
4581 	ipst->ips_ip_multirt_log_interval = 1000;
4582 
4583 	ipst->ips_ill_index = 1;
4584 
4585 	ipst->ips_saved_ip_forwarding = -1;
4586 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4587 
4588 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4589 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4590 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4591 
4592 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4593 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4594 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4595 	ipst->ips_ip6_kstat =
4596 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4597 
4598 	ipst->ips_ip_src_id = 1;
4599 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4600 
4601 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4602 
4603 	ip_net_init(ipst, ns);
4604 	ipv4_hook_init(ipst);
4605 	ipv6_hook_init(ipst);
4606 	arp_hook_init(ipst);
4607 	ipmp_init(ipst);
4608 	ipobs_init(ipst);
4609 
4610 	/*
4611 	 * Create the taskq dispatcher thread and initialize related stuff.
4612 	 */
4613 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4614 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4615 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4616 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4617 
4618 	major = mod_name_to_major(INET_NAME);
4619 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4620 	return (ipst);
4621 }
4622 
4623 /*
4624  * Allocate and initialize a DLPI template of the specified length.  (May be
4625  * called as writer.)
4626  */
4627 mblk_t *
4628 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4629 {
4630 	mblk_t	*mp;
4631 
4632 	mp = allocb(len, BPRI_MED);
4633 	if (!mp)
4634 		return (NULL);
4635 
4636 	/*
4637 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4638 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4639 	 * that other DLPI are M_PROTO.
4640 	 */
4641 	if (prim == DL_INFO_REQ) {
4642 		mp->b_datap->db_type = M_PCPROTO;
4643 	} else {
4644 		mp->b_datap->db_type = M_PROTO;
4645 	}
4646 
4647 	mp->b_wptr = mp->b_rptr + len;
4648 	bzero(mp->b_rptr, len);
4649 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4650 	return (mp);
4651 }
4652 
4653 /*
4654  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4655  */
4656 mblk_t *
4657 ip_dlnotify_alloc(uint_t notification, uint_t data)
4658 {
4659 	dl_notify_ind_t	*notifyp;
4660 	mblk_t		*mp;
4661 
4662 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4663 		return (NULL);
4664 
4665 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4666 	notifyp->dl_notification = notification;
4667 	notifyp->dl_data = data;
4668 	return (mp);
4669 }
4670 
4671 /*
4672  * Debug formatting routine.  Returns a character string representation of the
4673  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4674  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4675  *
4676  * Once the ndd table-printing interfaces are removed, this can be changed to
4677  * standard dotted-decimal form.
4678  */
4679 char *
4680 ip_dot_addr(ipaddr_t addr, char *buf)
4681 {
4682 	uint8_t *ap = (uint8_t *)&addr;
4683 
4684 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4685 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4686 	return (buf);
4687 }
4688 
4689 /*
4690  * Write the given MAC address as a printable string in the usual colon-
4691  * separated format.
4692  */
4693 const char *
4694 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4695 {
4696 	char *bp;
4697 
4698 	if (alen == 0 || buflen < 4)
4699 		return ("?");
4700 	bp = buf;
4701 	for (;;) {
4702 		/*
4703 		 * If there are more MAC address bytes available, but we won't
4704 		 * have any room to print them, then add "..." to the string
4705 		 * instead.  See below for the 'magic number' explanation.
4706 		 */
4707 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4708 			(void) strcpy(bp, "...");
4709 			break;
4710 		}
4711 		(void) sprintf(bp, "%02x", *addr++);
4712 		bp += 2;
4713 		if (--alen == 0)
4714 			break;
4715 		*bp++ = ':';
4716 		buflen -= 3;
4717 		/*
4718 		 * At this point, based on the first 'if' statement above,
4719 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4720 		 * buflen >= 4.  The first case leaves room for the final "xx"
4721 		 * number and trailing NUL byte.  The second leaves room for at
4722 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4723 		 * that statement.
4724 		 */
4725 	}
4726 	return (buf);
4727 }
4728 
4729 /*
4730  * Called when it is conceptually a ULP that would sent the packet
4731  * e.g., port unreachable and protocol unreachable. Check that the packet
4732  * would have passed the IPsec global policy before sending the error.
4733  *
4734  * Send an ICMP error after patching up the packet appropriately.
4735  * Uses ip_drop_input and bumps the appropriate MIB.
4736  */
4737 void
4738 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4739     ip_recv_attr_t *ira)
4740 {
4741 	ipha_t		*ipha;
4742 	boolean_t	secure;
4743 	ill_t		*ill = ira->ira_ill;
4744 	ip_stack_t	*ipst = ill->ill_ipst;
4745 	netstack_t	*ns = ipst->ips_netstack;
4746 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4747 
4748 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4749 
4750 	/*
4751 	 * We are generating an icmp error for some inbound packet.
4752 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4753 	 * Before we generate an error, check with global policy
4754 	 * to see whether this is allowed to enter the system. As
4755 	 * there is no "conn", we are checking with global policy.
4756 	 */
4757 	ipha = (ipha_t *)mp->b_rptr;
4758 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4759 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4760 		if (mp == NULL)
4761 			return;
4762 	}
4763 
4764 	/* We never send errors for protocols that we do implement */
4765 	if (ira->ira_protocol == IPPROTO_ICMP ||
4766 	    ira->ira_protocol == IPPROTO_IGMP) {
4767 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4768 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4769 		freemsg(mp);
4770 		return;
4771 	}
4772 	/*
4773 	 * Have to correct checksum since
4774 	 * the packet might have been
4775 	 * fragmented and the reassembly code in ip_rput
4776 	 * does not restore the IP checksum.
4777 	 */
4778 	ipha->ipha_hdr_checksum = 0;
4779 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4780 
4781 	switch (icmp_type) {
4782 	case ICMP_DEST_UNREACHABLE:
4783 		switch (icmp_code) {
4784 		case ICMP_PROTOCOL_UNREACHABLE:
4785 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4786 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4787 			break;
4788 		case ICMP_PORT_UNREACHABLE:
4789 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4790 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4791 			break;
4792 		}
4793 
4794 		icmp_unreachable(mp, icmp_code, ira);
4795 		break;
4796 	default:
4797 #ifdef DEBUG
4798 		panic("ip_fanout_send_icmp_v4: wrong type");
4799 		/*NOTREACHED*/
4800 #else
4801 		freemsg(mp);
4802 		break;
4803 #endif
4804 	}
4805 }
4806 
4807 /*
4808  * Used to send an ICMP error message when a packet is received for
4809  * a protocol that is not supported. The mblk passed as argument
4810  * is consumed by this function.
4811  */
4812 void
4813 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4814 {
4815 	ipha_t		*ipha;
4816 
4817 	ipha = (ipha_t *)mp->b_rptr;
4818 	if (ira->ira_flags & IRAF_IS_IPV4) {
4819 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4820 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4821 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4822 	} else {
4823 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4824 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4825 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4826 	}
4827 }
4828 
4829 /*
4830  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4831  * Handles IPv4 and IPv6.
4832  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4833  * Caller is responsible for dropping references to the conn.
4834  */
4835 void
4836 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4837     ip_recv_attr_t *ira)
4838 {
4839 	ill_t		*ill = ira->ira_ill;
4840 	ip_stack_t	*ipst = ill->ill_ipst;
4841 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4842 	boolean_t	secure;
4843 	uint_t		protocol = ira->ira_protocol;
4844 	iaflags_t	iraflags = ira->ira_flags;
4845 	queue_t		*rq;
4846 
4847 	secure = iraflags & IRAF_IPSEC_SECURE;
4848 
4849 	rq = connp->conn_rq;
4850 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4851 		switch (protocol) {
4852 		case IPPROTO_ICMPV6:
4853 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4854 			break;
4855 		case IPPROTO_ICMP:
4856 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4857 			break;
4858 		default:
4859 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4860 			break;
4861 		}
4862 		freemsg(mp);
4863 		return;
4864 	}
4865 
4866 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4867 
4868 	if (((iraflags & IRAF_IS_IPV4) ?
4869 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4870 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4871 	    secure) {
4872 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4873 		    ip6h, ira);
4874 		if (mp == NULL) {
4875 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4876 			/* Note that mp is NULL */
4877 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4878 			return;
4879 		}
4880 	}
4881 
4882 	if (iraflags & IRAF_ICMP_ERROR) {
4883 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4884 	} else {
4885 		ill_t *rill = ira->ira_rill;
4886 
4887 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4888 		ira->ira_ill = ira->ira_rill = NULL;
4889 		/* Send it upstream */
4890 		(connp->conn_recv)(connp, mp, NULL, ira);
4891 		ira->ira_ill = ill;
4892 		ira->ira_rill = rill;
4893 	}
4894 }
4895 
4896 /*
4897  * Handle protocols with which IP is less intimate.  There
4898  * can be more than one stream bound to a particular
4899  * protocol.  When this is the case, normally each one gets a copy
4900  * of any incoming packets.
4901  *
4902  * IPsec NOTE :
4903  *
4904  * Don't allow a secure packet going up a non-secure connection.
4905  * We don't allow this because
4906  *
4907  * 1) Reply might go out in clear which will be dropped at
4908  *    the sending side.
4909  * 2) If the reply goes out in clear it will give the
4910  *    adversary enough information for getting the key in
4911  *    most of the cases.
4912  *
4913  * Moreover getting a secure packet when we expect clear
4914  * implies that SA's were added without checking for
4915  * policy on both ends. This should not happen once ISAKMP
4916  * is used to negotiate SAs as SAs will be added only after
4917  * verifying the policy.
4918  *
4919  * Zones notes:
4920  * Earlier in ip_input on a system with multiple shared-IP zones we
4921  * duplicate the multicast and broadcast packets and send them up
4922  * with each explicit zoneid that exists on that ill.
4923  * This means that here we can match the zoneid with SO_ALLZONES being special.
4924  */
4925 void
4926 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
4927 {
4928 	mblk_t		*mp1;
4929 	ipaddr_t	laddr;
4930 	conn_t		*connp, *first_connp, *next_connp;
4931 	connf_t		*connfp;
4932 	ill_t		*ill = ira->ira_ill;
4933 	ip_stack_t	*ipst = ill->ill_ipst;
4934 
4935 	laddr = ipha->ipha_dst;
4936 
4937 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
4938 	mutex_enter(&connfp->connf_lock);
4939 	connp = connfp->connf_head;
4940 	for (connp = connfp->connf_head; connp != NULL;
4941 	    connp = connp->conn_next) {
4942 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4943 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4944 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4945 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
4946 			break;
4947 		}
4948 	}
4949 
4950 	if (connp == NULL) {
4951 		/*
4952 		 * No one bound to these addresses.  Is
4953 		 * there a client that wants all
4954 		 * unclaimed datagrams?
4955 		 */
4956 		mutex_exit(&connfp->connf_lock);
4957 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4958 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4959 		return;
4960 	}
4961 
4962 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
4963 
4964 	CONN_INC_REF(connp);
4965 	first_connp = connp;
4966 	connp = connp->conn_next;
4967 
4968 	for (;;) {
4969 		while (connp != NULL) {
4970 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4971 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4972 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4973 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
4974 			    ira, connp)))
4975 				break;
4976 			connp = connp->conn_next;
4977 		}
4978 
4979 		if (connp == NULL) {
4980 			/* No more interested clients */
4981 			connp = first_connp;
4982 			break;
4983 		}
4984 		if (((mp1 = dupmsg(mp)) == NULL) &&
4985 		    ((mp1 = copymsg(mp)) == NULL)) {
4986 			/* Memory allocation failed */
4987 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4988 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4989 			connp = first_connp;
4990 			break;
4991 		}
4992 
4993 		CONN_INC_REF(connp);
4994 		mutex_exit(&connfp->connf_lock);
4995 
4996 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
4997 		    ira);
4998 
4999 		mutex_enter(&connfp->connf_lock);
5000 		/* Follow the next pointer before releasing the conn. */
5001 		next_connp = connp->conn_next;
5002 		CONN_DEC_REF(connp);
5003 		connp = next_connp;
5004 	}
5005 
5006 	/* Last one.  Send it upstream. */
5007 	mutex_exit(&connfp->connf_lock);
5008 
5009 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5010 
5011 	CONN_DEC_REF(connp);
5012 }
5013 
5014 /*
5015  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5016  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5017  * is not consumed.
5018  *
5019  * One of three things can happen, all of which affect the passed-in mblk:
5020  *
5021  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5022  *
5023  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5024  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5025  *
5026  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5027  */
5028 mblk_t *
5029 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5030 {
5031 	int shift, plen, iph_len;
5032 	ipha_t *ipha;
5033 	udpha_t *udpha;
5034 	uint32_t *spi;
5035 	uint32_t esp_ports;
5036 	uint8_t *orptr;
5037 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5038 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5039 
5040 	ipha = (ipha_t *)mp->b_rptr;
5041 	iph_len = ira->ira_ip_hdr_length;
5042 	plen = ira->ira_pktlen;
5043 
5044 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5045 		/*
5046 		 * Most likely a keepalive for the benefit of an intervening
5047 		 * NAT.  These aren't for us, per se, so drop it.
5048 		 *
5049 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5050 		 * byte packets (keepalives are 1-byte), but we'll drop them
5051 		 * also.
5052 		 */
5053 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5054 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5055 		return (NULL);
5056 	}
5057 
5058 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5059 		/* might as well pull it all up - it might be ESP. */
5060 		if (!pullupmsg(mp, -1)) {
5061 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5062 			    DROPPER(ipss, ipds_esp_nomem),
5063 			    &ipss->ipsec_dropper);
5064 			return (NULL);
5065 		}
5066 
5067 		ipha = (ipha_t *)mp->b_rptr;
5068 	}
5069 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5070 	if (*spi == 0) {
5071 		/* UDP packet - remove 0-spi. */
5072 		shift = sizeof (uint32_t);
5073 	} else {
5074 		/* ESP-in-UDP packet - reduce to ESP. */
5075 		ipha->ipha_protocol = IPPROTO_ESP;
5076 		shift = sizeof (udpha_t);
5077 	}
5078 
5079 	/* Fix IP header */
5080 	ira->ira_pktlen = (plen - shift);
5081 	ipha->ipha_length = htons(ira->ira_pktlen);
5082 	ipha->ipha_hdr_checksum = 0;
5083 
5084 	orptr = mp->b_rptr;
5085 	mp->b_rptr += shift;
5086 
5087 	udpha = (udpha_t *)(orptr + iph_len);
5088 	if (*spi == 0) {
5089 		ASSERT((uint8_t *)ipha == orptr);
5090 		udpha->uha_length = htons(plen - shift - iph_len);
5091 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5092 		esp_ports = 0;
5093 	} else {
5094 		esp_ports = *((uint32_t *)udpha);
5095 		ASSERT(esp_ports != 0);
5096 	}
5097 	ovbcopy(orptr, orptr + shift, iph_len);
5098 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5099 		ipha = (ipha_t *)(orptr + shift);
5100 
5101 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5102 		ira->ira_esp_udp_ports = esp_ports;
5103 		ip_fanout_v4(mp, ipha, ira);
5104 		return (NULL);
5105 	}
5106 	return (mp);
5107 }
5108 
5109 /*
5110  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5111  * Handles IPv4 and IPv6.
5112  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5113  * Caller is responsible for dropping references to the conn.
5114  */
5115 void
5116 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5117     ip_recv_attr_t *ira)
5118 {
5119 	ill_t		*ill = ira->ira_ill;
5120 	ip_stack_t	*ipst = ill->ill_ipst;
5121 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5122 	boolean_t	secure;
5123 	iaflags_t	iraflags = ira->ira_flags;
5124 
5125 	secure = iraflags & IRAF_IPSEC_SECURE;
5126 
5127 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5128 	    !canputnext(connp->conn_rq)) {
5129 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5130 		freemsg(mp);
5131 		return;
5132 	}
5133 
5134 	if (((iraflags & IRAF_IS_IPV4) ?
5135 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5136 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5137 	    secure) {
5138 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5139 		    ip6h, ira);
5140 		if (mp == NULL) {
5141 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5142 			/* Note that mp is NULL */
5143 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5144 			return;
5145 		}
5146 	}
5147 
5148 	/*
5149 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5150 	 * check. Only ip_fanout_v4 has that check.
5151 	 */
5152 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5153 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5154 	} else {
5155 		ill_t *rill = ira->ira_rill;
5156 
5157 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5158 		ira->ira_ill = ira->ira_rill = NULL;
5159 		/* Send it upstream */
5160 		(connp->conn_recv)(connp, mp, NULL, ira);
5161 		ira->ira_ill = ill;
5162 		ira->ira_rill = rill;
5163 	}
5164 }
5165 
5166 /*
5167  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5168  * (Unicast fanout is handled in ip_input_v4.)
5169  *
5170  * If SO_REUSEADDR is set all multicast and broadcast packets
5171  * will be delivered to all conns bound to the same port.
5172  *
5173  * If there is at least one matching AF_INET receiver, then we will
5174  * ignore any AF_INET6 receivers.
5175  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5176  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5177  * packets.
5178  *
5179  * Zones notes:
5180  * Earlier in ip_input on a system with multiple shared-IP zones we
5181  * duplicate the multicast and broadcast packets and send them up
5182  * with each explicit zoneid that exists on that ill.
5183  * This means that here we can match the zoneid with SO_ALLZONES being special.
5184  */
5185 void
5186 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5187     ip_recv_attr_t *ira)
5188 {
5189 	ipaddr_t	laddr;
5190 	in6_addr_t	v6faddr;
5191 	conn_t		*connp;
5192 	connf_t		*connfp;
5193 	ipaddr_t	faddr;
5194 	ill_t		*ill = ira->ira_ill;
5195 	ip_stack_t	*ipst = ill->ill_ipst;
5196 
5197 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5198 
5199 	laddr = ipha->ipha_dst;
5200 	faddr = ipha->ipha_src;
5201 
5202 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5203 	mutex_enter(&connfp->connf_lock);
5204 	connp = connfp->connf_head;
5205 
5206 	/*
5207 	 * If SO_REUSEADDR has been set on the first we send the
5208 	 * packet to all clients that have joined the group and
5209 	 * match the port.
5210 	 */
5211 	while (connp != NULL) {
5212 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5213 		    conn_wantpacket(connp, ira, ipha) &&
5214 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5215 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5216 			break;
5217 		connp = connp->conn_next;
5218 	}
5219 
5220 	if (connp == NULL)
5221 		goto notfound;
5222 
5223 	CONN_INC_REF(connp);
5224 
5225 	if (connp->conn_reuseaddr) {
5226 		conn_t		*first_connp = connp;
5227 		conn_t		*next_connp;
5228 		mblk_t		*mp1;
5229 
5230 		connp = connp->conn_next;
5231 		for (;;) {
5232 			while (connp != NULL) {
5233 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5234 				    fport, faddr) &&
5235 				    conn_wantpacket(connp, ira, ipha) &&
5236 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5237 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5238 				    ira, connp)))
5239 					break;
5240 				connp = connp->conn_next;
5241 			}
5242 			if (connp == NULL) {
5243 				/* No more interested clients */
5244 				connp = first_connp;
5245 				break;
5246 			}
5247 			if (((mp1 = dupmsg(mp)) == NULL) &&
5248 			    ((mp1 = copymsg(mp)) == NULL)) {
5249 				/* Memory allocation failed */
5250 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5251 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5252 				connp = first_connp;
5253 				break;
5254 			}
5255 			CONN_INC_REF(connp);
5256 			mutex_exit(&connfp->connf_lock);
5257 
5258 			IP_STAT(ipst, ip_udp_fanmb);
5259 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5260 			    NULL, ira);
5261 			mutex_enter(&connfp->connf_lock);
5262 			/* Follow the next pointer before releasing the conn */
5263 			next_connp = connp->conn_next;
5264 			CONN_DEC_REF(connp);
5265 			connp = next_connp;
5266 		}
5267 	}
5268 
5269 	/* Last one.  Send it upstream. */
5270 	mutex_exit(&connfp->connf_lock);
5271 	IP_STAT(ipst, ip_udp_fanmb);
5272 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5273 	CONN_DEC_REF(connp);
5274 	return;
5275 
5276 notfound:
5277 	mutex_exit(&connfp->connf_lock);
5278 	/*
5279 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5280 	 * have already been matched above, since they live in the IPv4
5281 	 * fanout tables. This implies we only need to
5282 	 * check for IPv6 in6addr_any endpoints here.
5283 	 * Thus we compare using ipv6_all_zeros instead of the destination
5284 	 * address, except for the multicast group membership lookup which
5285 	 * uses the IPv4 destination.
5286 	 */
5287 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5288 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5289 	mutex_enter(&connfp->connf_lock);
5290 	connp = connfp->connf_head;
5291 	/*
5292 	 * IPv4 multicast packet being delivered to an AF_INET6
5293 	 * in6addr_any endpoint.
5294 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5295 	 * and not conn_wantpacket_v6() since any multicast membership is
5296 	 * for an IPv4-mapped multicast address.
5297 	 */
5298 	while (connp != NULL) {
5299 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5300 		    fport, v6faddr) &&
5301 		    conn_wantpacket(connp, ira, ipha) &&
5302 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5303 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5304 			break;
5305 		connp = connp->conn_next;
5306 	}
5307 
5308 	if (connp == NULL) {
5309 		/*
5310 		 * No one bound to this port.  Is
5311 		 * there a client that wants all
5312 		 * unclaimed datagrams?
5313 		 */
5314 		mutex_exit(&connfp->connf_lock);
5315 
5316 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5317 		    NULL) {
5318 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5319 			ip_fanout_proto_v4(mp, ipha, ira);
5320 		} else {
5321 			/*
5322 			 * We used to attempt to send an icmp error here, but
5323 			 * since this is known to be a multicast packet
5324 			 * and we don't send icmp errors in response to
5325 			 * multicast, just drop the packet and give up sooner.
5326 			 */
5327 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5328 			freemsg(mp);
5329 		}
5330 		return;
5331 	}
5332 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5333 
5334 	/*
5335 	 * If SO_REUSEADDR has been set on the first we send the
5336 	 * packet to all clients that have joined the group and
5337 	 * match the port.
5338 	 */
5339 	if (connp->conn_reuseaddr) {
5340 		conn_t		*first_connp = connp;
5341 		conn_t		*next_connp;
5342 		mblk_t		*mp1;
5343 
5344 		CONN_INC_REF(connp);
5345 		connp = connp->conn_next;
5346 		for (;;) {
5347 			while (connp != NULL) {
5348 				if (IPCL_UDP_MATCH_V6(connp, lport,
5349 				    ipv6_all_zeros, fport, v6faddr) &&
5350 				    conn_wantpacket(connp, ira, ipha) &&
5351 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5352 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5353 				    ira, connp)))
5354 					break;
5355 				connp = connp->conn_next;
5356 			}
5357 			if (connp == NULL) {
5358 				/* No more interested clients */
5359 				connp = first_connp;
5360 				break;
5361 			}
5362 			if (((mp1 = dupmsg(mp)) == NULL) &&
5363 			    ((mp1 = copymsg(mp)) == NULL)) {
5364 				/* Memory allocation failed */
5365 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5366 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5367 				connp = first_connp;
5368 				break;
5369 			}
5370 			CONN_INC_REF(connp);
5371 			mutex_exit(&connfp->connf_lock);
5372 
5373 			IP_STAT(ipst, ip_udp_fanmb);
5374 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5375 			    NULL, ira);
5376 			mutex_enter(&connfp->connf_lock);
5377 			/* Follow the next pointer before releasing the conn */
5378 			next_connp = connp->conn_next;
5379 			CONN_DEC_REF(connp);
5380 			connp = next_connp;
5381 		}
5382 	}
5383 
5384 	/* Last one.  Send it upstream. */
5385 	mutex_exit(&connfp->connf_lock);
5386 	IP_STAT(ipst, ip_udp_fanmb);
5387 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5388 	CONN_DEC_REF(connp);
5389 }
5390 
5391 /*
5392  * Split an incoming packet's IPv4 options into the label and the other options.
5393  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5394  * clearing out any leftover label or options.
5395  * Otherwise it just makes ipp point into the packet.
5396  *
5397  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5398  */
5399 int
5400 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5401 {
5402 	uchar_t		*opt;
5403 	uint32_t	totallen;
5404 	uint32_t	optval;
5405 	uint32_t	optlen;
5406 
5407 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5408 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5409 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5410 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5411 
5412 	/*
5413 	 * Get length (in 4 byte octets) of IP header options.
5414 	 */
5415 	totallen = ipha->ipha_version_and_hdr_length -
5416 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5417 
5418 	if (totallen == 0) {
5419 		if (!allocate)
5420 			return (0);
5421 
5422 		/* Clear out anything from a previous packet */
5423 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5424 			kmem_free(ipp->ipp_ipv4_options,
5425 			    ipp->ipp_ipv4_options_len);
5426 			ipp->ipp_ipv4_options = NULL;
5427 			ipp->ipp_ipv4_options_len = 0;
5428 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5429 		}
5430 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5431 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5432 			ipp->ipp_label_v4 = NULL;
5433 			ipp->ipp_label_len_v4 = 0;
5434 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5435 		}
5436 		return (0);
5437 	}
5438 
5439 	totallen <<= 2;
5440 	opt = (uchar_t *)&ipha[1];
5441 	if (!is_system_labeled()) {
5442 
5443 	copyall:
5444 		if (!allocate) {
5445 			if (totallen != 0) {
5446 				ipp->ipp_ipv4_options = opt;
5447 				ipp->ipp_ipv4_options_len = totallen;
5448 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5449 			}
5450 			return (0);
5451 		}
5452 		/* Just copy all of options */
5453 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5454 			if (totallen == ipp->ipp_ipv4_options_len) {
5455 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5456 				return (0);
5457 			}
5458 			kmem_free(ipp->ipp_ipv4_options,
5459 			    ipp->ipp_ipv4_options_len);
5460 			ipp->ipp_ipv4_options = NULL;
5461 			ipp->ipp_ipv4_options_len = 0;
5462 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5463 		}
5464 		if (totallen == 0)
5465 			return (0);
5466 
5467 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5468 		if (ipp->ipp_ipv4_options == NULL)
5469 			return (ENOMEM);
5470 		ipp->ipp_ipv4_options_len = totallen;
5471 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5472 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5473 		return (0);
5474 	}
5475 
5476 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5477 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5478 		ipp->ipp_label_v4 = NULL;
5479 		ipp->ipp_label_len_v4 = 0;
5480 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5481 	}
5482 
5483 	/*
5484 	 * Search for CIPSO option.
5485 	 * We assume CIPSO is first in options if it is present.
5486 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5487 	 * prior to the CIPSO option.
5488 	 */
5489 	while (totallen != 0) {
5490 		switch (optval = opt[IPOPT_OPTVAL]) {
5491 		case IPOPT_EOL:
5492 			return (0);
5493 		case IPOPT_NOP:
5494 			optlen = 1;
5495 			break;
5496 		default:
5497 			if (totallen <= IPOPT_OLEN)
5498 				return (EINVAL);
5499 			optlen = opt[IPOPT_OLEN];
5500 			if (optlen < 2)
5501 				return (EINVAL);
5502 		}
5503 		if (optlen > totallen)
5504 			return (EINVAL);
5505 
5506 		switch (optval) {
5507 		case IPOPT_COMSEC:
5508 			if (!allocate) {
5509 				ipp->ipp_label_v4 = opt;
5510 				ipp->ipp_label_len_v4 = optlen;
5511 				ipp->ipp_fields |= IPPF_LABEL_V4;
5512 			} else {
5513 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5514 				    KM_NOSLEEP);
5515 				if (ipp->ipp_label_v4 == NULL)
5516 					return (ENOMEM);
5517 				ipp->ipp_label_len_v4 = optlen;
5518 				ipp->ipp_fields |= IPPF_LABEL_V4;
5519 				bcopy(opt, ipp->ipp_label_v4, optlen);
5520 			}
5521 			totallen -= optlen;
5522 			opt += optlen;
5523 
5524 			/* Skip padding bytes until we get to a multiple of 4 */
5525 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5526 				totallen--;
5527 				opt++;
5528 			}
5529 			/* Remaining as ipp_ipv4_options */
5530 			goto copyall;
5531 		}
5532 		totallen -= optlen;
5533 		opt += optlen;
5534 	}
5535 	/* No CIPSO found; return everything as ipp_ipv4_options */
5536 	totallen = ipha->ipha_version_and_hdr_length -
5537 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5538 	totallen <<= 2;
5539 	opt = (uchar_t *)&ipha[1];
5540 	goto copyall;
5541 }
5542 
5543 /*
5544  * Efficient versions of lookup for an IRE when we only
5545  * match the address.
5546  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5547  * Does not handle multicast addresses.
5548  */
5549 uint_t
5550 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5551 {
5552 	ire_t *ire;
5553 	uint_t result;
5554 
5555 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5556 	ASSERT(ire != NULL);
5557 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5558 		result = IRE_NOROUTE;
5559 	else
5560 		result = ire->ire_type;
5561 	ire_refrele(ire);
5562 	return (result);
5563 }
5564 
5565 /*
5566  * Efficient versions of lookup for an IRE when we only
5567  * match the address.
5568  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5569  * Does not handle multicast addresses.
5570  */
5571 uint_t
5572 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5573 {
5574 	ire_t *ire;
5575 	uint_t result;
5576 
5577 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5578 	ASSERT(ire != NULL);
5579 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5580 		result = IRE_NOROUTE;
5581 	else
5582 		result = ire->ire_type;
5583 	ire_refrele(ire);
5584 	return (result);
5585 }
5586 
5587 /*
5588  * Nobody should be sending
5589  * packets up this stream
5590  */
5591 static void
5592 ip_lrput(queue_t *q, mblk_t *mp)
5593 {
5594 	switch (mp->b_datap->db_type) {
5595 	case M_FLUSH:
5596 		/* Turn around */
5597 		if (*mp->b_rptr & FLUSHW) {
5598 			*mp->b_rptr &= ~FLUSHR;
5599 			qreply(q, mp);
5600 			return;
5601 		}
5602 		break;
5603 	}
5604 	freemsg(mp);
5605 }
5606 
5607 /* Nobody should be sending packets down this stream */
5608 /* ARGSUSED */
5609 void
5610 ip_lwput(queue_t *q, mblk_t *mp)
5611 {
5612 	freemsg(mp);
5613 }
5614 
5615 /*
5616  * Move the first hop in any source route to ipha_dst and remove that part of
5617  * the source route.  Called by other protocols.  Errors in option formatting
5618  * are ignored - will be handled by ip_output_options. Return the final
5619  * destination (either ipha_dst or the last entry in a source route.)
5620  */
5621 ipaddr_t
5622 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5623 {
5624 	ipoptp_t	opts;
5625 	uchar_t		*opt;
5626 	uint8_t		optval;
5627 	uint8_t		optlen;
5628 	ipaddr_t	dst;
5629 	int		i;
5630 	ip_stack_t	*ipst = ns->netstack_ip;
5631 
5632 	ip2dbg(("ip_massage_options\n"));
5633 	dst = ipha->ipha_dst;
5634 	for (optval = ipoptp_first(&opts, ipha);
5635 	    optval != IPOPT_EOL;
5636 	    optval = ipoptp_next(&opts)) {
5637 		opt = opts.ipoptp_cur;
5638 		switch (optval) {
5639 			uint8_t off;
5640 		case IPOPT_SSRR:
5641 		case IPOPT_LSRR:
5642 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5643 				ip1dbg(("ip_massage_options: bad src route\n"));
5644 				break;
5645 			}
5646 			optlen = opts.ipoptp_len;
5647 			off = opt[IPOPT_OFFSET];
5648 			off--;
5649 		redo_srr:
5650 			if (optlen < IP_ADDR_LEN ||
5651 			    off > optlen - IP_ADDR_LEN) {
5652 				/* End of source route */
5653 				ip1dbg(("ip_massage_options: end of SR\n"));
5654 				break;
5655 			}
5656 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5657 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5658 			    ntohl(dst)));
5659 			/*
5660 			 * Check if our address is present more than
5661 			 * once as consecutive hops in source route.
5662 			 * XXX verify per-interface ip_forwarding
5663 			 * for source route?
5664 			 */
5665 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5666 				off += IP_ADDR_LEN;
5667 				goto redo_srr;
5668 			}
5669 			if (dst == htonl(INADDR_LOOPBACK)) {
5670 				ip1dbg(("ip_massage_options: loopback addr in "
5671 				    "source route!\n"));
5672 				break;
5673 			}
5674 			/*
5675 			 * Update ipha_dst to be the first hop and remove the
5676 			 * first hop from the source route (by overwriting
5677 			 * part of the option with NOP options).
5678 			 */
5679 			ipha->ipha_dst = dst;
5680 			/* Put the last entry in dst */
5681 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5682 			    3;
5683 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5684 
5685 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5686 			    ntohl(dst)));
5687 			/* Move down and overwrite */
5688 			opt[IP_ADDR_LEN] = opt[0];
5689 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5690 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5691 			for (i = 0; i < IP_ADDR_LEN; i++)
5692 				opt[i] = IPOPT_NOP;
5693 			break;
5694 		}
5695 	}
5696 	return (dst);
5697 }
5698 
5699 /*
5700  * Return the network mask
5701  * associated with the specified address.
5702  */
5703 ipaddr_t
5704 ip_net_mask(ipaddr_t addr)
5705 {
5706 	uchar_t	*up = (uchar_t *)&addr;
5707 	ipaddr_t mask = 0;
5708 	uchar_t	*maskp = (uchar_t *)&mask;
5709 
5710 #if defined(__i386) || defined(__amd64)
5711 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5712 #endif
5713 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5714 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5715 #endif
5716 	if (CLASSD(addr)) {
5717 		maskp[0] = 0xF0;
5718 		return (mask);
5719 	}
5720 
5721 	/* We assume Class E default netmask to be 32 */
5722 	if (CLASSE(addr))
5723 		return (0xffffffffU);
5724 
5725 	if (addr == 0)
5726 		return (0);
5727 	maskp[0] = 0xFF;
5728 	if ((up[0] & 0x80) == 0)
5729 		return (mask);
5730 
5731 	maskp[1] = 0xFF;
5732 	if ((up[0] & 0xC0) == 0x80)
5733 		return (mask);
5734 
5735 	maskp[2] = 0xFF;
5736 	if ((up[0] & 0xE0) == 0xC0)
5737 		return (mask);
5738 
5739 	/* Otherwise return no mask */
5740 	return ((ipaddr_t)0);
5741 }
5742 
5743 /* Name/Value Table Lookup Routine */
5744 char *
5745 ip_nv_lookup(nv_t *nv, int value)
5746 {
5747 	if (!nv)
5748 		return (NULL);
5749 	for (; nv->nv_name; nv++) {
5750 		if (nv->nv_value == value)
5751 			return (nv->nv_name);
5752 	}
5753 	return ("unknown");
5754 }
5755 
5756 static int
5757 ip_wait_for_info_ack(ill_t *ill)
5758 {
5759 	int err;
5760 
5761 	mutex_enter(&ill->ill_lock);
5762 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5763 		/*
5764 		 * Return value of 0 indicates a pending signal.
5765 		 */
5766 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5767 		if (err == 0) {
5768 			mutex_exit(&ill->ill_lock);
5769 			return (EINTR);
5770 		}
5771 	}
5772 	mutex_exit(&ill->ill_lock);
5773 	/*
5774 	 * ip_rput_other could have set an error  in ill_error on
5775 	 * receipt of M_ERROR.
5776 	 */
5777 	return (ill->ill_error);
5778 }
5779 
5780 /*
5781  * This is a module open, i.e. this is a control stream for access
5782  * to a DLPI device.  We allocate an ill_t as the instance data in
5783  * this case.
5784  */
5785 static int
5786 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5787 {
5788 	ill_t	*ill;
5789 	int	err;
5790 	zoneid_t zoneid;
5791 	netstack_t *ns;
5792 	ip_stack_t *ipst;
5793 
5794 	/*
5795 	 * Prevent unprivileged processes from pushing IP so that
5796 	 * they can't send raw IP.
5797 	 */
5798 	if (secpolicy_net_rawaccess(credp) != 0)
5799 		return (EPERM);
5800 
5801 	ns = netstack_find_by_cred(credp);
5802 	ASSERT(ns != NULL);
5803 	ipst = ns->netstack_ip;
5804 	ASSERT(ipst != NULL);
5805 
5806 	/*
5807 	 * For exclusive stacks we set the zoneid to zero
5808 	 * to make IP operate as if in the global zone.
5809 	 */
5810 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5811 		zoneid = GLOBAL_ZONEID;
5812 	else
5813 		zoneid = crgetzoneid(credp);
5814 
5815 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5816 	q->q_ptr = WR(q)->q_ptr = ill;
5817 	ill->ill_ipst = ipst;
5818 	ill->ill_zoneid = zoneid;
5819 
5820 	/*
5821 	 * ill_init initializes the ill fields and then sends down
5822 	 * down a DL_INFO_REQ after calling qprocson.
5823 	 */
5824 	err = ill_init(q, ill);
5825 
5826 	if (err != 0) {
5827 		mi_free(ill);
5828 		netstack_rele(ipst->ips_netstack);
5829 		q->q_ptr = NULL;
5830 		WR(q)->q_ptr = NULL;
5831 		return (err);
5832 	}
5833 
5834 	/*
5835 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5836 	 *
5837 	 * ill_init initializes the ipsq marking this thread as
5838 	 * writer
5839 	 */
5840 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5841 	err = ip_wait_for_info_ack(ill);
5842 	if (err == 0)
5843 		ill->ill_credp = credp;
5844 	else
5845 		goto fail;
5846 
5847 	crhold(credp);
5848 
5849 	mutex_enter(&ipst->ips_ip_mi_lock);
5850 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5851 	    sflag, credp);
5852 	mutex_exit(&ipst->ips_ip_mi_lock);
5853 fail:
5854 	if (err) {
5855 		(void) ip_close(q, 0);
5856 		return (err);
5857 	}
5858 	return (0);
5859 }
5860 
5861 /* For /dev/ip aka AF_INET open */
5862 int
5863 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5864 {
5865 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5866 }
5867 
5868 /* For /dev/ip6 aka AF_INET6 open */
5869 int
5870 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5871 {
5872 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5873 }
5874 
5875 /* IP open routine. */
5876 int
5877 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5878     boolean_t isv6)
5879 {
5880 	conn_t 		*connp;
5881 	major_t		maj;
5882 	zoneid_t	zoneid;
5883 	netstack_t	*ns;
5884 	ip_stack_t	*ipst;
5885 
5886 	/* Allow reopen. */
5887 	if (q->q_ptr != NULL)
5888 		return (0);
5889 
5890 	if (sflag & MODOPEN) {
5891 		/* This is a module open */
5892 		return (ip_modopen(q, devp, flag, sflag, credp));
5893 	}
5894 
5895 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5896 		/*
5897 		 * Non streams based socket looking for a stream
5898 		 * to access IP
5899 		 */
5900 		return (ip_helper_stream_setup(q, devp, flag, sflag,
5901 		    credp, isv6));
5902 	}
5903 
5904 	ns = netstack_find_by_cred(credp);
5905 	ASSERT(ns != NULL);
5906 	ipst = ns->netstack_ip;
5907 	ASSERT(ipst != NULL);
5908 
5909 	/*
5910 	 * For exclusive stacks we set the zoneid to zero
5911 	 * to make IP operate as if in the global zone.
5912 	 */
5913 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5914 		zoneid = GLOBAL_ZONEID;
5915 	else
5916 		zoneid = crgetzoneid(credp);
5917 
5918 	/*
5919 	 * We are opening as a device. This is an IP client stream, and we
5920 	 * allocate an conn_t as the instance data.
5921 	 */
5922 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
5923 
5924 	/*
5925 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
5926 	 * done by netstack_find_by_cred()
5927 	 */
5928 	netstack_rele(ipst->ips_netstack);
5929 
5930 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
5931 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
5932 	connp->conn_ixa->ixa_zoneid = zoneid;
5933 	connp->conn_zoneid = zoneid;
5934 
5935 	connp->conn_rq = q;
5936 	q->q_ptr = WR(q)->q_ptr = connp;
5937 
5938 	/* Minor tells us which /dev entry was opened */
5939 	if (isv6) {
5940 		connp->conn_family = AF_INET6;
5941 		connp->conn_ipversion = IPV6_VERSION;
5942 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
5943 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
5944 	} else {
5945 		connp->conn_family = AF_INET;
5946 		connp->conn_ipversion = IPV4_VERSION;
5947 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
5948 	}
5949 
5950 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
5951 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
5952 		connp->conn_minor_arena = ip_minor_arena_la;
5953 	} else {
5954 		/*
5955 		 * Either minor numbers in the large arena were exhausted
5956 		 * or a non socket application is doing the open.
5957 		 * Try to allocate from the small arena.
5958 		 */
5959 		if ((connp->conn_dev =
5960 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
5961 			/* CONN_DEC_REF takes care of netstack_rele() */
5962 			q->q_ptr = WR(q)->q_ptr = NULL;
5963 			CONN_DEC_REF(connp);
5964 			return (EBUSY);
5965 		}
5966 		connp->conn_minor_arena = ip_minor_arena_sa;
5967 	}
5968 
5969 	maj = getemajor(*devp);
5970 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
5971 
5972 	/*
5973 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
5974 	 */
5975 	connp->conn_cred = credp;
5976 	connp->conn_cpid = curproc->p_pid;
5977 	/* Cache things in ixa without an extra refhold */
5978 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
5979 	connp->conn_ixa->ixa_cred = connp->conn_cred;
5980 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
5981 	if (is_system_labeled())
5982 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
5983 
5984 	/*
5985 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
5986 	 */
5987 	connp->conn_recv = ip_conn_input;
5988 	connp->conn_recvicmp = ip_conn_input_icmp;
5989 
5990 	crhold(connp->conn_cred);
5991 
5992 	/*
5993 	 * If the caller has the process-wide flag set, then default to MAC
5994 	 * exempt mode.  This allows read-down to unlabeled hosts.
5995 	 */
5996 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5997 		connp->conn_mac_mode = CONN_MAC_AWARE;
5998 
5999 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6000 
6001 	connp->conn_rq = q;
6002 	connp->conn_wq = WR(q);
6003 
6004 	/* Non-zero default values */
6005 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6006 
6007 	/*
6008 	 * Make the conn globally visible to walkers
6009 	 */
6010 	ASSERT(connp->conn_ref == 1);
6011 	mutex_enter(&connp->conn_lock);
6012 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6013 	mutex_exit(&connp->conn_lock);
6014 
6015 	qprocson(q);
6016 
6017 	return (0);
6018 }
6019 
6020 /*
6021  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6022  * all of them are copied to the conn_t. If the req is "zero", the policy is
6023  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6024  * fields.
6025  * We keep only the latest setting of the policy and thus policy setting
6026  * is not incremental/cumulative.
6027  *
6028  * Requests to set policies with multiple alternative actions will
6029  * go through a different API.
6030  */
6031 int
6032 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6033 {
6034 	uint_t ah_req = 0;
6035 	uint_t esp_req = 0;
6036 	uint_t se_req = 0;
6037 	ipsec_act_t *actp = NULL;
6038 	uint_t nact;
6039 	ipsec_policy_head_t *ph;
6040 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6041 	int error = 0;
6042 	netstack_t	*ns = connp->conn_netstack;
6043 	ip_stack_t	*ipst = ns->netstack_ip;
6044 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6045 
6046 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6047 
6048 	/*
6049 	 * The IP_SEC_OPT option does not allow variable length parameters,
6050 	 * hence a request cannot be NULL.
6051 	 */
6052 	if (req == NULL)
6053 		return (EINVAL);
6054 
6055 	ah_req = req->ipsr_ah_req;
6056 	esp_req = req->ipsr_esp_req;
6057 	se_req = req->ipsr_self_encap_req;
6058 
6059 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6060 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6061 		return (EINVAL);
6062 
6063 	/*
6064 	 * Are we dealing with a request to reset the policy (i.e.
6065 	 * zero requests).
6066 	 */
6067 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6068 	    (esp_req & REQ_MASK) == 0 &&
6069 	    (se_req & REQ_MASK) == 0);
6070 
6071 	if (!is_pol_reset) {
6072 		/*
6073 		 * If we couldn't load IPsec, fail with "protocol
6074 		 * not supported".
6075 		 * IPsec may not have been loaded for a request with zero
6076 		 * policies, so we don't fail in this case.
6077 		 */
6078 		mutex_enter(&ipss->ipsec_loader_lock);
6079 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6080 			mutex_exit(&ipss->ipsec_loader_lock);
6081 			return (EPROTONOSUPPORT);
6082 		}
6083 		mutex_exit(&ipss->ipsec_loader_lock);
6084 
6085 		/*
6086 		 * Test for valid requests. Invalid algorithms
6087 		 * need to be tested by IPsec code because new
6088 		 * algorithms can be added dynamically.
6089 		 */
6090 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6091 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6092 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6093 			return (EINVAL);
6094 		}
6095 
6096 		/*
6097 		 * Only privileged users can issue these
6098 		 * requests.
6099 		 */
6100 		if (((ah_req & IPSEC_PREF_NEVER) ||
6101 		    (esp_req & IPSEC_PREF_NEVER) ||
6102 		    (se_req & IPSEC_PREF_NEVER)) &&
6103 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6104 			return (EPERM);
6105 		}
6106 
6107 		/*
6108 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6109 		 * are mutually exclusive.
6110 		 */
6111 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6112 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6113 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6114 			/* Both of them are set */
6115 			return (EINVAL);
6116 		}
6117 	}
6118 
6119 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6120 
6121 	/*
6122 	 * If we have already cached policies in conn_connect(), don't
6123 	 * let them change now. We cache policies for connections
6124 	 * whose src,dst [addr, port] is known.
6125 	 */
6126 	if (connp->conn_policy_cached) {
6127 		return (EINVAL);
6128 	}
6129 
6130 	/*
6131 	 * We have a zero policies, reset the connection policy if already
6132 	 * set. This will cause the connection to inherit the
6133 	 * global policy, if any.
6134 	 */
6135 	if (is_pol_reset) {
6136 		if (connp->conn_policy != NULL) {
6137 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6138 			connp->conn_policy = NULL;
6139 		}
6140 		connp->conn_in_enforce_policy = B_FALSE;
6141 		connp->conn_out_enforce_policy = B_FALSE;
6142 		return (0);
6143 	}
6144 
6145 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6146 	    ipst->ips_netstack);
6147 	if (ph == NULL)
6148 		goto enomem;
6149 
6150 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6151 	if (actp == NULL)
6152 		goto enomem;
6153 
6154 	/*
6155 	 * Always insert IPv4 policy entries, since they can also apply to
6156 	 * ipv6 sockets being used in ipv4-compat mode.
6157 	 */
6158 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6159 	    IPSEC_TYPE_INBOUND, ns))
6160 		goto enomem;
6161 	is_pol_inserted = B_TRUE;
6162 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6163 	    IPSEC_TYPE_OUTBOUND, ns))
6164 		goto enomem;
6165 
6166 	/*
6167 	 * We're looking at a v6 socket, also insert the v6-specific
6168 	 * entries.
6169 	 */
6170 	if (connp->conn_family == AF_INET6) {
6171 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6172 		    IPSEC_TYPE_INBOUND, ns))
6173 			goto enomem;
6174 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6175 		    IPSEC_TYPE_OUTBOUND, ns))
6176 			goto enomem;
6177 	}
6178 
6179 	ipsec_actvec_free(actp, nact);
6180 
6181 	/*
6182 	 * If the requests need security, set enforce_policy.
6183 	 * If the requests are IPSEC_PREF_NEVER, one should
6184 	 * still set conn_out_enforce_policy so that ip_set_destination
6185 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6186 	 * for connections that we don't cache policy in at connect time,
6187 	 * if global policy matches in ip_output_attach_policy, we
6188 	 * don't wrongly inherit global policy. Similarly, we need
6189 	 * to set conn_in_enforce_policy also so that we don't verify
6190 	 * policy wrongly.
6191 	 */
6192 	if ((ah_req & REQ_MASK) != 0 ||
6193 	    (esp_req & REQ_MASK) != 0 ||
6194 	    (se_req & REQ_MASK) != 0) {
6195 		connp->conn_in_enforce_policy = B_TRUE;
6196 		connp->conn_out_enforce_policy = B_TRUE;
6197 	}
6198 
6199 	return (error);
6200 #undef REQ_MASK
6201 
6202 	/*
6203 	 * Common memory-allocation-failure exit path.
6204 	 */
6205 enomem:
6206 	if (actp != NULL)
6207 		ipsec_actvec_free(actp, nact);
6208 	if (is_pol_inserted)
6209 		ipsec_polhead_flush(ph, ns);
6210 	return (ENOMEM);
6211 }
6212 
6213 /*
6214  * Set socket options for joining and leaving multicast groups.
6215  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6216  * The caller has already check that the option name is consistent with
6217  * the address family of the socket.
6218  */
6219 int
6220 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6221     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6222 {
6223 	int		*i1 = (int *)invalp;
6224 	int		error = 0;
6225 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6226 	struct ip_mreq	*v4_mreqp;
6227 	struct ipv6_mreq *v6_mreqp;
6228 	struct group_req *greqp;
6229 	ire_t *ire;
6230 	boolean_t done = B_FALSE;
6231 	ipaddr_t ifaddr;
6232 	in6_addr_t v6group;
6233 	uint_t ifindex;
6234 	boolean_t mcast_opt = B_TRUE;
6235 	mcast_record_t fmode;
6236 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6237 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6238 
6239 	switch (name) {
6240 	case IP_ADD_MEMBERSHIP:
6241 	case IPV6_JOIN_GROUP:
6242 		mcast_opt = B_FALSE;
6243 		/* FALLTHRU */
6244 	case MCAST_JOIN_GROUP:
6245 		fmode = MODE_IS_EXCLUDE;
6246 		optfn = ip_opt_add_group;
6247 		break;
6248 
6249 	case IP_DROP_MEMBERSHIP:
6250 	case IPV6_LEAVE_GROUP:
6251 		mcast_opt = B_FALSE;
6252 		/* FALLTHRU */
6253 	case MCAST_LEAVE_GROUP:
6254 		fmode = MODE_IS_INCLUDE;
6255 		optfn = ip_opt_delete_group;
6256 		break;
6257 	default:
6258 		ASSERT(0);
6259 	}
6260 
6261 	if (mcast_opt) {
6262 		struct sockaddr_in *sin;
6263 		struct sockaddr_in6 *sin6;
6264 
6265 		greqp = (struct group_req *)i1;
6266 		if (greqp->gr_group.ss_family == AF_INET) {
6267 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6268 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6269 		} else {
6270 			if (!inet6)
6271 				return (EINVAL);	/* Not on INET socket */
6272 
6273 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6274 			v6group = sin6->sin6_addr;
6275 		}
6276 		ifaddr = INADDR_ANY;
6277 		ifindex = greqp->gr_interface;
6278 	} else if (inet6) {
6279 		v6_mreqp = (struct ipv6_mreq *)i1;
6280 		v6group = v6_mreqp->ipv6mr_multiaddr;
6281 		ifaddr = INADDR_ANY;
6282 		ifindex = v6_mreqp->ipv6mr_interface;
6283 	} else {
6284 		v4_mreqp = (struct ip_mreq *)i1;
6285 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6286 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6287 		ifindex = 0;
6288 	}
6289 
6290 	/*
6291 	 * In the multirouting case, we need to replicate
6292 	 * the request on all interfaces that will take part
6293 	 * in replication.  We do so because multirouting is
6294 	 * reflective, thus we will probably receive multi-
6295 	 * casts on those interfaces.
6296 	 * The ip_multirt_apply_membership() succeeds if
6297 	 * the operation succeeds on at least one interface.
6298 	 */
6299 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6300 		ipaddr_t group;
6301 
6302 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6303 
6304 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6305 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6306 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6307 	} else {
6308 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6309 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6310 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6311 	}
6312 	if (ire != NULL) {
6313 		if (ire->ire_flags & RTF_MULTIRT) {
6314 			error = ip_multirt_apply_membership(optfn, ire, connp,
6315 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6316 			done = B_TRUE;
6317 		}
6318 		ire_refrele(ire);
6319 	}
6320 
6321 	if (!done) {
6322 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6323 		    fmode, &ipv6_all_zeros);
6324 	}
6325 	return (error);
6326 }
6327 
6328 /*
6329  * Set socket options for joining and leaving multicast groups
6330  * for specific sources.
6331  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6332  * The caller has already check that the option name is consistent with
6333  * the address family of the socket.
6334  */
6335 int
6336 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6337     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6338 {
6339 	int		*i1 = (int *)invalp;
6340 	int		error = 0;
6341 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6342 	struct ip_mreq_source *imreqp;
6343 	struct group_source_req *gsreqp;
6344 	in6_addr_t v6group, v6src;
6345 	uint32_t ifindex;
6346 	ipaddr_t ifaddr;
6347 	boolean_t mcast_opt = B_TRUE;
6348 	mcast_record_t fmode;
6349 	ire_t *ire;
6350 	boolean_t done = B_FALSE;
6351 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6352 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6353 
6354 	switch (name) {
6355 	case IP_BLOCK_SOURCE:
6356 		mcast_opt = B_FALSE;
6357 		/* FALLTHRU */
6358 	case MCAST_BLOCK_SOURCE:
6359 		fmode = MODE_IS_EXCLUDE;
6360 		optfn = ip_opt_add_group;
6361 		break;
6362 
6363 	case IP_UNBLOCK_SOURCE:
6364 		mcast_opt = B_FALSE;
6365 		/* FALLTHRU */
6366 	case MCAST_UNBLOCK_SOURCE:
6367 		fmode = MODE_IS_EXCLUDE;
6368 		optfn = ip_opt_delete_group;
6369 		break;
6370 
6371 	case IP_ADD_SOURCE_MEMBERSHIP:
6372 		mcast_opt = B_FALSE;
6373 		/* FALLTHRU */
6374 	case MCAST_JOIN_SOURCE_GROUP:
6375 		fmode = MODE_IS_INCLUDE;
6376 		optfn = ip_opt_add_group;
6377 		break;
6378 
6379 	case IP_DROP_SOURCE_MEMBERSHIP:
6380 		mcast_opt = B_FALSE;
6381 		/* FALLTHRU */
6382 	case MCAST_LEAVE_SOURCE_GROUP:
6383 		fmode = MODE_IS_INCLUDE;
6384 		optfn = ip_opt_delete_group;
6385 		break;
6386 	default:
6387 		ASSERT(0);
6388 	}
6389 
6390 	if (mcast_opt) {
6391 		gsreqp = (struct group_source_req *)i1;
6392 		ifindex = gsreqp->gsr_interface;
6393 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6394 			struct sockaddr_in *s;
6395 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6396 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6397 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6398 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6399 		} else {
6400 			struct sockaddr_in6 *s6;
6401 
6402 			if (!inet6)
6403 				return (EINVAL);	/* Not on INET socket */
6404 
6405 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6406 			v6group = s6->sin6_addr;
6407 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6408 			v6src = s6->sin6_addr;
6409 		}
6410 		ifaddr = INADDR_ANY;
6411 	} else {
6412 		imreqp = (struct ip_mreq_source *)i1;
6413 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6414 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6415 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6416 		ifindex = 0;
6417 	}
6418 
6419 	/*
6420 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6421 	 */
6422 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6423 		v6src = ipv6_all_zeros;
6424 
6425 	/*
6426 	 * In the multirouting case, we need to replicate
6427 	 * the request as noted in the mcast cases above.
6428 	 */
6429 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6430 		ipaddr_t group;
6431 
6432 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6433 
6434 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6435 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6436 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6437 	} else {
6438 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6439 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6440 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6441 	}
6442 	if (ire != NULL) {
6443 		if (ire->ire_flags & RTF_MULTIRT) {
6444 			error = ip_multirt_apply_membership(optfn, ire, connp,
6445 			    checkonly, &v6group, fmode, &v6src);
6446 			done = B_TRUE;
6447 		}
6448 		ire_refrele(ire);
6449 	}
6450 	if (!done) {
6451 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6452 		    fmode, &v6src);
6453 	}
6454 	return (error);
6455 }
6456 
6457 /*
6458  * Given a destination address and a pointer to where to put the information
6459  * this routine fills in the mtuinfo.
6460  * The socket must be connected.
6461  * For sctp conn_faddr is the primary address.
6462  */
6463 int
6464 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6465 {
6466 	uint32_t	pmtu = IP_MAXPACKET;
6467 	uint_t		scopeid;
6468 
6469 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6470 		return (-1);
6471 
6472 	/* In case we never sent or called ip_set_destination_v4/v6 */
6473 	if (ixa->ixa_ire != NULL)
6474 		pmtu = ip_get_pmtu(ixa);
6475 
6476 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6477 		scopeid = ixa->ixa_scopeid;
6478 	else
6479 		scopeid = 0;
6480 
6481 	bzero(mtuinfo, sizeof (*mtuinfo));
6482 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6483 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6484 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6485 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6486 	mtuinfo->ip6m_mtu = pmtu;
6487 
6488 	return (sizeof (struct ip6_mtuinfo));
6489 }
6490 
6491 /*
6492  * When the src multihoming is changed from weak to [strong, preferred]
6493  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6494  * and identify routes that were created by user-applications in the
6495  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6496  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6497  * is selected by finding an interface route for the gateway.
6498  */
6499 /* ARGSUSED */
6500 void
6501 ip_ire_rebind_walker(ire_t *ire, void *notused)
6502 {
6503 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6504 		return;
6505 	ire_rebind(ire);
6506 	ire_delete(ire);
6507 }
6508 
6509 /*
6510  * When the src multihoming is changed from  [strong, preferred] to weak,
6511  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6512  * set any entries that were created by user-applications in the unbound state
6513  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6514  */
6515 /* ARGSUSED */
6516 void
6517 ip_ire_unbind_walker(ire_t *ire, void *notused)
6518 {
6519 	ire_t *new_ire;
6520 
6521 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6522 		return;
6523 	if (ire->ire_ipversion == IPV6_VERSION) {
6524 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6525 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6526 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6527 	} else {
6528 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6529 		    (uchar_t *)&ire->ire_mask,
6530 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6531 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6532 	}
6533 	if (new_ire == NULL)
6534 		return;
6535 	new_ire->ire_unbound = B_TRUE;
6536 	/*
6537 	 * The bound ire must first be deleted so that we don't return
6538 	 * the existing one on the attempt to add the unbound new_ire.
6539 	 */
6540 	ire_delete(ire);
6541 	new_ire = ire_add(new_ire);
6542 	if (new_ire != NULL)
6543 		ire_refrele(new_ire);
6544 }
6545 
6546 /*
6547  * When the settings of ip*_strict_src_multihoming tunables are changed,
6548  * all cached routes need to be recomputed. This recomputation needs to be
6549  * done when going from weaker to stronger modes so that the cached ire
6550  * for the connection does not violate the current ip*_strict_src_multihoming
6551  * setting. It also needs to be done when going from stronger to weaker modes,
6552  * so that we fall back to matching on the longest-matching-route (as opposed
6553  * to a shorter match that may have been selected in the strong mode
6554  * to satisfy src_multihoming settings).
6555  *
6556  * The cached ixa_ire entires for all conn_t entries are marked as
6557  * "verify" so that they will be recomputed for the next packet.
6558  */
6559 void
6560 conn_ire_revalidate(conn_t *connp, void *arg)
6561 {
6562 	boolean_t isv6 = (boolean_t)arg;
6563 
6564 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6565 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6566 		return;
6567 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6568 }
6569 
6570 /*
6571  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6572  * When an ipf is passed here for the first time, if
6573  * we already have in-order fragments on the queue, we convert from the fast-
6574  * path reassembly scheme to the hard-case scheme.  From then on, additional
6575  * fragments are reassembled here.  We keep track of the start and end offsets
6576  * of each piece, and the number of holes in the chain.  When the hole count
6577  * goes to zero, we are done!
6578  *
6579  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6580  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6581  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6582  * after the call to ip_reassemble().
6583  */
6584 int
6585 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6586     size_t msg_len)
6587 {
6588 	uint_t	end;
6589 	mblk_t	*next_mp;
6590 	mblk_t	*mp1;
6591 	uint_t	offset;
6592 	boolean_t incr_dups = B_TRUE;
6593 	boolean_t offset_zero_seen = B_FALSE;
6594 	boolean_t pkt_boundary_checked = B_FALSE;
6595 
6596 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6597 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6598 
6599 	/* Add in byte count */
6600 	ipf->ipf_count += msg_len;
6601 	if (ipf->ipf_end) {
6602 		/*
6603 		 * We were part way through in-order reassembly, but now there
6604 		 * is a hole.  We walk through messages already queued, and
6605 		 * mark them for hard case reassembly.  We know that up till
6606 		 * now they were in order starting from offset zero.
6607 		 */
6608 		offset = 0;
6609 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6610 			IP_REASS_SET_START(mp1, offset);
6611 			if (offset == 0) {
6612 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6613 				offset = -ipf->ipf_nf_hdr_len;
6614 			}
6615 			offset += mp1->b_wptr - mp1->b_rptr;
6616 			IP_REASS_SET_END(mp1, offset);
6617 		}
6618 		/* One hole at the end. */
6619 		ipf->ipf_hole_cnt = 1;
6620 		/* Brand it as a hard case, forever. */
6621 		ipf->ipf_end = 0;
6622 	}
6623 	/* Walk through all the new pieces. */
6624 	do {
6625 		end = start + (mp->b_wptr - mp->b_rptr);
6626 		/*
6627 		 * If start is 0, decrease 'end' only for the first mblk of
6628 		 * the fragment. Otherwise 'end' can get wrong value in the
6629 		 * second pass of the loop if first mblk is exactly the
6630 		 * size of ipf_nf_hdr_len.
6631 		 */
6632 		if (start == 0 && !offset_zero_seen) {
6633 			/* First segment */
6634 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6635 			end -= ipf->ipf_nf_hdr_len;
6636 			offset_zero_seen = B_TRUE;
6637 		}
6638 		next_mp = mp->b_cont;
6639 		/*
6640 		 * We are checking to see if there is any interesing data
6641 		 * to process.  If there isn't and the mblk isn't the
6642 		 * one which carries the unfragmentable header then we
6643 		 * drop it.  It's possible to have just the unfragmentable
6644 		 * header come through without any data.  That needs to be
6645 		 * saved.
6646 		 *
6647 		 * If the assert at the top of this function holds then the
6648 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6649 		 * is infrequently traveled enough that the test is left in
6650 		 * to protect against future code changes which break that
6651 		 * invariant.
6652 		 */
6653 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6654 			/* Empty.  Blast it. */
6655 			IP_REASS_SET_START(mp, 0);
6656 			IP_REASS_SET_END(mp, 0);
6657 			/*
6658 			 * If the ipf points to the mblk we are about to free,
6659 			 * update ipf to point to the next mblk (or NULL
6660 			 * if none).
6661 			 */
6662 			if (ipf->ipf_mp->b_cont == mp)
6663 				ipf->ipf_mp->b_cont = next_mp;
6664 			freeb(mp);
6665 			continue;
6666 		}
6667 		mp->b_cont = NULL;
6668 		IP_REASS_SET_START(mp, start);
6669 		IP_REASS_SET_END(mp, end);
6670 		if (!ipf->ipf_tail_mp) {
6671 			ipf->ipf_tail_mp = mp;
6672 			ipf->ipf_mp->b_cont = mp;
6673 			if (start == 0 || !more) {
6674 				ipf->ipf_hole_cnt = 1;
6675 				/*
6676 				 * if the first fragment comes in more than one
6677 				 * mblk, this loop will be executed for each
6678 				 * mblk. Need to adjust hole count so exiting
6679 				 * this routine will leave hole count at 1.
6680 				 */
6681 				if (next_mp)
6682 					ipf->ipf_hole_cnt++;
6683 			} else
6684 				ipf->ipf_hole_cnt = 2;
6685 			continue;
6686 		} else if (ipf->ipf_last_frag_seen && !more &&
6687 		    !pkt_boundary_checked) {
6688 			/*
6689 			 * We check datagram boundary only if this fragment
6690 			 * claims to be the last fragment and we have seen a
6691 			 * last fragment in the past too. We do this only
6692 			 * once for a given fragment.
6693 			 *
6694 			 * start cannot be 0 here as fragments with start=0
6695 			 * and MF=0 gets handled as a complete packet. These
6696 			 * fragments should not reach here.
6697 			 */
6698 
6699 			if (start + msgdsize(mp) !=
6700 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6701 				/*
6702 				 * We have two fragments both of which claim
6703 				 * to be the last fragment but gives conflicting
6704 				 * information about the whole datagram size.
6705 				 * Something fishy is going on. Drop the
6706 				 * fragment and free up the reassembly list.
6707 				 */
6708 				return (IP_REASS_FAILED);
6709 			}
6710 
6711 			/*
6712 			 * We shouldn't come to this code block again for this
6713 			 * particular fragment.
6714 			 */
6715 			pkt_boundary_checked = B_TRUE;
6716 		}
6717 
6718 		/* New stuff at or beyond tail? */
6719 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6720 		if (start >= offset) {
6721 			if (ipf->ipf_last_frag_seen) {
6722 				/* current fragment is beyond last fragment */
6723 				return (IP_REASS_FAILED);
6724 			}
6725 			/* Link it on end. */
6726 			ipf->ipf_tail_mp->b_cont = mp;
6727 			ipf->ipf_tail_mp = mp;
6728 			if (more) {
6729 				if (start != offset)
6730 					ipf->ipf_hole_cnt++;
6731 			} else if (start == offset && next_mp == NULL)
6732 					ipf->ipf_hole_cnt--;
6733 			continue;
6734 		}
6735 		mp1 = ipf->ipf_mp->b_cont;
6736 		offset = IP_REASS_START(mp1);
6737 		/* New stuff at the front? */
6738 		if (start < offset) {
6739 			if (start == 0) {
6740 				if (end >= offset) {
6741 					/* Nailed the hole at the begining. */
6742 					ipf->ipf_hole_cnt--;
6743 				}
6744 			} else if (end < offset) {
6745 				/*
6746 				 * A hole, stuff, and a hole where there used
6747 				 * to be just a hole.
6748 				 */
6749 				ipf->ipf_hole_cnt++;
6750 			}
6751 			mp->b_cont = mp1;
6752 			/* Check for overlap. */
6753 			while (end > offset) {
6754 				if (end < IP_REASS_END(mp1)) {
6755 					mp->b_wptr -= end - offset;
6756 					IP_REASS_SET_END(mp, offset);
6757 					BUMP_MIB(ill->ill_ip_mib,
6758 					    ipIfStatsReasmPartDups);
6759 					break;
6760 				}
6761 				/* Did we cover another hole? */
6762 				if ((mp1->b_cont &&
6763 				    IP_REASS_END(mp1) !=
6764 				    IP_REASS_START(mp1->b_cont) &&
6765 				    end >= IP_REASS_START(mp1->b_cont)) ||
6766 				    (!ipf->ipf_last_frag_seen && !more)) {
6767 					ipf->ipf_hole_cnt--;
6768 				}
6769 				/* Clip out mp1. */
6770 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6771 					/*
6772 					 * After clipping out mp1, this guy
6773 					 * is now hanging off the end.
6774 					 */
6775 					ipf->ipf_tail_mp = mp;
6776 				}
6777 				IP_REASS_SET_START(mp1, 0);
6778 				IP_REASS_SET_END(mp1, 0);
6779 				/* Subtract byte count */
6780 				ipf->ipf_count -= mp1->b_datap->db_lim -
6781 				    mp1->b_datap->db_base;
6782 				freeb(mp1);
6783 				BUMP_MIB(ill->ill_ip_mib,
6784 				    ipIfStatsReasmPartDups);
6785 				mp1 = mp->b_cont;
6786 				if (!mp1)
6787 					break;
6788 				offset = IP_REASS_START(mp1);
6789 			}
6790 			ipf->ipf_mp->b_cont = mp;
6791 			continue;
6792 		}
6793 		/*
6794 		 * The new piece starts somewhere between the start of the head
6795 		 * and before the end of the tail.
6796 		 */
6797 		for (; mp1; mp1 = mp1->b_cont) {
6798 			offset = IP_REASS_END(mp1);
6799 			if (start < offset) {
6800 				if (end <= offset) {
6801 					/* Nothing new. */
6802 					IP_REASS_SET_START(mp, 0);
6803 					IP_REASS_SET_END(mp, 0);
6804 					/* Subtract byte count */
6805 					ipf->ipf_count -= mp->b_datap->db_lim -
6806 					    mp->b_datap->db_base;
6807 					if (incr_dups) {
6808 						ipf->ipf_num_dups++;
6809 						incr_dups = B_FALSE;
6810 					}
6811 					freeb(mp);
6812 					BUMP_MIB(ill->ill_ip_mib,
6813 					    ipIfStatsReasmDuplicates);
6814 					break;
6815 				}
6816 				/*
6817 				 * Trim redundant stuff off beginning of new
6818 				 * piece.
6819 				 */
6820 				IP_REASS_SET_START(mp, offset);
6821 				mp->b_rptr += offset - start;
6822 				BUMP_MIB(ill->ill_ip_mib,
6823 				    ipIfStatsReasmPartDups);
6824 				start = offset;
6825 				if (!mp1->b_cont) {
6826 					/*
6827 					 * After trimming, this guy is now
6828 					 * hanging off the end.
6829 					 */
6830 					mp1->b_cont = mp;
6831 					ipf->ipf_tail_mp = mp;
6832 					if (!more) {
6833 						ipf->ipf_hole_cnt--;
6834 					}
6835 					break;
6836 				}
6837 			}
6838 			if (start >= IP_REASS_START(mp1->b_cont))
6839 				continue;
6840 			/* Fill a hole */
6841 			if (start > offset)
6842 				ipf->ipf_hole_cnt++;
6843 			mp->b_cont = mp1->b_cont;
6844 			mp1->b_cont = mp;
6845 			mp1 = mp->b_cont;
6846 			offset = IP_REASS_START(mp1);
6847 			if (end >= offset) {
6848 				ipf->ipf_hole_cnt--;
6849 				/* Check for overlap. */
6850 				while (end > offset) {
6851 					if (end < IP_REASS_END(mp1)) {
6852 						mp->b_wptr -= end - offset;
6853 						IP_REASS_SET_END(mp, offset);
6854 						/*
6855 						 * TODO we might bump
6856 						 * this up twice if there is
6857 						 * overlap at both ends.
6858 						 */
6859 						BUMP_MIB(ill->ill_ip_mib,
6860 						    ipIfStatsReasmPartDups);
6861 						break;
6862 					}
6863 					/* Did we cover another hole? */
6864 					if ((mp1->b_cont &&
6865 					    IP_REASS_END(mp1)
6866 					    != IP_REASS_START(mp1->b_cont) &&
6867 					    end >=
6868 					    IP_REASS_START(mp1->b_cont)) ||
6869 					    (!ipf->ipf_last_frag_seen &&
6870 					    !more)) {
6871 						ipf->ipf_hole_cnt--;
6872 					}
6873 					/* Clip out mp1. */
6874 					if ((mp->b_cont = mp1->b_cont) ==
6875 					    NULL) {
6876 						/*
6877 						 * After clipping out mp1,
6878 						 * this guy is now hanging
6879 						 * off the end.
6880 						 */
6881 						ipf->ipf_tail_mp = mp;
6882 					}
6883 					IP_REASS_SET_START(mp1, 0);
6884 					IP_REASS_SET_END(mp1, 0);
6885 					/* Subtract byte count */
6886 					ipf->ipf_count -=
6887 					    mp1->b_datap->db_lim -
6888 					    mp1->b_datap->db_base;
6889 					freeb(mp1);
6890 					BUMP_MIB(ill->ill_ip_mib,
6891 					    ipIfStatsReasmPartDups);
6892 					mp1 = mp->b_cont;
6893 					if (!mp1)
6894 						break;
6895 					offset = IP_REASS_START(mp1);
6896 				}
6897 			}
6898 			break;
6899 		}
6900 	} while (start = end, mp = next_mp);
6901 
6902 	/* Fragment just processed could be the last one. Remember this fact */
6903 	if (!more)
6904 		ipf->ipf_last_frag_seen = B_TRUE;
6905 
6906 	/* Still got holes? */
6907 	if (ipf->ipf_hole_cnt)
6908 		return (IP_REASS_PARTIAL);
6909 	/* Clean up overloaded fields to avoid upstream disasters. */
6910 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6911 		IP_REASS_SET_START(mp1, 0);
6912 		IP_REASS_SET_END(mp1, 0);
6913 	}
6914 	return (IP_REASS_COMPLETE);
6915 }
6916 
6917 /*
6918  * Fragmentation reassembly.  Each ILL has a hash table for
6919  * queuing packets undergoing reassembly for all IPIFs
6920  * associated with the ILL.  The hash is based on the packet
6921  * IP ident field.  The ILL frag hash table was allocated
6922  * as a timer block at the time the ILL was created.  Whenever
6923  * there is anything on the reassembly queue, the timer will
6924  * be running.  Returns the reassembled packet if reassembly completes.
6925  */
6926 mblk_t *
6927 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
6928 {
6929 	uint32_t	frag_offset_flags;
6930 	mblk_t		*t_mp;
6931 	ipaddr_t	dst;
6932 	uint8_t		proto = ipha->ipha_protocol;
6933 	uint32_t	sum_val;
6934 	uint16_t	sum_flags;
6935 	ipf_t		*ipf;
6936 	ipf_t		**ipfp;
6937 	ipfb_t		*ipfb;
6938 	uint16_t	ident;
6939 	uint32_t	offset;
6940 	ipaddr_t	src;
6941 	uint_t		hdr_length;
6942 	uint32_t	end;
6943 	mblk_t		*mp1;
6944 	mblk_t		*tail_mp;
6945 	size_t		count;
6946 	size_t		msg_len;
6947 	uint8_t		ecn_info = 0;
6948 	uint32_t	packet_size;
6949 	boolean_t	pruned = B_FALSE;
6950 	ill_t		*ill = ira->ira_ill;
6951 	ip_stack_t	*ipst = ill->ill_ipst;
6952 
6953 	/*
6954 	 * Drop the fragmented as early as possible, if
6955 	 * we don't have resource(s) to re-assemble.
6956 	 */
6957 	if (ipst->ips_ip_reass_queue_bytes == 0) {
6958 		freemsg(mp);
6959 		return (NULL);
6960 	}
6961 
6962 	/* Check for fragmentation offset; return if there's none */
6963 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
6964 	    (IPH_MF | IPH_OFFSET)) == 0)
6965 		return (mp);
6966 
6967 	/*
6968 	 * We utilize hardware computed checksum info only for UDP since
6969 	 * IP fragmentation is a normal occurrence for the protocol.  In
6970 	 * addition, checksum offload support for IP fragments carrying
6971 	 * UDP payload is commonly implemented across network adapters.
6972 	 */
6973 	ASSERT(ira->ira_rill != NULL);
6974 	if (proto == IPPROTO_UDP && dohwcksum &&
6975 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
6976 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
6977 		mblk_t *mp1 = mp->b_cont;
6978 		int32_t len;
6979 
6980 		/* Record checksum information from the packet */
6981 		sum_val = (uint32_t)DB_CKSUM16(mp);
6982 		sum_flags = DB_CKSUMFLAGS(mp);
6983 
6984 		/* IP payload offset from beginning of mblk */
6985 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
6986 
6987 		if ((sum_flags & HCK_PARTIALCKSUM) &&
6988 		    (mp1 == NULL || mp1->b_cont == NULL) &&
6989 		    offset >= DB_CKSUMSTART(mp) &&
6990 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
6991 			uint32_t adj;
6992 			/*
6993 			 * Partial checksum has been calculated by hardware
6994 			 * and attached to the packet; in addition, any
6995 			 * prepended extraneous data is even byte aligned.
6996 			 * If any such data exists, we adjust the checksum;
6997 			 * this would also handle any postpended data.
6998 			 */
6999 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7000 			    mp, mp1, len, adj);
7001 
7002 			/* One's complement subtract extraneous checksum */
7003 			if (adj >= sum_val)
7004 				sum_val = ~(adj - sum_val) & 0xFFFF;
7005 			else
7006 				sum_val -= adj;
7007 		}
7008 	} else {
7009 		sum_val = 0;
7010 		sum_flags = 0;
7011 	}
7012 
7013 	/* Clear hardware checksumming flag */
7014 	DB_CKSUMFLAGS(mp) = 0;
7015 
7016 	ident = ipha->ipha_ident;
7017 	offset = (frag_offset_flags << 3) & 0xFFFF;
7018 	src = ipha->ipha_src;
7019 	dst = ipha->ipha_dst;
7020 	hdr_length = IPH_HDR_LENGTH(ipha);
7021 	end = ntohs(ipha->ipha_length) - hdr_length;
7022 
7023 	/* If end == 0 then we have a packet with no data, so just free it */
7024 	if (end == 0) {
7025 		freemsg(mp);
7026 		return (NULL);
7027 	}
7028 
7029 	/* Record the ECN field info. */
7030 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7031 	if (offset != 0) {
7032 		/*
7033 		 * If this isn't the first piece, strip the header, and
7034 		 * add the offset to the end value.
7035 		 */
7036 		mp->b_rptr += hdr_length;
7037 		end += offset;
7038 	}
7039 
7040 	/* Handle vnic loopback of fragments */
7041 	if (mp->b_datap->db_ref > 2)
7042 		msg_len = 0;
7043 	else
7044 		msg_len = MBLKSIZE(mp);
7045 
7046 	tail_mp = mp;
7047 	while (tail_mp->b_cont != NULL) {
7048 		tail_mp = tail_mp->b_cont;
7049 		if (tail_mp->b_datap->db_ref <= 2)
7050 			msg_len += MBLKSIZE(tail_mp);
7051 	}
7052 
7053 	/* If the reassembly list for this ILL will get too big, prune it */
7054 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7055 	    ipst->ips_ip_reass_queue_bytes) {
7056 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7057 		    uint_t, ill->ill_frag_count,
7058 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7059 		ill_frag_prune(ill,
7060 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7061 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7062 		pruned = B_TRUE;
7063 	}
7064 
7065 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7066 	mutex_enter(&ipfb->ipfb_lock);
7067 
7068 	ipfp = &ipfb->ipfb_ipf;
7069 	/* Try to find an existing fragment queue for this packet. */
7070 	for (;;) {
7071 		ipf = ipfp[0];
7072 		if (ipf != NULL) {
7073 			/*
7074 			 * It has to match on ident and src/dst address.
7075 			 */
7076 			if (ipf->ipf_ident == ident &&
7077 			    ipf->ipf_src == src &&
7078 			    ipf->ipf_dst == dst &&
7079 			    ipf->ipf_protocol == proto) {
7080 				/*
7081 				 * If we have received too many
7082 				 * duplicate fragments for this packet
7083 				 * free it.
7084 				 */
7085 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7086 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7087 					freemsg(mp);
7088 					mutex_exit(&ipfb->ipfb_lock);
7089 					return (NULL);
7090 				}
7091 				/* Found it. */
7092 				break;
7093 			}
7094 			ipfp = &ipf->ipf_hash_next;
7095 			continue;
7096 		}
7097 
7098 		/*
7099 		 * If we pruned the list, do we want to store this new
7100 		 * fragment?. We apply an optimization here based on the
7101 		 * fact that most fragments will be received in order.
7102 		 * So if the offset of this incoming fragment is zero,
7103 		 * it is the first fragment of a new packet. We will
7104 		 * keep it.  Otherwise drop the fragment, as we have
7105 		 * probably pruned the packet already (since the
7106 		 * packet cannot be found).
7107 		 */
7108 		if (pruned && offset != 0) {
7109 			mutex_exit(&ipfb->ipfb_lock);
7110 			freemsg(mp);
7111 			return (NULL);
7112 		}
7113 
7114 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7115 			/*
7116 			 * Too many fragmented packets in this hash
7117 			 * bucket. Free the oldest.
7118 			 */
7119 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7120 		}
7121 
7122 		/* New guy.  Allocate a frag message. */
7123 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7124 		if (mp1 == NULL) {
7125 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7126 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7127 			freemsg(mp);
7128 reass_done:
7129 			mutex_exit(&ipfb->ipfb_lock);
7130 			return (NULL);
7131 		}
7132 
7133 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7134 		mp1->b_cont = mp;
7135 
7136 		/* Initialize the fragment header. */
7137 		ipf = (ipf_t *)mp1->b_rptr;
7138 		ipf->ipf_mp = mp1;
7139 		ipf->ipf_ptphn = ipfp;
7140 		ipfp[0] = ipf;
7141 		ipf->ipf_hash_next = NULL;
7142 		ipf->ipf_ident = ident;
7143 		ipf->ipf_protocol = proto;
7144 		ipf->ipf_src = src;
7145 		ipf->ipf_dst = dst;
7146 		ipf->ipf_nf_hdr_len = 0;
7147 		/* Record reassembly start time. */
7148 		ipf->ipf_timestamp = gethrestime_sec();
7149 		/* Record ipf generation and account for frag header */
7150 		ipf->ipf_gen = ill->ill_ipf_gen++;
7151 		ipf->ipf_count = MBLKSIZE(mp1);
7152 		ipf->ipf_last_frag_seen = B_FALSE;
7153 		ipf->ipf_ecn = ecn_info;
7154 		ipf->ipf_num_dups = 0;
7155 		ipfb->ipfb_frag_pkts++;
7156 		ipf->ipf_checksum = 0;
7157 		ipf->ipf_checksum_flags = 0;
7158 
7159 		/* Store checksum value in fragment header */
7160 		if (sum_flags != 0) {
7161 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7162 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7163 			ipf->ipf_checksum = sum_val;
7164 			ipf->ipf_checksum_flags = sum_flags;
7165 		}
7166 
7167 		/*
7168 		 * We handle reassembly two ways.  In the easy case,
7169 		 * where all the fragments show up in order, we do
7170 		 * minimal bookkeeping, and just clip new pieces on
7171 		 * the end.  If we ever see a hole, then we go off
7172 		 * to ip_reassemble which has to mark the pieces and
7173 		 * keep track of the number of holes, etc.  Obviously,
7174 		 * the point of having both mechanisms is so we can
7175 		 * handle the easy case as efficiently as possible.
7176 		 */
7177 		if (offset == 0) {
7178 			/* Easy case, in-order reassembly so far. */
7179 			ipf->ipf_count += msg_len;
7180 			ipf->ipf_tail_mp = tail_mp;
7181 			/*
7182 			 * Keep track of next expected offset in
7183 			 * ipf_end.
7184 			 */
7185 			ipf->ipf_end = end;
7186 			ipf->ipf_nf_hdr_len = hdr_length;
7187 		} else {
7188 			/* Hard case, hole at the beginning. */
7189 			ipf->ipf_tail_mp = NULL;
7190 			/*
7191 			 * ipf_end == 0 means that we have given up
7192 			 * on easy reassembly.
7193 			 */
7194 			ipf->ipf_end = 0;
7195 
7196 			/* Forget checksum offload from now on */
7197 			ipf->ipf_checksum_flags = 0;
7198 
7199 			/*
7200 			 * ipf_hole_cnt is set by ip_reassemble.
7201 			 * ipf_count is updated by ip_reassemble.
7202 			 * No need to check for return value here
7203 			 * as we don't expect reassembly to complete
7204 			 * or fail for the first fragment itself.
7205 			 */
7206 			(void) ip_reassemble(mp, ipf,
7207 			    (frag_offset_flags & IPH_OFFSET) << 3,
7208 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7209 		}
7210 		/* Update per ipfb and ill byte counts */
7211 		ipfb->ipfb_count += ipf->ipf_count;
7212 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7213 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7214 		/* If the frag timer wasn't already going, start it. */
7215 		mutex_enter(&ill->ill_lock);
7216 		ill_frag_timer_start(ill);
7217 		mutex_exit(&ill->ill_lock);
7218 		goto reass_done;
7219 	}
7220 
7221 	/*
7222 	 * If the packet's flag has changed (it could be coming up
7223 	 * from an interface different than the previous, therefore
7224 	 * possibly different checksum capability), then forget about
7225 	 * any stored checksum states.  Otherwise add the value to
7226 	 * the existing one stored in the fragment header.
7227 	 */
7228 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7229 		sum_val += ipf->ipf_checksum;
7230 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7231 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7232 		ipf->ipf_checksum = sum_val;
7233 	} else if (ipf->ipf_checksum_flags != 0) {
7234 		/* Forget checksum offload from now on */
7235 		ipf->ipf_checksum_flags = 0;
7236 	}
7237 
7238 	/*
7239 	 * We have a new piece of a datagram which is already being
7240 	 * reassembled.  Update the ECN info if all IP fragments
7241 	 * are ECN capable.  If there is one which is not, clear
7242 	 * all the info.  If there is at least one which has CE
7243 	 * code point, IP needs to report that up to transport.
7244 	 */
7245 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7246 		if (ecn_info == IPH_ECN_CE)
7247 			ipf->ipf_ecn = IPH_ECN_CE;
7248 	} else {
7249 		ipf->ipf_ecn = IPH_ECN_NECT;
7250 	}
7251 	if (offset && ipf->ipf_end == offset) {
7252 		/* The new fragment fits at the end */
7253 		ipf->ipf_tail_mp->b_cont = mp;
7254 		/* Update the byte count */
7255 		ipf->ipf_count += msg_len;
7256 		/* Update per ipfb and ill byte counts */
7257 		ipfb->ipfb_count += msg_len;
7258 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7259 		atomic_add_32(&ill->ill_frag_count, msg_len);
7260 		if (frag_offset_flags & IPH_MF) {
7261 			/* More to come. */
7262 			ipf->ipf_end = end;
7263 			ipf->ipf_tail_mp = tail_mp;
7264 			goto reass_done;
7265 		}
7266 	} else {
7267 		/* Go do the hard cases. */
7268 		int ret;
7269 
7270 		if (offset == 0)
7271 			ipf->ipf_nf_hdr_len = hdr_length;
7272 
7273 		/* Save current byte count */
7274 		count = ipf->ipf_count;
7275 		ret = ip_reassemble(mp, ipf,
7276 		    (frag_offset_flags & IPH_OFFSET) << 3,
7277 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7278 		/* Count of bytes added and subtracted (freeb()ed) */
7279 		count = ipf->ipf_count - count;
7280 		if (count) {
7281 			/* Update per ipfb and ill byte counts */
7282 			ipfb->ipfb_count += count;
7283 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7284 			atomic_add_32(&ill->ill_frag_count, count);
7285 		}
7286 		if (ret == IP_REASS_PARTIAL) {
7287 			goto reass_done;
7288 		} else if (ret == IP_REASS_FAILED) {
7289 			/* Reassembly failed. Free up all resources */
7290 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7291 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7292 				IP_REASS_SET_START(t_mp, 0);
7293 				IP_REASS_SET_END(t_mp, 0);
7294 			}
7295 			freemsg(mp);
7296 			goto reass_done;
7297 		}
7298 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7299 	}
7300 	/*
7301 	 * We have completed reassembly.  Unhook the frag header from
7302 	 * the reassembly list.
7303 	 *
7304 	 * Before we free the frag header, record the ECN info
7305 	 * to report back to the transport.
7306 	 */
7307 	ecn_info = ipf->ipf_ecn;
7308 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7309 	ipfp = ipf->ipf_ptphn;
7310 
7311 	/* We need to supply these to caller */
7312 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7313 		sum_val = ipf->ipf_checksum;
7314 	else
7315 		sum_val = 0;
7316 
7317 	mp1 = ipf->ipf_mp;
7318 	count = ipf->ipf_count;
7319 	ipf = ipf->ipf_hash_next;
7320 	if (ipf != NULL)
7321 		ipf->ipf_ptphn = ipfp;
7322 	ipfp[0] = ipf;
7323 	atomic_add_32(&ill->ill_frag_count, -count);
7324 	ASSERT(ipfb->ipfb_count >= count);
7325 	ipfb->ipfb_count -= count;
7326 	ipfb->ipfb_frag_pkts--;
7327 	mutex_exit(&ipfb->ipfb_lock);
7328 	/* Ditch the frag header. */
7329 	mp = mp1->b_cont;
7330 
7331 	freeb(mp1);
7332 
7333 	/* Restore original IP length in header. */
7334 	packet_size = (uint32_t)msgdsize(mp);
7335 	if (packet_size > IP_MAXPACKET) {
7336 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7337 		ip_drop_input("Reassembled packet too large", mp, ill);
7338 		freemsg(mp);
7339 		return (NULL);
7340 	}
7341 
7342 	if (DB_REF(mp) > 1) {
7343 		mblk_t *mp2 = copymsg(mp);
7344 
7345 		if (mp2 == NULL) {
7346 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7347 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7348 			freemsg(mp);
7349 			return (NULL);
7350 		}
7351 		freemsg(mp);
7352 		mp = mp2;
7353 	}
7354 	ipha = (ipha_t *)mp->b_rptr;
7355 
7356 	ipha->ipha_length = htons((uint16_t)packet_size);
7357 	/* We're now complete, zip the frag state */
7358 	ipha->ipha_fragment_offset_and_flags = 0;
7359 	/* Record the ECN info. */
7360 	ipha->ipha_type_of_service &= 0xFC;
7361 	ipha->ipha_type_of_service |= ecn_info;
7362 
7363 	/* Update the receive attributes */
7364 	ira->ira_pktlen = packet_size;
7365 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7366 
7367 	/* Reassembly is successful; set checksum information in packet */
7368 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7369 	DB_CKSUMFLAGS(mp) = sum_flags;
7370 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7371 
7372 	return (mp);
7373 }
7374 
7375 /*
7376  * Pullup function that should be used for IP input in order to
7377  * ensure we do not loose the L2 source address; we need the l2 source
7378  * address for IP_RECVSLLA and for ndp_input.
7379  *
7380  * We return either NULL or b_rptr.
7381  */
7382 void *
7383 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7384 {
7385 	ill_t		*ill = ira->ira_ill;
7386 
7387 	if (ip_rput_pullups++ == 0) {
7388 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7389 		    "ip_pullup: %s forced us to "
7390 		    " pullup pkt, hdr len %ld, hdr addr %p",
7391 		    ill->ill_name, len, (void *)mp->b_rptr);
7392 	}
7393 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7394 		ip_setl2src(mp, ira, ira->ira_rill);
7395 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7396 	if (!pullupmsg(mp, len))
7397 		return (NULL);
7398 	else
7399 		return (mp->b_rptr);
7400 }
7401 
7402 /*
7403  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7404  * When called from the ULP ira_rill will be NULL hence the caller has to
7405  * pass in the ill.
7406  */
7407 /* ARGSUSED */
7408 void
7409 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7410 {
7411 	const uchar_t *addr;
7412 	int alen;
7413 
7414 	if (ira->ira_flags & IRAF_L2SRC_SET)
7415 		return;
7416 
7417 	ASSERT(ill != NULL);
7418 	alen = ill->ill_phys_addr_length;
7419 	ASSERT(alen <= sizeof (ira->ira_l2src));
7420 	if (ira->ira_mhip != NULL &&
7421 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7422 		bcopy(addr, ira->ira_l2src, alen);
7423 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7424 	    (addr = ill->ill_phys_addr) != NULL) {
7425 		bcopy(addr, ira->ira_l2src, alen);
7426 	} else {
7427 		bzero(ira->ira_l2src, alen);
7428 	}
7429 	ira->ira_flags |= IRAF_L2SRC_SET;
7430 }
7431 
7432 /*
7433  * check ip header length and align it.
7434  */
7435 mblk_t *
7436 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7437 {
7438 	ill_t	*ill = ira->ira_ill;
7439 	ssize_t len;
7440 
7441 	len = MBLKL(mp);
7442 
7443 	if (!OK_32PTR(mp->b_rptr))
7444 		IP_STAT(ill->ill_ipst, ip_notaligned);
7445 	else
7446 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7447 
7448 	/* Guard against bogus device drivers */
7449 	if (len < 0) {
7450 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7451 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7452 		freemsg(mp);
7453 		return (NULL);
7454 	}
7455 
7456 	if (len == 0) {
7457 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7458 		mblk_t *mp1 = mp->b_cont;
7459 
7460 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7461 			ip_setl2src(mp, ira, ira->ira_rill);
7462 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7463 
7464 		freeb(mp);
7465 		mp = mp1;
7466 		if (mp == NULL)
7467 			return (NULL);
7468 
7469 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7470 			return (mp);
7471 	}
7472 	if (ip_pullup(mp, min_size, ira) == NULL) {
7473 		if (msgdsize(mp) < min_size) {
7474 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7475 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7476 		} else {
7477 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7478 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7479 		}
7480 		freemsg(mp);
7481 		return (NULL);
7482 	}
7483 	return (mp);
7484 }
7485 
7486 /*
7487  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7488  */
7489 mblk_t *
7490 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7491     uint_t min_size, ip_recv_attr_t *ira)
7492 {
7493 	ill_t	*ill = ira->ira_ill;
7494 
7495 	/*
7496 	 * Make sure we have data length consistent
7497 	 * with the IP header.
7498 	 */
7499 	if (mp->b_cont == NULL) {
7500 		/* pkt_len is based on ipha_len, not the mblk length */
7501 		if (pkt_len < min_size) {
7502 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7503 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7504 			freemsg(mp);
7505 			return (NULL);
7506 		}
7507 		if (len < 0) {
7508 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7509 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7510 			freemsg(mp);
7511 			return (NULL);
7512 		}
7513 		/* Drop any pad */
7514 		mp->b_wptr = rptr + pkt_len;
7515 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7516 		ASSERT(pkt_len >= min_size);
7517 		if (pkt_len < min_size) {
7518 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7519 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7520 			freemsg(mp);
7521 			return (NULL);
7522 		}
7523 		if (len < 0) {
7524 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7525 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7526 			freemsg(mp);
7527 			return (NULL);
7528 		}
7529 		/* Drop any pad */
7530 		(void) adjmsg(mp, -len);
7531 		/*
7532 		 * adjmsg may have freed an mblk from the chain, hence
7533 		 * invalidate any hw checksum here. This will force IP to
7534 		 * calculate the checksum in sw, but only for this packet.
7535 		 */
7536 		DB_CKSUMFLAGS(mp) = 0;
7537 		IP_STAT(ill->ill_ipst, ip_multimblk);
7538 	}
7539 	return (mp);
7540 }
7541 
7542 /*
7543  * Check that the IPv4 opt_len is consistent with the packet and pullup
7544  * the options.
7545  */
7546 mblk_t *
7547 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7548     ip_recv_attr_t *ira)
7549 {
7550 	ill_t	*ill = ira->ira_ill;
7551 	ssize_t len;
7552 
7553 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7554 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7555 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7556 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7557 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7558 		freemsg(mp);
7559 		return (NULL);
7560 	}
7561 
7562 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7563 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7564 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7565 		freemsg(mp);
7566 		return (NULL);
7567 	}
7568 	/*
7569 	 * Recompute complete header length and make sure we
7570 	 * have access to all of it.
7571 	 */
7572 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7573 	if (len > (mp->b_wptr - mp->b_rptr)) {
7574 		if (len > pkt_len) {
7575 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7576 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7577 			freemsg(mp);
7578 			return (NULL);
7579 		}
7580 		if (ip_pullup(mp, len, ira) == NULL) {
7581 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7582 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7583 			freemsg(mp);
7584 			return (NULL);
7585 		}
7586 	}
7587 	return (mp);
7588 }
7589 
7590 /*
7591  * Returns a new ire, or the same ire, or NULL.
7592  * If a different IRE is returned, then it is held; the caller
7593  * needs to release it.
7594  * In no case is there any hold/release on the ire argument.
7595  */
7596 ire_t *
7597 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7598 {
7599 	ire_t		*new_ire;
7600 	ill_t		*ire_ill;
7601 	uint_t		ifindex;
7602 	ip_stack_t	*ipst = ill->ill_ipst;
7603 	boolean_t	strict_check = B_FALSE;
7604 
7605 	/*
7606 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7607 	 * issue (e.g. packet received on an underlying interface matched an
7608 	 * IRE_LOCAL on its associated group interface).
7609 	 */
7610 	ASSERT(ire->ire_ill != NULL);
7611 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7612 		return (ire);
7613 
7614 	/*
7615 	 * Do another ire lookup here, using the ingress ill, to see if the
7616 	 * interface is in a usesrc group.
7617 	 * As long as the ills belong to the same group, we don't consider
7618 	 * them to be arriving on the wrong interface. Thus, if the switch
7619 	 * is doing inbound load spreading, we won't drop packets when the
7620 	 * ip*_strict_dst_multihoming switch is on.
7621 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7622 	 * where the local address may not be unique. In this case we were
7623 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7624 	 * actually returned. The new lookup, which is more specific, should
7625 	 * only find the IRE_LOCAL associated with the ingress ill if one
7626 	 * exists.
7627 	 */
7628 	if (ire->ire_ipversion == IPV4_VERSION) {
7629 		if (ipst->ips_ip_strict_dst_multihoming)
7630 			strict_check = B_TRUE;
7631 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7632 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7633 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7634 	} else {
7635 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7636 		if (ipst->ips_ipv6_strict_dst_multihoming)
7637 			strict_check = B_TRUE;
7638 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7639 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7640 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7641 	}
7642 	/*
7643 	 * If the same ire that was returned in ip_input() is found then this
7644 	 * is an indication that usesrc groups are in use. The packet
7645 	 * arrived on a different ill in the group than the one associated with
7646 	 * the destination address.  If a different ire was found then the same
7647 	 * IP address must be hosted on multiple ills. This is possible with
7648 	 * unnumbered point2point interfaces. We switch to use this new ire in
7649 	 * order to have accurate interface statistics.
7650 	 */
7651 	if (new_ire != NULL) {
7652 		/* Note: held in one case but not the other? Caller handles */
7653 		if (new_ire != ire)
7654 			return (new_ire);
7655 		/* Unchanged */
7656 		ire_refrele(new_ire);
7657 		return (ire);
7658 	}
7659 
7660 	/*
7661 	 * Chase pointers once and store locally.
7662 	 */
7663 	ASSERT(ire->ire_ill != NULL);
7664 	ire_ill = ire->ire_ill;
7665 	ifindex = ill->ill_usesrc_ifindex;
7666 
7667 	/*
7668 	 * Check if it's a legal address on the 'usesrc' interface.
7669 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7670 	 * can just check phyint_ifindex.
7671 	 */
7672 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7673 		return (ire);
7674 	}
7675 
7676 	/*
7677 	 * If the ip*_strict_dst_multihoming switch is on then we can
7678 	 * only accept this packet if the interface is marked as routing.
7679 	 */
7680 	if (!(strict_check))
7681 		return (ire);
7682 
7683 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7684 		return (ire);
7685 	}
7686 	return (NULL);
7687 }
7688 
7689 /*
7690  * This function is used to construct a mac_header_info_s from a
7691  * DL_UNITDATA_IND message.
7692  * The address fields in the mhi structure points into the message,
7693  * thus the caller can't use those fields after freeing the message.
7694  *
7695  * We determine whether the packet received is a non-unicast packet
7696  * and in doing so, determine whether or not it is broadcast vs multicast.
7697  * For it to be a broadcast packet, we must have the appropriate mblk_t
7698  * hanging off the ill_t.  If this is either not present or doesn't match
7699  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7700  * to be multicast.  Thus NICs that have no broadcast address (or no
7701  * capability for one, such as point to point links) cannot return as
7702  * the packet being broadcast.
7703  */
7704 void
7705 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7706 {
7707 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7708 	mblk_t *bmp;
7709 	uint_t extra_offset;
7710 
7711 	bzero(mhip, sizeof (struct mac_header_info_s));
7712 
7713 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7714 
7715 	if (ill->ill_sap_length < 0)
7716 		extra_offset = 0;
7717 	else
7718 		extra_offset = ill->ill_sap_length;
7719 
7720 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7721 	    extra_offset;
7722 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7723 	    extra_offset;
7724 
7725 	if (!ind->dl_group_address)
7726 		return;
7727 
7728 	/* Multicast or broadcast */
7729 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7730 
7731 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7732 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7733 	    (bmp = ill->ill_bcast_mp) != NULL) {
7734 		dl_unitdata_req_t *dlur;
7735 		uint8_t *bphys_addr;
7736 
7737 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7738 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7739 		    extra_offset;
7740 
7741 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7742 		    ind->dl_dest_addr_length) == 0)
7743 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7744 	}
7745 }
7746 
7747 /*
7748  * This function is used to construct a mac_header_info_s from a
7749  * M_DATA fastpath message from a DLPI driver.
7750  * The address fields in the mhi structure points into the message,
7751  * thus the caller can't use those fields after freeing the message.
7752  *
7753  * We determine whether the packet received is a non-unicast packet
7754  * and in doing so, determine whether or not it is broadcast vs multicast.
7755  * For it to be a broadcast packet, we must have the appropriate mblk_t
7756  * hanging off the ill_t.  If this is either not present or doesn't match
7757  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7758  * to be multicast.  Thus NICs that have no broadcast address (or no
7759  * capability for one, such as point to point links) cannot return as
7760  * the packet being broadcast.
7761  */
7762 void
7763 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7764 {
7765 	mblk_t *bmp;
7766 	struct ether_header *pether;
7767 
7768 	bzero(mhip, sizeof (struct mac_header_info_s));
7769 
7770 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7771 
7772 	pether = (struct ether_header *)((char *)mp->b_rptr
7773 	    - sizeof (struct ether_header));
7774 
7775 	/*
7776 	 * Make sure the interface is an ethernet type, since we don't
7777 	 * know the header format for anything but Ethernet. Also make
7778 	 * sure we are pointing correctly above db_base.
7779 	 */
7780 	if (ill->ill_type != IFT_ETHER)
7781 		return;
7782 
7783 retry:
7784 	if ((uchar_t *)pether < mp->b_datap->db_base)
7785 		return;
7786 
7787 	/* Is there a VLAN tag? */
7788 	if (ill->ill_isv6) {
7789 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7790 			pether = (struct ether_header *)((char *)pether - 4);
7791 			goto retry;
7792 		}
7793 	} else {
7794 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7795 			pether = (struct ether_header *)((char *)pether - 4);
7796 			goto retry;
7797 		}
7798 	}
7799 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7800 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7801 
7802 	if (!(mhip->mhi_daddr[0] & 0x01))
7803 		return;
7804 
7805 	/* Multicast or broadcast */
7806 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7807 
7808 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7809 		dl_unitdata_req_t *dlur;
7810 		uint8_t *bphys_addr;
7811 		uint_t	addrlen;
7812 
7813 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7814 		addrlen = dlur->dl_dest_addr_length;
7815 		if (ill->ill_sap_length < 0) {
7816 			bphys_addr = (uchar_t *)dlur +
7817 			    dlur->dl_dest_addr_offset;
7818 			addrlen += ill->ill_sap_length;
7819 		} else {
7820 			bphys_addr = (uchar_t *)dlur +
7821 			    dlur->dl_dest_addr_offset +
7822 			    ill->ill_sap_length;
7823 			addrlen -= ill->ill_sap_length;
7824 		}
7825 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7826 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7827 	}
7828 }
7829 
7830 /*
7831  * Handle anything but M_DATA messages
7832  * We see the DL_UNITDATA_IND which are part
7833  * of the data path, and also the other messages from the driver.
7834  */
7835 void
7836 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7837 {
7838 	mblk_t		*first_mp;
7839 	struct iocblk   *iocp;
7840 	struct mac_header_info_s mhi;
7841 
7842 	switch (DB_TYPE(mp)) {
7843 	case M_PROTO:
7844 	case M_PCPROTO: {
7845 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7846 		    DL_UNITDATA_IND) {
7847 			/* Go handle anything other than data elsewhere. */
7848 			ip_rput_dlpi(ill, mp);
7849 			return;
7850 		}
7851 
7852 		first_mp = mp;
7853 		mp = first_mp->b_cont;
7854 		first_mp->b_cont = NULL;
7855 
7856 		if (mp == NULL) {
7857 			freeb(first_mp);
7858 			return;
7859 		}
7860 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7861 		if (ill->ill_isv6)
7862 			ip_input_v6(ill, NULL, mp, &mhi);
7863 		else
7864 			ip_input(ill, NULL, mp, &mhi);
7865 
7866 		/* Ditch the DLPI header. */
7867 		freeb(first_mp);
7868 		return;
7869 	}
7870 	case M_IOCACK:
7871 		iocp = (struct iocblk *)mp->b_rptr;
7872 		switch (iocp->ioc_cmd) {
7873 		case DL_IOC_HDR_INFO:
7874 			ill_fastpath_ack(ill, mp);
7875 			return;
7876 		default:
7877 			putnext(ill->ill_rq, mp);
7878 			return;
7879 		}
7880 		/* FALLTHRU */
7881 	case M_ERROR:
7882 	case M_HANGUP:
7883 		mutex_enter(&ill->ill_lock);
7884 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7885 			mutex_exit(&ill->ill_lock);
7886 			freemsg(mp);
7887 			return;
7888 		}
7889 		ill_refhold_locked(ill);
7890 		mutex_exit(&ill->ill_lock);
7891 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7892 		    B_FALSE);
7893 		return;
7894 	case M_CTL:
7895 		putnext(ill->ill_rq, mp);
7896 		return;
7897 	case M_IOCNAK:
7898 		ip1dbg(("got iocnak "));
7899 		iocp = (struct iocblk *)mp->b_rptr;
7900 		switch (iocp->ioc_cmd) {
7901 		case DL_IOC_HDR_INFO:
7902 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7903 			return;
7904 		default:
7905 			break;
7906 		}
7907 		/* FALLTHRU */
7908 	default:
7909 		putnext(ill->ill_rq, mp);
7910 		return;
7911 	}
7912 }
7913 
7914 /* Read side put procedure.  Packets coming from the wire arrive here. */
7915 void
7916 ip_rput(queue_t *q, mblk_t *mp)
7917 {
7918 	ill_t	*ill;
7919 	union DL_primitives *dl;
7920 
7921 	ill = (ill_t *)q->q_ptr;
7922 
7923 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
7924 		/*
7925 		 * If things are opening or closing, only accept high-priority
7926 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
7927 		 * created; on close, things hanging off the ill may have been
7928 		 * freed already.)
7929 		 */
7930 		dl = (union DL_primitives *)mp->b_rptr;
7931 		if (DB_TYPE(mp) != M_PCPROTO ||
7932 		    dl->dl_primitive == DL_UNITDATA_IND) {
7933 			inet_freemsg(mp);
7934 			return;
7935 		}
7936 	}
7937 	if (DB_TYPE(mp) == M_DATA) {
7938 		struct mac_header_info_s mhi;
7939 
7940 		ip_mdata_to_mhi(ill, mp, &mhi);
7941 		ip_input(ill, NULL, mp, &mhi);
7942 	} else {
7943 		ip_rput_notdata(ill, mp);
7944 	}
7945 }
7946 
7947 /*
7948  * Move the information to a copy.
7949  */
7950 mblk_t *
7951 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
7952 {
7953 	mblk_t		*mp1;
7954 	ill_t		*ill = ira->ira_ill;
7955 	ip_stack_t	*ipst = ill->ill_ipst;
7956 
7957 	IP_STAT(ipst, ip_db_ref);
7958 
7959 	/* Make sure we have ira_l2src before we loose the original mblk */
7960 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7961 		ip_setl2src(mp, ira, ira->ira_rill);
7962 
7963 	mp1 = copymsg(mp);
7964 	if (mp1 == NULL) {
7965 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7966 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
7967 		freemsg(mp);
7968 		return (NULL);
7969 	}
7970 	/* preserve the hardware checksum flags and data, if present */
7971 	if (DB_CKSUMFLAGS(mp) != 0) {
7972 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
7973 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
7974 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
7975 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
7976 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
7977 	}
7978 	freemsg(mp);
7979 	return (mp1);
7980 }
7981 
7982 static void
7983 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
7984     t_uscalar_t err)
7985 {
7986 	if (dl_err == DL_SYSERR) {
7987 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
7988 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
7989 		    ill->ill_name, dl_primstr(prim), err);
7990 		return;
7991 	}
7992 
7993 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
7994 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
7995 	    dl_errstr(dl_err));
7996 }
7997 
7998 /*
7999  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8000  * than DL_UNITDATA_IND messages. If we need to process this message
8001  * exclusively, we call qwriter_ip, in which case we also need to call
8002  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8003  */
8004 void
8005 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8006 {
8007 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8008 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8009 	queue_t		*q = ill->ill_rq;
8010 	t_uscalar_t	prim = dloa->dl_primitive;
8011 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8012 
8013 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8014 	    char *, dl_primstr(prim), ill_t *, ill);
8015 	ip1dbg(("ip_rput_dlpi"));
8016 
8017 	/*
8018 	 * If we received an ACK but didn't send a request for it, then it
8019 	 * can't be part of any pending operation; discard up-front.
8020 	 */
8021 	switch (prim) {
8022 	case DL_ERROR_ACK:
8023 		reqprim = dlea->dl_error_primitive;
8024 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8025 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8026 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8027 		    dlea->dl_unix_errno));
8028 		break;
8029 	case DL_OK_ACK:
8030 		reqprim = dloa->dl_correct_primitive;
8031 		break;
8032 	case DL_INFO_ACK:
8033 		reqprim = DL_INFO_REQ;
8034 		break;
8035 	case DL_BIND_ACK:
8036 		reqprim = DL_BIND_REQ;
8037 		break;
8038 	case DL_PHYS_ADDR_ACK:
8039 		reqprim = DL_PHYS_ADDR_REQ;
8040 		break;
8041 	case DL_NOTIFY_ACK:
8042 		reqprim = DL_NOTIFY_REQ;
8043 		break;
8044 	case DL_CAPABILITY_ACK:
8045 		reqprim = DL_CAPABILITY_REQ;
8046 		break;
8047 	}
8048 
8049 	if (prim != DL_NOTIFY_IND) {
8050 		if (reqprim == DL_PRIM_INVAL ||
8051 		    !ill_dlpi_pending(ill, reqprim)) {
8052 			/* Not a DLPI message we support or expected */
8053 			freemsg(mp);
8054 			return;
8055 		}
8056 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8057 		    dl_primstr(reqprim)));
8058 	}
8059 
8060 	switch (reqprim) {
8061 	case DL_UNBIND_REQ:
8062 		/*
8063 		 * NOTE: we mark the unbind as complete even if we got a
8064 		 * DL_ERROR_ACK, since there's not much else we can do.
8065 		 */
8066 		mutex_enter(&ill->ill_lock);
8067 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8068 		cv_signal(&ill->ill_cv);
8069 		mutex_exit(&ill->ill_lock);
8070 		break;
8071 
8072 	case DL_ENABMULTI_REQ:
8073 		if (prim == DL_OK_ACK) {
8074 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8075 				ill->ill_dlpi_multicast_state = IDS_OK;
8076 		}
8077 		break;
8078 	}
8079 
8080 	/*
8081 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8082 	 * need to become writer to continue to process it.  Because an
8083 	 * exclusive operation doesn't complete until replies to all queued
8084 	 * DLPI messages have been received, we know we're in the middle of an
8085 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8086 	 *
8087 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8088 	 * Since this is on the ill stream we unconditionally bump up the
8089 	 * refcount without doing ILL_CAN_LOOKUP().
8090 	 */
8091 	ill_refhold(ill);
8092 	if (prim == DL_NOTIFY_IND)
8093 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8094 	else
8095 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8096 }
8097 
8098 /*
8099  * Handling of DLPI messages that require exclusive access to the ipsq.
8100  *
8101  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8102  * happen here. (along with mi_copy_done)
8103  */
8104 /* ARGSUSED */
8105 static void
8106 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8107 {
8108 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8109 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8110 	int		err = 0;
8111 	ill_t		*ill = (ill_t *)q->q_ptr;
8112 	ipif_t		*ipif = NULL;
8113 	mblk_t		*mp1 = NULL;
8114 	conn_t		*connp = NULL;
8115 	t_uscalar_t	paddrreq;
8116 	mblk_t		*mp_hw;
8117 	boolean_t	success;
8118 	boolean_t	ioctl_aborted = B_FALSE;
8119 	boolean_t	log = B_TRUE;
8120 
8121 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8122 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8123 
8124 	ip1dbg(("ip_rput_dlpi_writer .."));
8125 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8126 	ASSERT(IAM_WRITER_ILL(ill));
8127 
8128 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8129 	/*
8130 	 * The current ioctl could have been aborted by the user and a new
8131 	 * ioctl to bring up another ill could have started. We could still
8132 	 * get a response from the driver later.
8133 	 */
8134 	if (ipif != NULL && ipif->ipif_ill != ill)
8135 		ioctl_aborted = B_TRUE;
8136 
8137 	switch (dloa->dl_primitive) {
8138 	case DL_ERROR_ACK:
8139 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8140 		    dl_primstr(dlea->dl_error_primitive)));
8141 
8142 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8143 		    char *, dl_primstr(dlea->dl_error_primitive),
8144 		    ill_t *, ill);
8145 
8146 		switch (dlea->dl_error_primitive) {
8147 		case DL_DISABMULTI_REQ:
8148 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8149 			break;
8150 		case DL_PROMISCON_REQ:
8151 		case DL_PROMISCOFF_REQ:
8152 		case DL_UNBIND_REQ:
8153 		case DL_ATTACH_REQ:
8154 		case DL_INFO_REQ:
8155 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8156 			break;
8157 		case DL_NOTIFY_REQ:
8158 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8159 			log = B_FALSE;
8160 			break;
8161 		case DL_PHYS_ADDR_REQ:
8162 			/*
8163 			 * For IPv6 only, there are two additional
8164 			 * phys_addr_req's sent to the driver to get the
8165 			 * IPv6 token and lla. This allows IP to acquire
8166 			 * the hardware address format for a given interface
8167 			 * without having built in knowledge of the hardware
8168 			 * address. ill_phys_addr_pend keeps track of the last
8169 			 * DL_PAR sent so we know which response we are
8170 			 * dealing with. ill_dlpi_done will update
8171 			 * ill_phys_addr_pend when it sends the next req.
8172 			 * We don't complete the IOCTL until all three DL_PARs
8173 			 * have been attempted, so set *_len to 0 and break.
8174 			 */
8175 			paddrreq = ill->ill_phys_addr_pend;
8176 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8177 			if (paddrreq == DL_IPV6_TOKEN) {
8178 				ill->ill_token_length = 0;
8179 				log = B_FALSE;
8180 				break;
8181 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8182 				ill->ill_nd_lla_len = 0;
8183 				log = B_FALSE;
8184 				break;
8185 			}
8186 			/*
8187 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8188 			 * We presumably have an IOCTL hanging out waiting
8189 			 * for completion. Find it and complete the IOCTL
8190 			 * with the error noted.
8191 			 * However, ill_dl_phys was called on an ill queue
8192 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8193 			 * set. But the ioctl is known to be pending on ill_wq.
8194 			 */
8195 			if (!ill->ill_ifname_pending)
8196 				break;
8197 			ill->ill_ifname_pending = 0;
8198 			if (!ioctl_aborted)
8199 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8200 			if (mp1 != NULL) {
8201 				/*
8202 				 * This operation (SIOCSLIFNAME) must have
8203 				 * happened on the ill. Assert there is no conn
8204 				 */
8205 				ASSERT(connp == NULL);
8206 				q = ill->ill_wq;
8207 			}
8208 			break;
8209 		case DL_BIND_REQ:
8210 			ill_dlpi_done(ill, DL_BIND_REQ);
8211 			if (ill->ill_ifname_pending)
8212 				break;
8213 			mutex_enter(&ill->ill_lock);
8214 			ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8215 			mutex_exit(&ill->ill_lock);
8216 			/*
8217 			 * Something went wrong with the bind.  We presumably
8218 			 * have an IOCTL hanging out waiting for completion.
8219 			 * Find it, take down the interface that was coming
8220 			 * up, and complete the IOCTL with the error noted.
8221 			 */
8222 			if (!ioctl_aborted)
8223 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8224 			if (mp1 != NULL) {
8225 				/*
8226 				 * This might be a result of a DL_NOTE_REPLUMB
8227 				 * notification. In that case, connp is NULL.
8228 				 */
8229 				if (connp != NULL)
8230 					q = CONNP_TO_WQ(connp);
8231 
8232 				(void) ipif_down(ipif, NULL, NULL);
8233 				/* error is set below the switch */
8234 			}
8235 			break;
8236 		case DL_ENABMULTI_REQ:
8237 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8238 
8239 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8240 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8241 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8242 
8243 				printf("ip: joining multicasts failed (%d)"
8244 				    " on %s - will use link layer "
8245 				    "broadcasts for multicast\n",
8246 				    dlea->dl_errno, ill->ill_name);
8247 
8248 				/*
8249 				 * Set up for multi_bcast; We are the
8250 				 * writer, so ok to access ill->ill_ipif
8251 				 * without any lock.
8252 				 */
8253 				mutex_enter(&ill->ill_phyint->phyint_lock);
8254 				ill->ill_phyint->phyint_flags |=
8255 				    PHYI_MULTI_BCAST;
8256 				mutex_exit(&ill->ill_phyint->phyint_lock);
8257 
8258 			}
8259 			freemsg(mp);	/* Don't want to pass this up */
8260 			return;
8261 		case DL_CAPABILITY_REQ:
8262 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8263 			    "DL_CAPABILITY REQ\n"));
8264 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8265 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8266 			ill_capability_done(ill);
8267 			freemsg(mp);
8268 			return;
8269 		}
8270 		/*
8271 		 * Note the error for IOCTL completion (mp1 is set when
8272 		 * ready to complete ioctl). If ill_ifname_pending_err is
8273 		 * set, an error occured during plumbing (ill_ifname_pending),
8274 		 * so we want to report that error.
8275 		 *
8276 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8277 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8278 		 * expected to get errack'd if the driver doesn't support
8279 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8280 		 * if these error conditions are encountered.
8281 		 */
8282 		if (mp1 != NULL) {
8283 			if (ill->ill_ifname_pending_err != 0)  {
8284 				err = ill->ill_ifname_pending_err;
8285 				ill->ill_ifname_pending_err = 0;
8286 			} else {
8287 				err = dlea->dl_unix_errno ?
8288 				    dlea->dl_unix_errno : ENXIO;
8289 			}
8290 		/*
8291 		 * If we're plumbing an interface and an error hasn't already
8292 		 * been saved, set ill_ifname_pending_err to the error passed
8293 		 * up. Ignore the error if log is B_FALSE (see comment above).
8294 		 */
8295 		} else if (log && ill->ill_ifname_pending &&
8296 		    ill->ill_ifname_pending_err == 0) {
8297 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8298 			    dlea->dl_unix_errno : ENXIO;
8299 		}
8300 
8301 		if (log)
8302 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8303 			    dlea->dl_errno, dlea->dl_unix_errno);
8304 		break;
8305 	case DL_CAPABILITY_ACK:
8306 		ill_capability_ack(ill, mp);
8307 		/*
8308 		 * The message has been handed off to ill_capability_ack
8309 		 * and must not be freed below
8310 		 */
8311 		mp = NULL;
8312 		break;
8313 
8314 	case DL_INFO_ACK:
8315 		/* Call a routine to handle this one. */
8316 		ill_dlpi_done(ill, DL_INFO_REQ);
8317 		ip_ll_subnet_defaults(ill, mp);
8318 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8319 		return;
8320 	case DL_BIND_ACK:
8321 		/*
8322 		 * We should have an IOCTL waiting on this unless
8323 		 * sent by ill_dl_phys, in which case just return
8324 		 */
8325 		ill_dlpi_done(ill, DL_BIND_REQ);
8326 
8327 		if (ill->ill_ifname_pending) {
8328 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8329 			    ill_t *, ill, mblk_t *, mp);
8330 			break;
8331 		}
8332 		mutex_enter(&ill->ill_lock);
8333 		ill->ill_dl_up = 1;
8334 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8335 		mutex_exit(&ill->ill_lock);
8336 
8337 		if (!ioctl_aborted)
8338 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8339 		if (mp1 == NULL) {
8340 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8341 			break;
8342 		}
8343 		/*
8344 		 * mp1 was added by ill_dl_up(). if that is a result of
8345 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8346 		 */
8347 		if (connp != NULL)
8348 			q = CONNP_TO_WQ(connp);
8349 		/*
8350 		 * We are exclusive. So nothing can change even after
8351 		 * we get the pending mp.
8352 		 */
8353 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8354 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8355 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8356 
8357 		/*
8358 		 * Now bring up the resolver; when that is complete, we'll
8359 		 * create IREs.  Note that we intentionally mirror what
8360 		 * ipif_up() would have done, because we got here by way of
8361 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8362 		 */
8363 		if (ill->ill_isv6) {
8364 			/*
8365 			 * v6 interfaces.
8366 			 * Unlike ARP which has to do another bind
8367 			 * and attach, once we get here we are
8368 			 * done with NDP
8369 			 */
8370 			(void) ipif_resolver_up(ipif, Res_act_initial);
8371 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8372 				err = ipif_up_done_v6(ipif);
8373 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8374 			/*
8375 			 * ARP and other v4 external resolvers.
8376 			 * Leave the pending mblk intact so that
8377 			 * the ioctl completes in ip_rput().
8378 			 */
8379 			if (connp != NULL)
8380 				mutex_enter(&connp->conn_lock);
8381 			mutex_enter(&ill->ill_lock);
8382 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8383 			mutex_exit(&ill->ill_lock);
8384 			if (connp != NULL)
8385 				mutex_exit(&connp->conn_lock);
8386 			if (success) {
8387 				err = ipif_resolver_up(ipif, Res_act_initial);
8388 				if (err == EINPROGRESS) {
8389 					freemsg(mp);
8390 					return;
8391 				}
8392 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8393 			} else {
8394 				/* The conn has started closing */
8395 				err = EINTR;
8396 			}
8397 		} else {
8398 			/*
8399 			 * This one is complete. Reply to pending ioctl.
8400 			 */
8401 			(void) ipif_resolver_up(ipif, Res_act_initial);
8402 			err = ipif_up_done(ipif);
8403 		}
8404 
8405 		if ((err == 0) && (ill->ill_up_ipifs)) {
8406 			err = ill_up_ipifs(ill, q, mp1);
8407 			if (err == EINPROGRESS) {
8408 				freemsg(mp);
8409 				return;
8410 			}
8411 		}
8412 
8413 		/*
8414 		 * If we have a moved ipif to bring up, and everything has
8415 		 * succeeded to this point, bring it up on the IPMP ill.
8416 		 * Otherwise, leave it down -- the admin can try to bring it
8417 		 * up by hand if need be.
8418 		 */
8419 		if (ill->ill_move_ipif != NULL) {
8420 			if (err != 0) {
8421 				ill->ill_move_ipif = NULL;
8422 			} else {
8423 				ipif = ill->ill_move_ipif;
8424 				ill->ill_move_ipif = NULL;
8425 				err = ipif_up(ipif, q, mp1);
8426 				if (err == EINPROGRESS) {
8427 					freemsg(mp);
8428 					return;
8429 				}
8430 			}
8431 		}
8432 		break;
8433 
8434 	case DL_NOTIFY_IND: {
8435 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8436 		uint_t orig_mtu;
8437 
8438 		switch (notify->dl_notification) {
8439 		case DL_NOTE_PHYS_ADDR:
8440 			err = ill_set_phys_addr(ill, mp);
8441 			break;
8442 
8443 		case DL_NOTE_REPLUMB:
8444 			/*
8445 			 * Directly return after calling ill_replumb().
8446 			 * Note that we should not free mp as it is reused
8447 			 * in the ill_replumb() function.
8448 			 */
8449 			err = ill_replumb(ill, mp);
8450 			return;
8451 
8452 		case DL_NOTE_FASTPATH_FLUSH:
8453 			nce_flush(ill, B_FALSE);
8454 			break;
8455 
8456 		case DL_NOTE_SDU_SIZE:
8457 			/*
8458 			 * The dce and fragmentation code can cope with
8459 			 * this changing while packets are being sent.
8460 			 * When packets are sent ip_output will discover
8461 			 * a change.
8462 			 *
8463 			 * Change the MTU size of the interface.
8464 			 */
8465 			mutex_enter(&ill->ill_lock);
8466 			ill->ill_current_frag = (uint_t)notify->dl_data;
8467 			if (ill->ill_current_frag > ill->ill_max_frag)
8468 				ill->ill_max_frag = ill->ill_current_frag;
8469 
8470 			orig_mtu = ill->ill_mtu;
8471 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8472 				ill->ill_mtu = ill->ill_current_frag;
8473 
8474 				/*
8475 				 * If ill_user_mtu was set (via
8476 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8477 				 */
8478 				if (ill->ill_user_mtu != 0 &&
8479 				    ill->ill_user_mtu < ill->ill_mtu)
8480 					ill->ill_mtu = ill->ill_user_mtu;
8481 
8482 				if (ill->ill_isv6) {
8483 					if (ill->ill_mtu < IPV6_MIN_MTU)
8484 						ill->ill_mtu = IPV6_MIN_MTU;
8485 				} else {
8486 					if (ill->ill_mtu < IP_MIN_MTU)
8487 						ill->ill_mtu = IP_MIN_MTU;
8488 				}
8489 			}
8490 			mutex_exit(&ill->ill_lock);
8491 			/*
8492 			 * Make sure all dce_generation checks find out
8493 			 * that ill_mtu has changed.
8494 			 */
8495 			if (orig_mtu != ill->ill_mtu) {
8496 				dce_increment_all_generations(ill->ill_isv6,
8497 				    ill->ill_ipst);
8498 			}
8499 
8500 			/*
8501 			 * Refresh IPMP meta-interface MTU if necessary.
8502 			 */
8503 			if (IS_UNDER_IPMP(ill))
8504 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8505 			break;
8506 
8507 		case DL_NOTE_LINK_UP:
8508 		case DL_NOTE_LINK_DOWN: {
8509 			/*
8510 			 * We are writer. ill / phyint / ipsq assocs stable.
8511 			 * The RUNNING flag reflects the state of the link.
8512 			 */
8513 			phyint_t *phyint = ill->ill_phyint;
8514 			uint64_t new_phyint_flags;
8515 			boolean_t changed = B_FALSE;
8516 			boolean_t went_up;
8517 
8518 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8519 			mutex_enter(&phyint->phyint_lock);
8520 
8521 			new_phyint_flags = went_up ?
8522 			    phyint->phyint_flags | PHYI_RUNNING :
8523 			    phyint->phyint_flags & ~PHYI_RUNNING;
8524 
8525 			if (IS_IPMP(ill)) {
8526 				new_phyint_flags = went_up ?
8527 				    new_phyint_flags & ~PHYI_FAILED :
8528 				    new_phyint_flags | PHYI_FAILED;
8529 			}
8530 
8531 			if (new_phyint_flags != phyint->phyint_flags) {
8532 				phyint->phyint_flags = new_phyint_flags;
8533 				changed = B_TRUE;
8534 			}
8535 			mutex_exit(&phyint->phyint_lock);
8536 			/*
8537 			 * ill_restart_dad handles the DAD restart and routing
8538 			 * socket notification logic.
8539 			 */
8540 			if (changed) {
8541 				ill_restart_dad(phyint->phyint_illv4, went_up);
8542 				ill_restart_dad(phyint->phyint_illv6, went_up);
8543 			}
8544 			break;
8545 		}
8546 		case DL_NOTE_PROMISC_ON_PHYS: {
8547 			phyint_t *phyint = ill->ill_phyint;
8548 
8549 			mutex_enter(&phyint->phyint_lock);
8550 			phyint->phyint_flags |= PHYI_PROMISC;
8551 			mutex_exit(&phyint->phyint_lock);
8552 			break;
8553 		}
8554 		case DL_NOTE_PROMISC_OFF_PHYS: {
8555 			phyint_t *phyint = ill->ill_phyint;
8556 
8557 			mutex_enter(&phyint->phyint_lock);
8558 			phyint->phyint_flags &= ~PHYI_PROMISC;
8559 			mutex_exit(&phyint->phyint_lock);
8560 			break;
8561 		}
8562 		case DL_NOTE_CAPAB_RENEG:
8563 			/*
8564 			 * Something changed on the driver side.
8565 			 * It wants us to renegotiate the capabilities
8566 			 * on this ill. One possible cause is the aggregation
8567 			 * interface under us where a port got added or
8568 			 * went away.
8569 			 *
8570 			 * If the capability negotiation is already done
8571 			 * or is in progress, reset the capabilities and
8572 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8573 			 * so that when the ack comes back, we can start
8574 			 * the renegotiation process.
8575 			 *
8576 			 * Note that if ill_capab_reneg is already B_TRUE
8577 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8578 			 * the capability resetting request has been sent
8579 			 * and the renegotiation has not been started yet;
8580 			 * nothing needs to be done in this case.
8581 			 */
8582 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8583 			ill_capability_reset(ill, B_TRUE);
8584 			ipsq_current_finish(ipsq);
8585 			break;
8586 
8587 		case DL_NOTE_ALLOWED_IPS:
8588 			ill_set_allowed_ips(ill, mp);
8589 			break;
8590 		default:
8591 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8592 			    "type 0x%x for DL_NOTIFY_IND\n",
8593 			    notify->dl_notification));
8594 			break;
8595 		}
8596 
8597 		/*
8598 		 * As this is an asynchronous operation, we
8599 		 * should not call ill_dlpi_done
8600 		 */
8601 		break;
8602 	}
8603 	case DL_NOTIFY_ACK: {
8604 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8605 
8606 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8607 			ill->ill_note_link = 1;
8608 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8609 		break;
8610 	}
8611 	case DL_PHYS_ADDR_ACK: {
8612 		/*
8613 		 * As part of plumbing the interface via SIOCSLIFNAME,
8614 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8615 		 * whose answers we receive here.  As each answer is received,
8616 		 * we call ill_dlpi_done() to dispatch the next request as
8617 		 * we're processing the current one.  Once all answers have
8618 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8619 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8620 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8621 		 * available, but we know the ioctl is pending on ill_wq.)
8622 		 */
8623 		uint_t	paddrlen, paddroff;
8624 		uint8_t	*addr;
8625 
8626 		paddrreq = ill->ill_phys_addr_pend;
8627 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8628 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8629 		addr = mp->b_rptr + paddroff;
8630 
8631 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8632 		if (paddrreq == DL_IPV6_TOKEN) {
8633 			/*
8634 			 * bcopy to low-order bits of ill_token
8635 			 *
8636 			 * XXX Temporary hack - currently, all known tokens
8637 			 * are 64 bits, so I'll cheat for the moment.
8638 			 */
8639 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8640 			ill->ill_token_length = paddrlen;
8641 			break;
8642 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8643 			ASSERT(ill->ill_nd_lla_mp == NULL);
8644 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8645 			mp = NULL;
8646 			break;
8647 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8648 			ASSERT(ill->ill_dest_addr_mp == NULL);
8649 			ill->ill_dest_addr_mp = mp;
8650 			ill->ill_dest_addr = addr;
8651 			mp = NULL;
8652 			if (ill->ill_isv6) {
8653 				ill_setdesttoken(ill);
8654 				ipif_setdestlinklocal(ill->ill_ipif);
8655 			}
8656 			break;
8657 		}
8658 
8659 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8660 		ASSERT(ill->ill_phys_addr_mp == NULL);
8661 		if (!ill->ill_ifname_pending)
8662 			break;
8663 		ill->ill_ifname_pending = 0;
8664 		if (!ioctl_aborted)
8665 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8666 		if (mp1 != NULL) {
8667 			ASSERT(connp == NULL);
8668 			q = ill->ill_wq;
8669 		}
8670 		/*
8671 		 * If any error acks received during the plumbing sequence,
8672 		 * ill_ifname_pending_err will be set. Break out and send up
8673 		 * the error to the pending ioctl.
8674 		 */
8675 		if (ill->ill_ifname_pending_err != 0) {
8676 			err = ill->ill_ifname_pending_err;
8677 			ill->ill_ifname_pending_err = 0;
8678 			break;
8679 		}
8680 
8681 		ill->ill_phys_addr_mp = mp;
8682 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8683 		mp = NULL;
8684 
8685 		/*
8686 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8687 		 * provider doesn't support physical addresses.  We check both
8688 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8689 		 * not have physical addresses, but historically adversises a
8690 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8691 		 * its DL_PHYS_ADDR_ACK.
8692 		 */
8693 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8694 			ill->ill_phys_addr = NULL;
8695 		} else if (paddrlen != ill->ill_phys_addr_length) {
8696 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8697 			    paddrlen, ill->ill_phys_addr_length));
8698 			err = EINVAL;
8699 			break;
8700 		}
8701 
8702 		if (ill->ill_nd_lla_mp == NULL) {
8703 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8704 				err = ENOMEM;
8705 				break;
8706 			}
8707 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8708 		}
8709 
8710 		if (ill->ill_isv6) {
8711 			ill_setdefaulttoken(ill);
8712 			ipif_setlinklocal(ill->ill_ipif);
8713 		}
8714 		break;
8715 	}
8716 	case DL_OK_ACK:
8717 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8718 		    dl_primstr((int)dloa->dl_correct_primitive),
8719 		    dloa->dl_correct_primitive));
8720 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8721 		    char *, dl_primstr(dloa->dl_correct_primitive),
8722 		    ill_t *, ill);
8723 
8724 		switch (dloa->dl_correct_primitive) {
8725 		case DL_ENABMULTI_REQ:
8726 		case DL_DISABMULTI_REQ:
8727 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8728 			break;
8729 		case DL_PROMISCON_REQ:
8730 		case DL_PROMISCOFF_REQ:
8731 		case DL_UNBIND_REQ:
8732 		case DL_ATTACH_REQ:
8733 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8734 			break;
8735 		}
8736 		break;
8737 	default:
8738 		break;
8739 	}
8740 
8741 	freemsg(mp);
8742 	if (mp1 == NULL)
8743 		return;
8744 
8745 	/*
8746 	 * The operation must complete without EINPROGRESS since
8747 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8748 	 * the operation will be stuck forever inside the IPSQ.
8749 	 */
8750 	ASSERT(err != EINPROGRESS);
8751 
8752 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8753 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8754 	    ipif_t *, NULL);
8755 
8756 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8757 	case 0:
8758 		ipsq_current_finish(ipsq);
8759 		break;
8760 
8761 	case SIOCSLIFNAME:
8762 	case IF_UNITSEL: {
8763 		ill_t *ill_other = ILL_OTHER(ill);
8764 
8765 		/*
8766 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8767 		 * ill has a peer which is in an IPMP group, then place ill
8768 		 * into the same group.  One catch: although ifconfig plumbs
8769 		 * the appropriate IPMP meta-interface prior to plumbing this
8770 		 * ill, it is possible for multiple ifconfig applications to
8771 		 * race (or for another application to adjust plumbing), in
8772 		 * which case the IPMP meta-interface we need will be missing.
8773 		 * If so, kick the phyint out of the group.
8774 		 */
8775 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8776 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8777 			ipmp_illgrp_t	*illg;
8778 
8779 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8780 			if (illg == NULL)
8781 				ipmp_phyint_leave_grp(ill->ill_phyint);
8782 			else
8783 				ipmp_ill_join_illgrp(ill, illg);
8784 		}
8785 
8786 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8787 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8788 		else
8789 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8790 		break;
8791 	}
8792 	case SIOCLIFADDIF:
8793 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8794 		break;
8795 
8796 	default:
8797 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8798 		break;
8799 	}
8800 }
8801 
8802 /*
8803  * ip_rput_other is called by ip_rput to handle messages modifying the global
8804  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8805  */
8806 /* ARGSUSED */
8807 void
8808 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8809 {
8810 	ill_t		*ill = q->q_ptr;
8811 	struct iocblk	*iocp;
8812 
8813 	ip1dbg(("ip_rput_other "));
8814 	if (ipsq != NULL) {
8815 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8816 		ASSERT(ipsq->ipsq_xop ==
8817 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8818 	}
8819 
8820 	switch (mp->b_datap->db_type) {
8821 	case M_ERROR:
8822 	case M_HANGUP:
8823 		/*
8824 		 * The device has a problem.  We force the ILL down.  It can
8825 		 * be brought up again manually using SIOCSIFFLAGS (via
8826 		 * ifconfig or equivalent).
8827 		 */
8828 		ASSERT(ipsq != NULL);
8829 		if (mp->b_rptr < mp->b_wptr)
8830 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8831 		if (ill->ill_error == 0)
8832 			ill->ill_error = ENXIO;
8833 		if (!ill_down_start(q, mp))
8834 			return;
8835 		ipif_all_down_tail(ipsq, q, mp, NULL);
8836 		break;
8837 	case M_IOCNAK: {
8838 		iocp = (struct iocblk *)mp->b_rptr;
8839 
8840 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8841 		/*
8842 		 * If this was the first attempt, turn off the fastpath
8843 		 * probing.
8844 		 */
8845 		mutex_enter(&ill->ill_lock);
8846 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8847 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8848 			mutex_exit(&ill->ill_lock);
8849 			/*
8850 			 * don't flush the nce_t entries: we use them
8851 			 * as an index to the ncec itself.
8852 			 */
8853 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8854 			    ill->ill_name));
8855 		} else {
8856 			mutex_exit(&ill->ill_lock);
8857 		}
8858 		freemsg(mp);
8859 		break;
8860 	}
8861 	default:
8862 		ASSERT(0);
8863 		break;
8864 	}
8865 }
8866 
8867 /*
8868  * Update any source route, record route or timestamp options
8869  * When it fails it has consumed the message and BUMPed the MIB.
8870  */
8871 boolean_t
8872 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8873     ip_recv_attr_t *ira)
8874 {
8875 	ipoptp_t	opts;
8876 	uchar_t		*opt;
8877 	uint8_t		optval;
8878 	uint8_t		optlen;
8879 	ipaddr_t	dst;
8880 	ipaddr_t	ifaddr;
8881 	uint32_t	ts;
8882 	timestruc_t	now;
8883 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
8884 
8885 	ip2dbg(("ip_forward_options\n"));
8886 	dst = ipha->ipha_dst;
8887 	for (optval = ipoptp_first(&opts, ipha);
8888 	    optval != IPOPT_EOL;
8889 	    optval = ipoptp_next(&opts)) {
8890 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
8891 		opt = opts.ipoptp_cur;
8892 		optlen = opts.ipoptp_len;
8893 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
8894 		    optval, opts.ipoptp_len));
8895 		switch (optval) {
8896 			uint32_t off;
8897 		case IPOPT_SSRR:
8898 		case IPOPT_LSRR:
8899 			/* Check if adminstratively disabled */
8900 			if (!ipst->ips_ip_forward_src_routed) {
8901 				BUMP_MIB(dst_ill->ill_ip_mib,
8902 				    ipIfStatsForwProhibits);
8903 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
8904 				    mp, dst_ill);
8905 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
8906 				    ira);
8907 				return (B_FALSE);
8908 			}
8909 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8910 				/*
8911 				 * Must be partial since ip_input_options
8912 				 * checked for strict.
8913 				 */
8914 				break;
8915 			}
8916 			off = opt[IPOPT_OFFSET];
8917 			off--;
8918 		redo_srr:
8919 			if (optlen < IP_ADDR_LEN ||
8920 			    off > optlen - IP_ADDR_LEN) {
8921 				/* End of source route */
8922 				ip1dbg((
8923 				    "ip_forward_options: end of SR\n"));
8924 				break;
8925 			}
8926 			/* Pick a reasonable address on the outbound if */
8927 			ASSERT(dst_ill != NULL);
8928 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8929 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8930 			    NULL) != 0) {
8931 				/* No source! Shouldn't happen */
8932 				ifaddr = INADDR_ANY;
8933 			}
8934 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8935 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8936 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
8937 			    ntohl(dst)));
8938 
8939 			/*
8940 			 * Check if our address is present more than
8941 			 * once as consecutive hops in source route.
8942 			 */
8943 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
8944 				off += IP_ADDR_LEN;
8945 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8946 				goto redo_srr;
8947 			}
8948 			ipha->ipha_dst = dst;
8949 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8950 			break;
8951 		case IPOPT_RR:
8952 			off = opt[IPOPT_OFFSET];
8953 			off--;
8954 			if (optlen < IP_ADDR_LEN ||
8955 			    off > optlen - IP_ADDR_LEN) {
8956 				/* No more room - ignore */
8957 				ip1dbg((
8958 				    "ip_forward_options: end of RR\n"));
8959 				break;
8960 			}
8961 			/* Pick a reasonable address on the outbound if */
8962 			ASSERT(dst_ill != NULL);
8963 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8964 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8965 			    NULL) != 0) {
8966 				/* No source! Shouldn't happen */
8967 				ifaddr = INADDR_ANY;
8968 			}
8969 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8970 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8971 			break;
8972 		case IPOPT_TS:
8973 			/* Insert timestamp if there is room */
8974 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
8975 			case IPOPT_TS_TSONLY:
8976 				off = IPOPT_TS_TIMELEN;
8977 				break;
8978 			case IPOPT_TS_PRESPEC:
8979 			case IPOPT_TS_PRESPEC_RFC791:
8980 				/* Verify that the address matched */
8981 				off = opt[IPOPT_OFFSET] - 1;
8982 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8983 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8984 					/* Not for us */
8985 					break;
8986 				}
8987 				/* FALLTHRU */
8988 			case IPOPT_TS_TSANDADDR:
8989 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
8990 				break;
8991 			default:
8992 				/*
8993 				 * ip_*put_options should have already
8994 				 * dropped this packet.
8995 				 */
8996 				cmn_err(CE_PANIC, "ip_forward_options: "
8997 				    "unknown IT - bug in ip_input_options?\n");
8998 				return (B_TRUE);	/* Keep "lint" happy */
8999 			}
9000 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9001 				/* Increase overflow counter */
9002 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9003 				opt[IPOPT_POS_OV_FLG] =
9004 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9005 				    (off << 4));
9006 				break;
9007 			}
9008 			off = opt[IPOPT_OFFSET] - 1;
9009 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9010 			case IPOPT_TS_PRESPEC:
9011 			case IPOPT_TS_PRESPEC_RFC791:
9012 			case IPOPT_TS_TSANDADDR:
9013 				/* Pick a reasonable addr on the outbound if */
9014 				ASSERT(dst_ill != NULL);
9015 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9016 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9017 				    NULL, NULL) != 0) {
9018 					/* No source! Shouldn't happen */
9019 					ifaddr = INADDR_ANY;
9020 				}
9021 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9022 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9023 				/* FALLTHRU */
9024 			case IPOPT_TS_TSONLY:
9025 				off = opt[IPOPT_OFFSET] - 1;
9026 				/* Compute # of milliseconds since midnight */
9027 				gethrestime(&now);
9028 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9029 				    now.tv_nsec / (NANOSEC / MILLISEC);
9030 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9031 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9032 				break;
9033 			}
9034 			break;
9035 		}
9036 	}
9037 	return (B_TRUE);
9038 }
9039 
9040 /*
9041  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9042  * returns 'true' if there are still fragments left on the queue, in
9043  * which case we restart the timer.
9044  */
9045 void
9046 ill_frag_timer(void *arg)
9047 {
9048 	ill_t	*ill = (ill_t *)arg;
9049 	boolean_t frag_pending;
9050 	ip_stack_t *ipst = ill->ill_ipst;
9051 	time_t	timeout;
9052 
9053 	mutex_enter(&ill->ill_lock);
9054 	ASSERT(!ill->ill_fragtimer_executing);
9055 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9056 		ill->ill_frag_timer_id = 0;
9057 		mutex_exit(&ill->ill_lock);
9058 		return;
9059 	}
9060 	ill->ill_fragtimer_executing = 1;
9061 	mutex_exit(&ill->ill_lock);
9062 
9063 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9064 	    ipst->ips_ip_reassembly_timeout);
9065 
9066 	frag_pending = ill_frag_timeout(ill, timeout);
9067 
9068 	/*
9069 	 * Restart the timer, if we have fragments pending or if someone
9070 	 * wanted us to be scheduled again.
9071 	 */
9072 	mutex_enter(&ill->ill_lock);
9073 	ill->ill_fragtimer_executing = 0;
9074 	ill->ill_frag_timer_id = 0;
9075 	if (frag_pending || ill->ill_fragtimer_needrestart)
9076 		ill_frag_timer_start(ill);
9077 	mutex_exit(&ill->ill_lock);
9078 }
9079 
9080 void
9081 ill_frag_timer_start(ill_t *ill)
9082 {
9083 	ip_stack_t *ipst = ill->ill_ipst;
9084 	clock_t	timeo_ms;
9085 
9086 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9087 
9088 	/* If the ill is closing or opening don't proceed */
9089 	if (ill->ill_state_flags & ILL_CONDEMNED)
9090 		return;
9091 
9092 	if (ill->ill_fragtimer_executing) {
9093 		/*
9094 		 * ill_frag_timer is currently executing. Just record the
9095 		 * the fact that we want the timer to be restarted.
9096 		 * ill_frag_timer will post a timeout before it returns,
9097 		 * ensuring it will be called again.
9098 		 */
9099 		ill->ill_fragtimer_needrestart = 1;
9100 		return;
9101 	}
9102 
9103 	if (ill->ill_frag_timer_id == 0) {
9104 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9105 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9106 
9107 		/*
9108 		 * The timer is neither running nor is the timeout handler
9109 		 * executing. Post a timeout so that ill_frag_timer will be
9110 		 * called
9111 		 */
9112 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9113 		    MSEC_TO_TICK(timeo_ms >> 1));
9114 		ill->ill_fragtimer_needrestart = 0;
9115 	}
9116 }
9117 
9118 /*
9119  * Update any source route, record route or timestamp options.
9120  * Check that we are at end of strict source route.
9121  * The options have already been checked for sanity in ip_input_options().
9122  */
9123 boolean_t
9124 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9125 {
9126 	ipoptp_t	opts;
9127 	uchar_t		*opt;
9128 	uint8_t		optval;
9129 	uint8_t		optlen;
9130 	ipaddr_t	dst;
9131 	ipaddr_t	ifaddr;
9132 	uint32_t	ts;
9133 	timestruc_t	now;
9134 	ill_t		*ill = ira->ira_ill;
9135 	ip_stack_t	*ipst = ill->ill_ipst;
9136 
9137 	ip2dbg(("ip_input_local_options\n"));
9138 
9139 	for (optval = ipoptp_first(&opts, ipha);
9140 	    optval != IPOPT_EOL;
9141 	    optval = ipoptp_next(&opts)) {
9142 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9143 		opt = opts.ipoptp_cur;
9144 		optlen = opts.ipoptp_len;
9145 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9146 		    optval, optlen));
9147 		switch (optval) {
9148 			uint32_t off;
9149 		case IPOPT_SSRR:
9150 		case IPOPT_LSRR:
9151 			off = opt[IPOPT_OFFSET];
9152 			off--;
9153 			if (optlen < IP_ADDR_LEN ||
9154 			    off > optlen - IP_ADDR_LEN) {
9155 				/* End of source route */
9156 				ip1dbg(("ip_input_local_options: end of SR\n"));
9157 				break;
9158 			}
9159 			/*
9160 			 * This will only happen if two consecutive entries
9161 			 * in the source route contains our address or if
9162 			 * it is a packet with a loose source route which
9163 			 * reaches us before consuming the whole source route
9164 			 */
9165 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9166 			if (optval == IPOPT_SSRR) {
9167 				goto bad_src_route;
9168 			}
9169 			/*
9170 			 * Hack: instead of dropping the packet truncate the
9171 			 * source route to what has been used by filling the
9172 			 * rest with IPOPT_NOP.
9173 			 */
9174 			opt[IPOPT_OLEN] = (uint8_t)off;
9175 			while (off < optlen) {
9176 				opt[off++] = IPOPT_NOP;
9177 			}
9178 			break;
9179 		case IPOPT_RR:
9180 			off = opt[IPOPT_OFFSET];
9181 			off--;
9182 			if (optlen < IP_ADDR_LEN ||
9183 			    off > optlen - IP_ADDR_LEN) {
9184 				/* No more room - ignore */
9185 				ip1dbg((
9186 				    "ip_input_local_options: end of RR\n"));
9187 				break;
9188 			}
9189 			/* Pick a reasonable address on the outbound if */
9190 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9191 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9192 			    NULL) != 0) {
9193 				/* No source! Shouldn't happen */
9194 				ifaddr = INADDR_ANY;
9195 			}
9196 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9197 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9198 			break;
9199 		case IPOPT_TS:
9200 			/* Insert timestamp if there is romm */
9201 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9202 			case IPOPT_TS_TSONLY:
9203 				off = IPOPT_TS_TIMELEN;
9204 				break;
9205 			case IPOPT_TS_PRESPEC:
9206 			case IPOPT_TS_PRESPEC_RFC791:
9207 				/* Verify that the address matched */
9208 				off = opt[IPOPT_OFFSET] - 1;
9209 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9210 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9211 					/* Not for us */
9212 					break;
9213 				}
9214 				/* FALLTHRU */
9215 			case IPOPT_TS_TSANDADDR:
9216 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9217 				break;
9218 			default:
9219 				/*
9220 				 * ip_*put_options should have already
9221 				 * dropped this packet.
9222 				 */
9223 				cmn_err(CE_PANIC, "ip_input_local_options: "
9224 				    "unknown IT - bug in ip_input_options?\n");
9225 				return (B_TRUE);	/* Keep "lint" happy */
9226 			}
9227 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9228 				/* Increase overflow counter */
9229 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9230 				opt[IPOPT_POS_OV_FLG] =
9231 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9232 				    (off << 4));
9233 				break;
9234 			}
9235 			off = opt[IPOPT_OFFSET] - 1;
9236 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9237 			case IPOPT_TS_PRESPEC:
9238 			case IPOPT_TS_PRESPEC_RFC791:
9239 			case IPOPT_TS_TSANDADDR:
9240 				/* Pick a reasonable addr on the outbound if */
9241 				if (ip_select_source_v4(ill, INADDR_ANY,
9242 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9243 				    &ifaddr, NULL, NULL) != 0) {
9244 					/* No source! Shouldn't happen */
9245 					ifaddr = INADDR_ANY;
9246 				}
9247 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9248 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9249 				/* FALLTHRU */
9250 			case IPOPT_TS_TSONLY:
9251 				off = opt[IPOPT_OFFSET] - 1;
9252 				/* Compute # of milliseconds since midnight */
9253 				gethrestime(&now);
9254 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9255 				    now.tv_nsec / (NANOSEC / MILLISEC);
9256 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9257 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9258 				break;
9259 			}
9260 			break;
9261 		}
9262 	}
9263 	return (B_TRUE);
9264 
9265 bad_src_route:
9266 	/* make sure we clear any indication of a hardware checksum */
9267 	DB_CKSUMFLAGS(mp) = 0;
9268 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9269 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9270 	return (B_FALSE);
9271 
9272 }
9273 
9274 /*
9275  * Process IP options in an inbound packet.  Always returns the nexthop.
9276  * Normally this is the passed in nexthop, but if there is an option
9277  * that effects the nexthop (such as a source route) that will be returned.
9278  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9279  * and mp freed.
9280  */
9281 ipaddr_t
9282 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9283     ip_recv_attr_t *ira, int *errorp)
9284 {
9285 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9286 	ipoptp_t	opts;
9287 	uchar_t		*opt;
9288 	uint8_t		optval;
9289 	uint8_t		optlen;
9290 	intptr_t	code = 0;
9291 	ire_t		*ire;
9292 
9293 	ip2dbg(("ip_input_options\n"));
9294 	*errorp = 0;
9295 	for (optval = ipoptp_first(&opts, ipha);
9296 	    optval != IPOPT_EOL;
9297 	    optval = ipoptp_next(&opts)) {
9298 		opt = opts.ipoptp_cur;
9299 		optlen = opts.ipoptp_len;
9300 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9301 		    optval, optlen));
9302 		/*
9303 		 * Note: we need to verify the checksum before we
9304 		 * modify anything thus this routine only extracts the next
9305 		 * hop dst from any source route.
9306 		 */
9307 		switch (optval) {
9308 			uint32_t off;
9309 		case IPOPT_SSRR:
9310 		case IPOPT_LSRR:
9311 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9312 				if (optval == IPOPT_SSRR) {
9313 					ip1dbg(("ip_input_options: not next"
9314 					    " strict source route 0x%x\n",
9315 					    ntohl(dst)));
9316 					code = (char *)&ipha->ipha_dst -
9317 					    (char *)ipha;
9318 					goto param_prob; /* RouterReq's */
9319 				}
9320 				ip2dbg(("ip_input_options: "
9321 				    "not next source route 0x%x\n",
9322 				    ntohl(dst)));
9323 				break;
9324 			}
9325 
9326 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9327 				ip1dbg((
9328 				    "ip_input_options: bad option offset\n"));
9329 				code = (char *)&opt[IPOPT_OLEN] -
9330 				    (char *)ipha;
9331 				goto param_prob;
9332 			}
9333 			off = opt[IPOPT_OFFSET];
9334 			off--;
9335 		redo_srr:
9336 			if (optlen < IP_ADDR_LEN ||
9337 			    off > optlen - IP_ADDR_LEN) {
9338 				/* End of source route */
9339 				ip1dbg(("ip_input_options: end of SR\n"));
9340 				break;
9341 			}
9342 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9343 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9344 			    ntohl(dst)));
9345 
9346 			/*
9347 			 * Check if our address is present more than
9348 			 * once as consecutive hops in source route.
9349 			 * XXX verify per-interface ip_forwarding
9350 			 * for source route?
9351 			 */
9352 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9353 				off += IP_ADDR_LEN;
9354 				goto redo_srr;
9355 			}
9356 
9357 			if (dst == htonl(INADDR_LOOPBACK)) {
9358 				ip1dbg(("ip_input_options: loopback addr in "
9359 				    "source route!\n"));
9360 				goto bad_src_route;
9361 			}
9362 			/*
9363 			 * For strict: verify that dst is directly
9364 			 * reachable.
9365 			 */
9366 			if (optval == IPOPT_SSRR) {
9367 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9368 				    IRE_IF_ALL, NULL, ALL_ZONES,
9369 				    ira->ira_tsl,
9370 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9371 				    NULL);
9372 				if (ire == NULL) {
9373 					ip1dbg(("ip_input_options: SSRR not "
9374 					    "directly reachable: 0x%x\n",
9375 					    ntohl(dst)));
9376 					goto bad_src_route;
9377 				}
9378 				ire_refrele(ire);
9379 			}
9380 			/*
9381 			 * Defer update of the offset and the record route
9382 			 * until the packet is forwarded.
9383 			 */
9384 			break;
9385 		case IPOPT_RR:
9386 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9387 				ip1dbg((
9388 				    "ip_input_options: bad option offset\n"));
9389 				code = (char *)&opt[IPOPT_OLEN] -
9390 				    (char *)ipha;
9391 				goto param_prob;
9392 			}
9393 			break;
9394 		case IPOPT_TS:
9395 			/*
9396 			 * Verify that length >= 5 and that there is either
9397 			 * room for another timestamp or that the overflow
9398 			 * counter is not maxed out.
9399 			 */
9400 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9401 			if (optlen < IPOPT_MINLEN_IT) {
9402 				goto param_prob;
9403 			}
9404 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9405 				ip1dbg((
9406 				    "ip_input_options: bad option offset\n"));
9407 				code = (char *)&opt[IPOPT_OFFSET] -
9408 				    (char *)ipha;
9409 				goto param_prob;
9410 			}
9411 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9412 			case IPOPT_TS_TSONLY:
9413 				off = IPOPT_TS_TIMELEN;
9414 				break;
9415 			case IPOPT_TS_TSANDADDR:
9416 			case IPOPT_TS_PRESPEC:
9417 			case IPOPT_TS_PRESPEC_RFC791:
9418 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9419 				break;
9420 			default:
9421 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9422 				    (char *)ipha;
9423 				goto param_prob;
9424 			}
9425 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9426 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9427 				/*
9428 				 * No room and the overflow counter is 15
9429 				 * already.
9430 				 */
9431 				goto param_prob;
9432 			}
9433 			break;
9434 		}
9435 	}
9436 
9437 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9438 		return (dst);
9439 	}
9440 
9441 	ip1dbg(("ip_input_options: error processing IP options."));
9442 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9443 
9444 param_prob:
9445 	/* make sure we clear any indication of a hardware checksum */
9446 	DB_CKSUMFLAGS(mp) = 0;
9447 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9448 	icmp_param_problem(mp, (uint8_t)code, ira);
9449 	*errorp = -1;
9450 	return (dst);
9451 
9452 bad_src_route:
9453 	/* make sure we clear any indication of a hardware checksum */
9454 	DB_CKSUMFLAGS(mp) = 0;
9455 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9456 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9457 	*errorp = -1;
9458 	return (dst);
9459 }
9460 
9461 /*
9462  * IP & ICMP info in >=14 msg's ...
9463  *  - ip fixed part (mib2_ip_t)
9464  *  - icmp fixed part (mib2_icmp_t)
9465  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9466  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9467  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9468  *  - ipRouteAttributeTable (ip 102)	labeled routes
9469  *  - ip multicast membership (ip_member_t)
9470  *  - ip multicast source filtering (ip_grpsrc_t)
9471  *  - igmp fixed part (struct igmpstat)
9472  *  - multicast routing stats (struct mrtstat)
9473  *  - multicast routing vifs (array of struct vifctl)
9474  *  - multicast routing routes (array of struct mfcctl)
9475  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9476  *					One per ill plus one generic
9477  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9478  *					One per ill plus one generic
9479  *  - ipv6RouteEntry			all IPv6 IREs
9480  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9481  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9482  *  - ipv6AddrEntry			all IPv6 ipifs
9483  *  - ipv6 multicast membership (ipv6_member_t)
9484  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9485  *
9486  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9487  * already filled in by the caller.
9488  * Return value of 0 indicates that no messages were sent and caller
9489  * should free mpctl.
9490  */
9491 int
9492 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
9493 {
9494 	ip_stack_t *ipst;
9495 	sctp_stack_t *sctps;
9496 
9497 	if (q->q_next != NULL) {
9498 		ipst = ILLQ_TO_IPST(q);
9499 	} else {
9500 		ipst = CONNQ_TO_IPST(q);
9501 	}
9502 	ASSERT(ipst != NULL);
9503 	sctps = ipst->ips_netstack->netstack_sctp;
9504 
9505 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9506 		return (0);
9507 	}
9508 
9509 	/*
9510 	 * For the purposes of the (broken) packet shell use
9511 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9512 	 * to make TCP and UDP appear first in the list of mib items.
9513 	 * TBD: We could expand this and use it in netstat so that
9514 	 * the kernel doesn't have to produce large tables (connections,
9515 	 * routes, etc) when netstat only wants the statistics or a particular
9516 	 * table.
9517 	 */
9518 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9519 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9520 			return (1);
9521 		}
9522 	}
9523 
9524 	if (level != MIB2_TCP) {
9525 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
9526 			return (1);
9527 		}
9528 	}
9529 
9530 	if (level != MIB2_UDP) {
9531 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
9532 			return (1);
9533 		}
9534 	}
9535 
9536 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9537 	    ipst)) == NULL) {
9538 		return (1);
9539 	}
9540 
9541 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
9542 		return (1);
9543 	}
9544 
9545 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9546 		return (1);
9547 	}
9548 
9549 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9550 		return (1);
9551 	}
9552 
9553 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9554 		return (1);
9555 	}
9556 
9557 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9558 		return (1);
9559 	}
9560 
9561 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
9562 		return (1);
9563 	}
9564 
9565 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
9566 		return (1);
9567 	}
9568 
9569 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9570 		return (1);
9571 	}
9572 
9573 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9574 		return (1);
9575 	}
9576 
9577 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9578 		return (1);
9579 	}
9580 
9581 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9582 		return (1);
9583 	}
9584 
9585 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9586 		return (1);
9587 	}
9588 
9589 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9590 		return (1);
9591 	}
9592 
9593 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9594 	if (mpctl == NULL)
9595 		return (1);
9596 
9597 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9598 	if (mpctl == NULL)
9599 		return (1);
9600 
9601 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9602 		return (1);
9603 	}
9604 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9605 		return (1);
9606 	}
9607 	freemsg(mpctl);
9608 	return (1);
9609 }
9610 
9611 /* Get global (legacy) IPv4 statistics */
9612 static mblk_t *
9613 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9614     ip_stack_t *ipst)
9615 {
9616 	mib2_ip_t		old_ip_mib;
9617 	struct opthdr		*optp;
9618 	mblk_t			*mp2ctl;
9619 
9620 	/*
9621 	 * make a copy of the original message
9622 	 */
9623 	mp2ctl = copymsg(mpctl);
9624 
9625 	/* fixed length IP structure... */
9626 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9627 	optp->level = MIB2_IP;
9628 	optp->name = 0;
9629 	SET_MIB(old_ip_mib.ipForwarding,
9630 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9631 	SET_MIB(old_ip_mib.ipDefaultTTL,
9632 	    (uint32_t)ipst->ips_ip_def_ttl);
9633 	SET_MIB(old_ip_mib.ipReasmTimeout,
9634 	    ipst->ips_ip_reassembly_timeout);
9635 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9636 	    sizeof (mib2_ipAddrEntry_t));
9637 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9638 	    sizeof (mib2_ipRouteEntry_t));
9639 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9640 	    sizeof (mib2_ipNetToMediaEntry_t));
9641 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9642 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9643 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9644 	    sizeof (mib2_ipAttributeEntry_t));
9645 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9646 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9647 
9648 	/*
9649 	 * Grab the statistics from the new IP MIB
9650 	 */
9651 	SET_MIB(old_ip_mib.ipInReceives,
9652 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9653 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9654 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9655 	SET_MIB(old_ip_mib.ipForwDatagrams,
9656 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9657 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9658 	    ipmib->ipIfStatsInUnknownProtos);
9659 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9660 	SET_MIB(old_ip_mib.ipInDelivers,
9661 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9662 	SET_MIB(old_ip_mib.ipOutRequests,
9663 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9664 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9665 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9666 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9667 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9668 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9669 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9670 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9671 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9672 
9673 	/* ipRoutingDiscards is not being used */
9674 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9675 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9676 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9677 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9678 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9679 	    ipmib->ipIfStatsReasmDuplicates);
9680 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9681 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9682 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9683 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9684 	SET_MIB(old_ip_mib.rawipInOverflows,
9685 	    ipmib->rawipIfStatsInOverflows);
9686 
9687 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9688 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9689 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9690 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9691 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9692 	    ipmib->ipIfStatsOutSwitchIPVersion);
9693 
9694 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9695 	    (int)sizeof (old_ip_mib))) {
9696 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9697 		    (uint_t)sizeof (old_ip_mib)));
9698 	}
9699 
9700 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9701 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9702 	    (int)optp->level, (int)optp->name, (int)optp->len));
9703 	qreply(q, mpctl);
9704 	return (mp2ctl);
9705 }
9706 
9707 /* Per interface IPv4 statistics */
9708 static mblk_t *
9709 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9710 {
9711 	struct opthdr		*optp;
9712 	mblk_t			*mp2ctl;
9713 	ill_t			*ill;
9714 	ill_walk_context_t	ctx;
9715 	mblk_t			*mp_tail = NULL;
9716 	mib2_ipIfStatsEntry_t	global_ip_mib;
9717 
9718 	/*
9719 	 * Make a copy of the original message
9720 	 */
9721 	mp2ctl = copymsg(mpctl);
9722 
9723 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9724 	optp->level = MIB2_IP;
9725 	optp->name = MIB2_IP_TRAFFIC_STATS;
9726 	/* Include "unknown interface" ip_mib */
9727 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9728 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9729 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9730 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9731 	    (ipst->ips_ip_forwarding ? 1 : 2));
9732 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9733 	    (uint32_t)ipst->ips_ip_def_ttl);
9734 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9735 	    sizeof (mib2_ipIfStatsEntry_t));
9736 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9737 	    sizeof (mib2_ipAddrEntry_t));
9738 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9739 	    sizeof (mib2_ipRouteEntry_t));
9740 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9741 	    sizeof (mib2_ipNetToMediaEntry_t));
9742 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9743 	    sizeof (ip_member_t));
9744 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9745 	    sizeof (ip_grpsrc_t));
9746 
9747 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9748 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
9749 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9750 		    "failed to allocate %u bytes\n",
9751 		    (uint_t)sizeof (ipst->ips_ip_mib)));
9752 	}
9753 
9754 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9755 
9756 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9757 	ill = ILL_START_WALK_V4(&ctx, ipst);
9758 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9759 		ill->ill_ip_mib->ipIfStatsIfIndex =
9760 		    ill->ill_phyint->phyint_ifindex;
9761 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9762 		    (ipst->ips_ip_forwarding ? 1 : 2));
9763 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9764 		    (uint32_t)ipst->ips_ip_def_ttl);
9765 
9766 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9767 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9768 		    (char *)ill->ill_ip_mib,
9769 		    (int)sizeof (*ill->ill_ip_mib))) {
9770 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9771 			    "failed to allocate %u bytes\n",
9772 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9773 		}
9774 	}
9775 	rw_exit(&ipst->ips_ill_g_lock);
9776 
9777 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9778 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9779 	    "level %d, name %d, len %d\n",
9780 	    (int)optp->level, (int)optp->name, (int)optp->len));
9781 	qreply(q, mpctl);
9782 
9783 	if (mp2ctl == NULL)
9784 		return (NULL);
9785 
9786 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
9787 }
9788 
9789 /* Global IPv4 ICMP statistics */
9790 static mblk_t *
9791 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9792 {
9793 	struct opthdr		*optp;
9794 	mblk_t			*mp2ctl;
9795 
9796 	/*
9797 	 * Make a copy of the original message
9798 	 */
9799 	mp2ctl = copymsg(mpctl);
9800 
9801 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9802 	optp->level = MIB2_ICMP;
9803 	optp->name = 0;
9804 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9805 	    (int)sizeof (ipst->ips_icmp_mib))) {
9806 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9807 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9808 	}
9809 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9810 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9811 	    (int)optp->level, (int)optp->name, (int)optp->len));
9812 	qreply(q, mpctl);
9813 	return (mp2ctl);
9814 }
9815 
9816 /* Global IPv4 IGMP statistics */
9817 static mblk_t *
9818 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9819 {
9820 	struct opthdr		*optp;
9821 	mblk_t			*mp2ctl;
9822 
9823 	/*
9824 	 * make a copy of the original message
9825 	 */
9826 	mp2ctl = copymsg(mpctl);
9827 
9828 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9829 	optp->level = EXPER_IGMP;
9830 	optp->name = 0;
9831 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9832 	    (int)sizeof (ipst->ips_igmpstat))) {
9833 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9834 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9835 	}
9836 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9837 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9838 	    (int)optp->level, (int)optp->name, (int)optp->len));
9839 	qreply(q, mpctl);
9840 	return (mp2ctl);
9841 }
9842 
9843 /* Global IPv4 Multicast Routing statistics */
9844 static mblk_t *
9845 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9846 {
9847 	struct opthdr		*optp;
9848 	mblk_t			*mp2ctl;
9849 
9850 	/*
9851 	 * make a copy of the original message
9852 	 */
9853 	mp2ctl = copymsg(mpctl);
9854 
9855 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9856 	optp->level = EXPER_DVMRP;
9857 	optp->name = 0;
9858 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9859 		ip0dbg(("ip_mroute_stats: failed\n"));
9860 	}
9861 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9862 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9863 	    (int)optp->level, (int)optp->name, (int)optp->len));
9864 	qreply(q, mpctl);
9865 	return (mp2ctl);
9866 }
9867 
9868 /* IPv4 address information */
9869 static mblk_t *
9870 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9871 {
9872 	struct opthdr		*optp;
9873 	mblk_t			*mp2ctl;
9874 	mblk_t			*mp_tail = NULL;
9875 	ill_t			*ill;
9876 	ipif_t			*ipif;
9877 	uint_t			bitval;
9878 	mib2_ipAddrEntry_t	mae;
9879 	zoneid_t		zoneid;
9880 	ill_walk_context_t ctx;
9881 
9882 	/*
9883 	 * make a copy of the original message
9884 	 */
9885 	mp2ctl = copymsg(mpctl);
9886 
9887 	/* ipAddrEntryTable */
9888 
9889 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9890 	optp->level = MIB2_IP;
9891 	optp->name = MIB2_IP_ADDR;
9892 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9893 
9894 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9895 	ill = ILL_START_WALK_V4(&ctx, ipst);
9896 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9897 		for (ipif = ill->ill_ipif; ipif != NULL;
9898 		    ipif = ipif->ipif_next) {
9899 			if (ipif->ipif_zoneid != zoneid &&
9900 			    ipif->ipif_zoneid != ALL_ZONES)
9901 				continue;
9902 			/* Sum of count from dead IRE_LO* and our current */
9903 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9904 			if (ipif->ipif_ire_local != NULL) {
9905 				mae.ipAdEntInfo.ae_ibcnt +=
9906 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9907 			}
9908 			mae.ipAdEntInfo.ae_obcnt = 0;
9909 			mae.ipAdEntInfo.ae_focnt = 0;
9910 
9911 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
9912 			    OCTET_LENGTH);
9913 			mae.ipAdEntIfIndex.o_length =
9914 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
9915 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
9916 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
9917 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
9918 			mae.ipAdEntInfo.ae_subnet_len =
9919 			    ip_mask_to_plen(ipif->ipif_net_mask);
9920 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
9921 			for (bitval = 1;
9922 			    bitval &&
9923 			    !(bitval & ipif->ipif_brd_addr);
9924 			    bitval <<= 1)
9925 				noop;
9926 			mae.ipAdEntBcastAddr = bitval;
9927 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
9928 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
9929 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
9930 			mae.ipAdEntInfo.ae_broadcast_addr =
9931 			    ipif->ipif_brd_addr;
9932 			mae.ipAdEntInfo.ae_pp_dst_addr =
9933 			    ipif->ipif_pp_dst_addr;
9934 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
9935 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
9936 			mae.ipAdEntRetransmitTime =
9937 			    ill->ill_reachable_retrans_time;
9938 
9939 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9940 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
9941 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
9942 				    "allocate %u bytes\n",
9943 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
9944 			}
9945 		}
9946 	}
9947 	rw_exit(&ipst->ips_ill_g_lock);
9948 
9949 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9950 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
9951 	    (int)optp->level, (int)optp->name, (int)optp->len));
9952 	qreply(q, mpctl);
9953 	return (mp2ctl);
9954 }
9955 
9956 /* IPv6 address information */
9957 static mblk_t *
9958 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9959 {
9960 	struct opthdr		*optp;
9961 	mblk_t			*mp2ctl;
9962 	mblk_t			*mp_tail = NULL;
9963 	ill_t			*ill;
9964 	ipif_t			*ipif;
9965 	mib2_ipv6AddrEntry_t	mae6;
9966 	zoneid_t		zoneid;
9967 	ill_walk_context_t	ctx;
9968 
9969 	/*
9970 	 * make a copy of the original message
9971 	 */
9972 	mp2ctl = copymsg(mpctl);
9973 
9974 	/* ipv6AddrEntryTable */
9975 
9976 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9977 	optp->level = MIB2_IP6;
9978 	optp->name = MIB2_IP6_ADDR;
9979 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9980 
9981 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9982 	ill = ILL_START_WALK_V6(&ctx, ipst);
9983 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9984 		for (ipif = ill->ill_ipif; ipif != NULL;
9985 		    ipif = ipif->ipif_next) {
9986 			if (ipif->ipif_zoneid != zoneid &&
9987 			    ipif->ipif_zoneid != ALL_ZONES)
9988 				continue;
9989 			/* Sum of count from dead IRE_LO* and our current */
9990 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9991 			if (ipif->ipif_ire_local != NULL) {
9992 				mae6.ipv6AddrInfo.ae_ibcnt +=
9993 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9994 			}
9995 			mae6.ipv6AddrInfo.ae_obcnt = 0;
9996 			mae6.ipv6AddrInfo.ae_focnt = 0;
9997 
9998 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
9999 			    OCTET_LENGTH);
10000 			mae6.ipv6AddrIfIndex.o_length =
10001 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10002 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10003 			mae6.ipv6AddrPfxLength =
10004 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10005 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10006 			mae6.ipv6AddrInfo.ae_subnet_len =
10007 			    mae6.ipv6AddrPfxLength;
10008 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10009 
10010 			/* Type: stateless(1), stateful(2), unknown(3) */
10011 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10012 				mae6.ipv6AddrType = 1;
10013 			else
10014 				mae6.ipv6AddrType = 2;
10015 			/* Anycast: true(1), false(2) */
10016 			if (ipif->ipif_flags & IPIF_ANYCAST)
10017 				mae6.ipv6AddrAnycastFlag = 1;
10018 			else
10019 				mae6.ipv6AddrAnycastFlag = 2;
10020 
10021 			/*
10022 			 * Address status: preferred(1), deprecated(2),
10023 			 * invalid(3), inaccessible(4), unknown(5)
10024 			 */
10025 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10026 				mae6.ipv6AddrStatus = 3;
10027 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10028 				mae6.ipv6AddrStatus = 2;
10029 			else
10030 				mae6.ipv6AddrStatus = 1;
10031 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10032 			mae6.ipv6AddrInfo.ae_metric  =
10033 			    ipif->ipif_ill->ill_metric;
10034 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10035 			    ipif->ipif_v6pp_dst_addr;
10036 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10037 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10038 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10039 			mae6.ipv6AddrIdentifier = ill->ill_token;
10040 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10041 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10042 			mae6.ipv6AddrRetransmitTime =
10043 			    ill->ill_reachable_retrans_time;
10044 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10045 			    (char *)&mae6,
10046 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
10047 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10048 				    "allocate %u bytes\n",
10049 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
10050 			}
10051 		}
10052 	}
10053 	rw_exit(&ipst->ips_ill_g_lock);
10054 
10055 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10056 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10057 	    (int)optp->level, (int)optp->name, (int)optp->len));
10058 	qreply(q, mpctl);
10059 	return (mp2ctl);
10060 }
10061 
10062 /* IPv4 multicast group membership. */
10063 static mblk_t *
10064 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10065 {
10066 	struct opthdr		*optp;
10067 	mblk_t			*mp2ctl;
10068 	ill_t			*ill;
10069 	ipif_t			*ipif;
10070 	ilm_t			*ilm;
10071 	ip_member_t		ipm;
10072 	mblk_t			*mp_tail = NULL;
10073 	ill_walk_context_t	ctx;
10074 	zoneid_t		zoneid;
10075 
10076 	/*
10077 	 * make a copy of the original message
10078 	 */
10079 	mp2ctl = copymsg(mpctl);
10080 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10081 
10082 	/* ipGroupMember table */
10083 	optp = (struct opthdr *)&mpctl->b_rptr[
10084 	    sizeof (struct T_optmgmt_ack)];
10085 	optp->level = MIB2_IP;
10086 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10087 
10088 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10089 	ill = ILL_START_WALK_V4(&ctx, ipst);
10090 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10091 		/* Make sure the ill isn't going away. */
10092 		if (!ill_check_and_refhold(ill))
10093 			continue;
10094 		rw_exit(&ipst->ips_ill_g_lock);
10095 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10096 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10097 			if (ilm->ilm_zoneid != zoneid &&
10098 			    ilm->ilm_zoneid != ALL_ZONES)
10099 				continue;
10100 
10101 			/* Is there an ipif for ilm_ifaddr? */
10102 			for (ipif = ill->ill_ipif; ipif != NULL;
10103 			    ipif = ipif->ipif_next) {
10104 				if (!IPIF_IS_CONDEMNED(ipif) &&
10105 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10106 				    ilm->ilm_ifaddr != INADDR_ANY)
10107 					break;
10108 			}
10109 			if (ipif != NULL) {
10110 				ipif_get_name(ipif,
10111 				    ipm.ipGroupMemberIfIndex.o_bytes,
10112 				    OCTET_LENGTH);
10113 			} else {
10114 				ill_get_name(ill,
10115 				    ipm.ipGroupMemberIfIndex.o_bytes,
10116 				    OCTET_LENGTH);
10117 			}
10118 			ipm.ipGroupMemberIfIndex.o_length =
10119 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10120 
10121 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10122 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10123 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10124 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10125 			    (char *)&ipm, (int)sizeof (ipm))) {
10126 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10127 				    "failed to allocate %u bytes\n",
10128 				    (uint_t)sizeof (ipm)));
10129 			}
10130 		}
10131 		rw_exit(&ill->ill_mcast_lock);
10132 		ill_refrele(ill);
10133 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10134 	}
10135 	rw_exit(&ipst->ips_ill_g_lock);
10136 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10137 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10138 	    (int)optp->level, (int)optp->name, (int)optp->len));
10139 	qreply(q, mpctl);
10140 	return (mp2ctl);
10141 }
10142 
10143 /* IPv6 multicast group membership. */
10144 static mblk_t *
10145 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10146 {
10147 	struct opthdr		*optp;
10148 	mblk_t			*mp2ctl;
10149 	ill_t			*ill;
10150 	ilm_t			*ilm;
10151 	ipv6_member_t		ipm6;
10152 	mblk_t			*mp_tail = NULL;
10153 	ill_walk_context_t	ctx;
10154 	zoneid_t		zoneid;
10155 
10156 	/*
10157 	 * make a copy of the original message
10158 	 */
10159 	mp2ctl = copymsg(mpctl);
10160 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10161 
10162 	/* ip6GroupMember table */
10163 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10164 	optp->level = MIB2_IP6;
10165 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10166 
10167 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10168 	ill = ILL_START_WALK_V6(&ctx, ipst);
10169 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10170 		/* Make sure the ill isn't going away. */
10171 		if (!ill_check_and_refhold(ill))
10172 			continue;
10173 		rw_exit(&ipst->ips_ill_g_lock);
10174 		/*
10175 		 * Normally we don't have any members on under IPMP interfaces.
10176 		 * We report them as a debugging aid.
10177 		 */
10178 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10179 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10180 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10181 			if (ilm->ilm_zoneid != zoneid &&
10182 			    ilm->ilm_zoneid != ALL_ZONES)
10183 				continue;	/* not this zone */
10184 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10185 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10186 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10187 			if (!snmp_append_data2(mpctl->b_cont,
10188 			    &mp_tail,
10189 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10190 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10191 				    "failed to allocate %u bytes\n",
10192 				    (uint_t)sizeof (ipm6)));
10193 			}
10194 		}
10195 		rw_exit(&ill->ill_mcast_lock);
10196 		ill_refrele(ill);
10197 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10198 	}
10199 	rw_exit(&ipst->ips_ill_g_lock);
10200 
10201 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10202 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10203 	    (int)optp->level, (int)optp->name, (int)optp->len));
10204 	qreply(q, mpctl);
10205 	return (mp2ctl);
10206 }
10207 
10208 /* IP multicast filtered sources */
10209 static mblk_t *
10210 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10211 {
10212 	struct opthdr		*optp;
10213 	mblk_t			*mp2ctl;
10214 	ill_t			*ill;
10215 	ipif_t			*ipif;
10216 	ilm_t			*ilm;
10217 	ip_grpsrc_t		ips;
10218 	mblk_t			*mp_tail = NULL;
10219 	ill_walk_context_t	ctx;
10220 	zoneid_t		zoneid;
10221 	int			i;
10222 	slist_t			*sl;
10223 
10224 	/*
10225 	 * make a copy of the original message
10226 	 */
10227 	mp2ctl = copymsg(mpctl);
10228 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10229 
10230 	/* ipGroupSource table */
10231 	optp = (struct opthdr *)&mpctl->b_rptr[
10232 	    sizeof (struct T_optmgmt_ack)];
10233 	optp->level = MIB2_IP;
10234 	optp->name = EXPER_IP_GROUP_SOURCES;
10235 
10236 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10237 	ill = ILL_START_WALK_V4(&ctx, ipst);
10238 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10239 		/* Make sure the ill isn't going away. */
10240 		if (!ill_check_and_refhold(ill))
10241 			continue;
10242 		rw_exit(&ipst->ips_ill_g_lock);
10243 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10244 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10245 			sl = ilm->ilm_filter;
10246 			if (ilm->ilm_zoneid != zoneid &&
10247 			    ilm->ilm_zoneid != ALL_ZONES)
10248 				continue;
10249 			if (SLIST_IS_EMPTY(sl))
10250 				continue;
10251 
10252 			/* Is there an ipif for ilm_ifaddr? */
10253 			for (ipif = ill->ill_ipif; ipif != NULL;
10254 			    ipif = ipif->ipif_next) {
10255 				if (!IPIF_IS_CONDEMNED(ipif) &&
10256 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10257 				    ilm->ilm_ifaddr != INADDR_ANY)
10258 					break;
10259 			}
10260 			if (ipif != NULL) {
10261 				ipif_get_name(ipif,
10262 				    ips.ipGroupSourceIfIndex.o_bytes,
10263 				    OCTET_LENGTH);
10264 			} else {
10265 				ill_get_name(ill,
10266 				    ips.ipGroupSourceIfIndex.o_bytes,
10267 				    OCTET_LENGTH);
10268 			}
10269 			ips.ipGroupSourceIfIndex.o_length =
10270 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10271 
10272 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10273 			for (i = 0; i < sl->sl_numsrc; i++) {
10274 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10275 					continue;
10276 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10277 				    ips.ipGroupSourceAddress);
10278 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10279 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10280 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10281 					    " failed to allocate %u bytes\n",
10282 					    (uint_t)sizeof (ips)));
10283 				}
10284 			}
10285 		}
10286 		rw_exit(&ill->ill_mcast_lock);
10287 		ill_refrele(ill);
10288 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10289 	}
10290 	rw_exit(&ipst->ips_ill_g_lock);
10291 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10292 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10293 	    (int)optp->level, (int)optp->name, (int)optp->len));
10294 	qreply(q, mpctl);
10295 	return (mp2ctl);
10296 }
10297 
10298 /* IPv6 multicast filtered sources. */
10299 static mblk_t *
10300 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10301 {
10302 	struct opthdr		*optp;
10303 	mblk_t			*mp2ctl;
10304 	ill_t			*ill;
10305 	ilm_t			*ilm;
10306 	ipv6_grpsrc_t		ips6;
10307 	mblk_t			*mp_tail = NULL;
10308 	ill_walk_context_t	ctx;
10309 	zoneid_t		zoneid;
10310 	int			i;
10311 	slist_t			*sl;
10312 
10313 	/*
10314 	 * make a copy of the original message
10315 	 */
10316 	mp2ctl = copymsg(mpctl);
10317 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10318 
10319 	/* ip6GroupMember table */
10320 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10321 	optp->level = MIB2_IP6;
10322 	optp->name = EXPER_IP6_GROUP_SOURCES;
10323 
10324 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10325 	ill = ILL_START_WALK_V6(&ctx, ipst);
10326 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10327 		/* Make sure the ill isn't going away. */
10328 		if (!ill_check_and_refhold(ill))
10329 			continue;
10330 		rw_exit(&ipst->ips_ill_g_lock);
10331 		/*
10332 		 * Normally we don't have any members on under IPMP interfaces.
10333 		 * We report them as a debugging aid.
10334 		 */
10335 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10336 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10337 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10338 			sl = ilm->ilm_filter;
10339 			if (ilm->ilm_zoneid != zoneid &&
10340 			    ilm->ilm_zoneid != ALL_ZONES)
10341 				continue;
10342 			if (SLIST_IS_EMPTY(sl))
10343 				continue;
10344 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10345 			for (i = 0; i < sl->sl_numsrc; i++) {
10346 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10347 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10348 				    (char *)&ips6, (int)sizeof (ips6))) {
10349 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10350 					    "group_src: failed to allocate "
10351 					    "%u bytes\n",
10352 					    (uint_t)sizeof (ips6)));
10353 				}
10354 			}
10355 		}
10356 		rw_exit(&ill->ill_mcast_lock);
10357 		ill_refrele(ill);
10358 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10359 	}
10360 	rw_exit(&ipst->ips_ill_g_lock);
10361 
10362 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10363 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10364 	    (int)optp->level, (int)optp->name, (int)optp->len));
10365 	qreply(q, mpctl);
10366 	return (mp2ctl);
10367 }
10368 
10369 /* Multicast routing virtual interface table. */
10370 static mblk_t *
10371 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10372 {
10373 	struct opthdr		*optp;
10374 	mblk_t			*mp2ctl;
10375 
10376 	/*
10377 	 * make a copy of the original message
10378 	 */
10379 	mp2ctl = copymsg(mpctl);
10380 
10381 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10382 	optp->level = EXPER_DVMRP;
10383 	optp->name = EXPER_DVMRP_VIF;
10384 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10385 		ip0dbg(("ip_mroute_vif: failed\n"));
10386 	}
10387 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10388 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10389 	    (int)optp->level, (int)optp->name, (int)optp->len));
10390 	qreply(q, mpctl);
10391 	return (mp2ctl);
10392 }
10393 
10394 /* Multicast routing table. */
10395 static mblk_t *
10396 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10397 {
10398 	struct opthdr		*optp;
10399 	mblk_t			*mp2ctl;
10400 
10401 	/*
10402 	 * make a copy of the original message
10403 	 */
10404 	mp2ctl = copymsg(mpctl);
10405 
10406 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10407 	optp->level = EXPER_DVMRP;
10408 	optp->name = EXPER_DVMRP_MRT;
10409 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10410 		ip0dbg(("ip_mroute_mrt: failed\n"));
10411 	}
10412 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10413 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10414 	    (int)optp->level, (int)optp->name, (int)optp->len));
10415 	qreply(q, mpctl);
10416 	return (mp2ctl);
10417 }
10418 
10419 /*
10420  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10421  * in one IRE walk.
10422  */
10423 static mblk_t *
10424 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10425     ip_stack_t *ipst)
10426 {
10427 	struct opthdr	*optp;
10428 	mblk_t		*mp2ctl;	/* Returned */
10429 	mblk_t		*mp3ctl;	/* nettomedia */
10430 	mblk_t		*mp4ctl;	/* routeattrs */
10431 	iproutedata_t	ird;
10432 	zoneid_t	zoneid;
10433 
10434 	/*
10435 	 * make copies of the original message
10436 	 *	- mp2ctl is returned unchanged to the caller for his use
10437 	 *	- mpctl is sent upstream as ipRouteEntryTable
10438 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10439 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10440 	 */
10441 	mp2ctl = copymsg(mpctl);
10442 	mp3ctl = copymsg(mpctl);
10443 	mp4ctl = copymsg(mpctl);
10444 	if (mp3ctl == NULL || mp4ctl == NULL) {
10445 		freemsg(mp4ctl);
10446 		freemsg(mp3ctl);
10447 		freemsg(mp2ctl);
10448 		freemsg(mpctl);
10449 		return (NULL);
10450 	}
10451 
10452 	bzero(&ird, sizeof (ird));
10453 
10454 	ird.ird_route.lp_head = mpctl->b_cont;
10455 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10456 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10457 	/*
10458 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10459 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10460 	 * intended a temporary solution until a proper MIB API is provided
10461 	 * that provides complete filtering/caller-opt-in.
10462 	 */
10463 	if (level == EXPER_IP_AND_ALL_IRES)
10464 		ird.ird_flags |= IRD_REPORT_ALL;
10465 
10466 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10467 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10468 
10469 	/* ipRouteEntryTable in mpctl */
10470 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10471 	optp->level = MIB2_IP;
10472 	optp->name = MIB2_IP_ROUTE;
10473 	optp->len = msgdsize(ird.ird_route.lp_head);
10474 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10475 	    (int)optp->level, (int)optp->name, (int)optp->len));
10476 	qreply(q, mpctl);
10477 
10478 	/* ipNetToMediaEntryTable in mp3ctl */
10479 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10480 
10481 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10482 	optp->level = MIB2_IP;
10483 	optp->name = MIB2_IP_MEDIA;
10484 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10485 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10486 	    (int)optp->level, (int)optp->name, (int)optp->len));
10487 	qreply(q, mp3ctl);
10488 
10489 	/* ipRouteAttributeTable in mp4ctl */
10490 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10491 	optp->level = MIB2_IP;
10492 	optp->name = EXPER_IP_RTATTR;
10493 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10494 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10495 	    (int)optp->level, (int)optp->name, (int)optp->len));
10496 	if (optp->len == 0)
10497 		freemsg(mp4ctl);
10498 	else
10499 		qreply(q, mp4ctl);
10500 
10501 	return (mp2ctl);
10502 }
10503 
10504 /*
10505  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10506  * ipv6NetToMediaEntryTable in an NDP walk.
10507  */
10508 static mblk_t *
10509 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10510     ip_stack_t *ipst)
10511 {
10512 	struct opthdr	*optp;
10513 	mblk_t		*mp2ctl;	/* Returned */
10514 	mblk_t		*mp3ctl;	/* nettomedia */
10515 	mblk_t		*mp4ctl;	/* routeattrs */
10516 	iproutedata_t	ird;
10517 	zoneid_t	zoneid;
10518 
10519 	/*
10520 	 * make copies of the original message
10521 	 *	- mp2ctl is returned unchanged to the caller for his use
10522 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10523 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10524 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10525 	 */
10526 	mp2ctl = copymsg(mpctl);
10527 	mp3ctl = copymsg(mpctl);
10528 	mp4ctl = copymsg(mpctl);
10529 	if (mp3ctl == NULL || mp4ctl == NULL) {
10530 		freemsg(mp4ctl);
10531 		freemsg(mp3ctl);
10532 		freemsg(mp2ctl);
10533 		freemsg(mpctl);
10534 		return (NULL);
10535 	}
10536 
10537 	bzero(&ird, sizeof (ird));
10538 
10539 	ird.ird_route.lp_head = mpctl->b_cont;
10540 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10541 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10542 	/*
10543 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10544 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10545 	 * intended a temporary solution until a proper MIB API is provided
10546 	 * that provides complete filtering/caller-opt-in.
10547 	 */
10548 	if (level == EXPER_IP_AND_ALL_IRES)
10549 		ird.ird_flags |= IRD_REPORT_ALL;
10550 
10551 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10552 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10553 
10554 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10555 	optp->level = MIB2_IP6;
10556 	optp->name = MIB2_IP6_ROUTE;
10557 	optp->len = msgdsize(ird.ird_route.lp_head);
10558 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10559 	    (int)optp->level, (int)optp->name, (int)optp->len));
10560 	qreply(q, mpctl);
10561 
10562 	/* ipv6NetToMediaEntryTable in mp3ctl */
10563 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10564 
10565 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10566 	optp->level = MIB2_IP6;
10567 	optp->name = MIB2_IP6_MEDIA;
10568 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10569 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10570 	    (int)optp->level, (int)optp->name, (int)optp->len));
10571 	qreply(q, mp3ctl);
10572 
10573 	/* ipv6RouteAttributeTable in mp4ctl */
10574 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10575 	optp->level = MIB2_IP6;
10576 	optp->name = EXPER_IP_RTATTR;
10577 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10578 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10579 	    (int)optp->level, (int)optp->name, (int)optp->len));
10580 	if (optp->len == 0)
10581 		freemsg(mp4ctl);
10582 	else
10583 		qreply(q, mp4ctl);
10584 
10585 	return (mp2ctl);
10586 }
10587 
10588 /*
10589  * IPv6 mib: One per ill
10590  */
10591 static mblk_t *
10592 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10593 {
10594 	struct opthdr		*optp;
10595 	mblk_t			*mp2ctl;
10596 	ill_t			*ill;
10597 	ill_walk_context_t	ctx;
10598 	mblk_t			*mp_tail = NULL;
10599 
10600 	/*
10601 	 * Make a copy of the original message
10602 	 */
10603 	mp2ctl = copymsg(mpctl);
10604 
10605 	/* fixed length IPv6 structure ... */
10606 
10607 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10608 	optp->level = MIB2_IP6;
10609 	optp->name = 0;
10610 	/* Include "unknown interface" ip6_mib */
10611 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10612 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10613 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10614 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10615 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10616 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10617 	    ipst->ips_ipv6_def_hops);
10618 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10619 	    sizeof (mib2_ipIfStatsEntry_t));
10620 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10621 	    sizeof (mib2_ipv6AddrEntry_t));
10622 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10623 	    sizeof (mib2_ipv6RouteEntry_t));
10624 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10625 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10626 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10627 	    sizeof (ipv6_member_t));
10628 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10629 	    sizeof (ipv6_grpsrc_t));
10630 
10631 	/*
10632 	 * Synchronize 64- and 32-bit counters
10633 	 */
10634 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10635 	    ipIfStatsHCInReceives);
10636 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10637 	    ipIfStatsHCInDelivers);
10638 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10639 	    ipIfStatsHCOutRequests);
10640 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10641 	    ipIfStatsHCOutForwDatagrams);
10642 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10643 	    ipIfStatsHCOutMcastPkts);
10644 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10645 	    ipIfStatsHCInMcastPkts);
10646 
10647 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10648 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
10649 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10650 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
10651 	}
10652 
10653 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10654 	ill = ILL_START_WALK_V6(&ctx, ipst);
10655 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10656 		ill->ill_ip_mib->ipIfStatsIfIndex =
10657 		    ill->ill_phyint->phyint_ifindex;
10658 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10659 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10660 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10661 		    ill->ill_max_hops);
10662 
10663 		/*
10664 		 * Synchronize 64- and 32-bit counters
10665 		 */
10666 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10667 		    ipIfStatsHCInReceives);
10668 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10669 		    ipIfStatsHCInDelivers);
10670 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10671 		    ipIfStatsHCOutRequests);
10672 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10673 		    ipIfStatsHCOutForwDatagrams);
10674 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10675 		    ipIfStatsHCOutMcastPkts);
10676 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10677 		    ipIfStatsHCInMcastPkts);
10678 
10679 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10680 		    (char *)ill->ill_ip_mib,
10681 		    (int)sizeof (*ill->ill_ip_mib))) {
10682 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10683 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
10684 		}
10685 	}
10686 	rw_exit(&ipst->ips_ill_g_lock);
10687 
10688 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10689 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10690 	    (int)optp->level, (int)optp->name, (int)optp->len));
10691 	qreply(q, mpctl);
10692 	return (mp2ctl);
10693 }
10694 
10695 /*
10696  * ICMPv6 mib: One per ill
10697  */
10698 static mblk_t *
10699 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10700 {
10701 	struct opthdr		*optp;
10702 	mblk_t			*mp2ctl;
10703 	ill_t			*ill;
10704 	ill_walk_context_t	ctx;
10705 	mblk_t			*mp_tail = NULL;
10706 	/*
10707 	 * Make a copy of the original message
10708 	 */
10709 	mp2ctl = copymsg(mpctl);
10710 
10711 	/* fixed length ICMPv6 structure ... */
10712 
10713 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10714 	optp->level = MIB2_ICMP6;
10715 	optp->name = 0;
10716 	/* Include "unknown interface" icmp6_mib */
10717 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10718 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10719 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10720 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10721 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10722 	    (char *)&ipst->ips_icmp6_mib,
10723 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10724 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10725 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10726 	}
10727 
10728 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10729 	ill = ILL_START_WALK_V6(&ctx, ipst);
10730 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10731 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10732 		    ill->ill_phyint->phyint_ifindex;
10733 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10734 		    (char *)ill->ill_icmp6_mib,
10735 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10736 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10737 			    "%u bytes\n",
10738 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10739 		}
10740 	}
10741 	rw_exit(&ipst->ips_ill_g_lock);
10742 
10743 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10744 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10745 	    (int)optp->level, (int)optp->name, (int)optp->len));
10746 	qreply(q, mpctl);
10747 	return (mp2ctl);
10748 }
10749 
10750 /*
10751  * ire_walk routine to create both ipRouteEntryTable and
10752  * ipRouteAttributeTable in one IRE walk
10753  */
10754 static void
10755 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10756 {
10757 	ill_t				*ill;
10758 	mib2_ipRouteEntry_t		*re;
10759 	mib2_ipAttributeEntry_t		iaes;
10760 	tsol_ire_gw_secattr_t		*attrp;
10761 	tsol_gc_t			*gc = NULL;
10762 	tsol_gcgrp_t			*gcgrp = NULL;
10763 	ip_stack_t			*ipst = ire->ire_ipst;
10764 
10765 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10766 
10767 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10768 		if (ire->ire_testhidden)
10769 			return;
10770 		if (ire->ire_type & IRE_IF_CLONE)
10771 			return;
10772 	}
10773 
10774 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10775 		return;
10776 
10777 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10778 		mutex_enter(&attrp->igsa_lock);
10779 		if ((gc = attrp->igsa_gc) != NULL) {
10780 			gcgrp = gc->gc_grp;
10781 			ASSERT(gcgrp != NULL);
10782 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10783 		}
10784 		mutex_exit(&attrp->igsa_lock);
10785 	}
10786 	/*
10787 	 * Return all IRE types for route table... let caller pick and choose
10788 	 */
10789 	re->ipRouteDest = ire->ire_addr;
10790 	ill = ire->ire_ill;
10791 	re->ipRouteIfIndex.o_length = 0;
10792 	if (ill != NULL) {
10793 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10794 		re->ipRouteIfIndex.o_length =
10795 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10796 	}
10797 	re->ipRouteMetric1 = -1;
10798 	re->ipRouteMetric2 = -1;
10799 	re->ipRouteMetric3 = -1;
10800 	re->ipRouteMetric4 = -1;
10801 
10802 	re->ipRouteNextHop = ire->ire_gateway_addr;
10803 	/* indirect(4), direct(3), or invalid(2) */
10804 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10805 		re->ipRouteType = 2;
10806 	else if (ire->ire_type & IRE_ONLINK)
10807 		re->ipRouteType = 3;
10808 	else
10809 		re->ipRouteType = 4;
10810 
10811 	re->ipRouteProto = -1;
10812 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10813 	re->ipRouteMask = ire->ire_mask;
10814 	re->ipRouteMetric5 = -1;
10815 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10816 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10817 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10818 
10819 	re->ipRouteInfo.re_frag_flag	= 0;
10820 	re->ipRouteInfo.re_rtt		= 0;
10821 	re->ipRouteInfo.re_src_addr	= 0;
10822 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
10823 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10824 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10825 	re->ipRouteInfo.re_flags	= ire->ire_flags;
10826 
10827 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10828 	if (ire->ire_type & IRE_INTERFACE) {
10829 		ire_t *child;
10830 
10831 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10832 		child = ire->ire_dep_children;
10833 		while (child != NULL) {
10834 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10835 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10836 			child = child->ire_dep_sib_next;
10837 		}
10838 		rw_exit(&ipst->ips_ire_dep_lock);
10839 	}
10840 
10841 	if (ire->ire_flags & RTF_DYNAMIC) {
10842 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10843 	} else {
10844 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
10845 	}
10846 
10847 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10848 	    (char *)re, (int)sizeof (*re))) {
10849 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
10850 		    (uint_t)sizeof (*re)));
10851 	}
10852 
10853 	if (gc != NULL) {
10854 		iaes.iae_routeidx = ird->ird_idx;
10855 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10856 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10857 
10858 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10859 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10860 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
10861 			    "bytes\n", (uint_t)sizeof (iaes)));
10862 		}
10863 	}
10864 
10865 	/* bump route index for next pass */
10866 	ird->ird_idx++;
10867 
10868 	kmem_free(re, sizeof (*re));
10869 	if (gcgrp != NULL)
10870 		rw_exit(&gcgrp->gcgrp_rwlock);
10871 }
10872 
10873 /*
10874  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
10875  */
10876 static void
10877 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
10878 {
10879 	ill_t				*ill;
10880 	mib2_ipv6RouteEntry_t		*re;
10881 	mib2_ipAttributeEntry_t		iaes;
10882 	tsol_ire_gw_secattr_t		*attrp;
10883 	tsol_gc_t			*gc = NULL;
10884 	tsol_gcgrp_t			*gcgrp = NULL;
10885 	ip_stack_t			*ipst = ire->ire_ipst;
10886 
10887 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
10888 
10889 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10890 		if (ire->ire_testhidden)
10891 			return;
10892 		if (ire->ire_type & IRE_IF_CLONE)
10893 			return;
10894 	}
10895 
10896 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10897 		return;
10898 
10899 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10900 		mutex_enter(&attrp->igsa_lock);
10901 		if ((gc = attrp->igsa_gc) != NULL) {
10902 			gcgrp = gc->gc_grp;
10903 			ASSERT(gcgrp != NULL);
10904 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10905 		}
10906 		mutex_exit(&attrp->igsa_lock);
10907 	}
10908 	/*
10909 	 * Return all IRE types for route table... let caller pick and choose
10910 	 */
10911 	re->ipv6RouteDest = ire->ire_addr_v6;
10912 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
10913 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
10914 	re->ipv6RouteIfIndex.o_length = 0;
10915 	ill = ire->ire_ill;
10916 	if (ill != NULL) {
10917 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
10918 		re->ipv6RouteIfIndex.o_length =
10919 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
10920 	}
10921 
10922 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
10923 
10924 	mutex_enter(&ire->ire_lock);
10925 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
10926 	mutex_exit(&ire->ire_lock);
10927 
10928 	/* remote(4), local(3), or discard(2) */
10929 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10930 		re->ipv6RouteType = 2;
10931 	else if (ire->ire_type & IRE_ONLINK)
10932 		re->ipv6RouteType = 3;
10933 	else
10934 		re->ipv6RouteType = 4;
10935 
10936 	re->ipv6RouteProtocol	= -1;
10937 	re->ipv6RoutePolicy	= 0;
10938 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
10939 	re->ipv6RouteNextHopRDI	= 0;
10940 	re->ipv6RouteWeight	= 0;
10941 	re->ipv6RouteMetric	= 0;
10942 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10943 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
10944 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10945 
10946 	re->ipv6RouteInfo.re_frag_flag	= 0;
10947 	re->ipv6RouteInfo.re_rtt	= 0;
10948 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
10949 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10950 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10951 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
10952 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
10953 
10954 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10955 	if (ire->ire_type & IRE_INTERFACE) {
10956 		ire_t *child;
10957 
10958 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10959 		child = ire->ire_dep_children;
10960 		while (child != NULL) {
10961 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
10962 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10963 			child = child->ire_dep_sib_next;
10964 		}
10965 		rw_exit(&ipst->ips_ire_dep_lock);
10966 	}
10967 	if (ire->ire_flags & RTF_DYNAMIC) {
10968 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10969 	} else {
10970 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
10971 	}
10972 
10973 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10974 	    (char *)re, (int)sizeof (*re))) {
10975 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
10976 		    (uint_t)sizeof (*re)));
10977 	}
10978 
10979 	if (gc != NULL) {
10980 		iaes.iae_routeidx = ird->ird_idx;
10981 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10982 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10983 
10984 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10985 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10986 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
10987 			    "bytes\n", (uint_t)sizeof (iaes)));
10988 		}
10989 	}
10990 
10991 	/* bump route index for next pass */
10992 	ird->ird_idx++;
10993 
10994 	kmem_free(re, sizeof (*re));
10995 	if (gcgrp != NULL)
10996 		rw_exit(&gcgrp->gcgrp_rwlock);
10997 }
10998 
10999 /*
11000  * ncec_walk routine to create ipv6NetToMediaEntryTable
11001  */
11002 static int
11003 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11004 {
11005 	ill_t				*ill;
11006 	mib2_ipv6NetToMediaEntry_t	ntme;
11007 
11008 	ill = ncec->ncec_ill;
11009 	/* skip arpce entries, and loopback ncec entries */
11010 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11011 		return (0);
11012 	/*
11013 	 * Neighbor cache entry attached to IRE with on-link
11014 	 * destination.
11015 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11016 	 */
11017 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11018 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11019 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11020 	if (ncec->ncec_lladdr != NULL) {
11021 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11022 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11023 	}
11024 	/*
11025 	 * Note: Returns ND_* states. Should be:
11026 	 * reachable(1), stale(2), delay(3), probe(4),
11027 	 * invalid(5), unknown(6)
11028 	 */
11029 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11030 	ntme.ipv6NetToMediaLastUpdated = 0;
11031 
11032 	/* other(1), dynamic(2), static(3), local(4) */
11033 	if (NCE_MYADDR(ncec)) {
11034 		ntme.ipv6NetToMediaType = 4;
11035 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11036 		ntme.ipv6NetToMediaType = 1; /* proxy */
11037 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11038 		ntme.ipv6NetToMediaType = 3;
11039 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11040 		ntme.ipv6NetToMediaType = 1;
11041 	} else {
11042 		ntme.ipv6NetToMediaType = 2;
11043 	}
11044 
11045 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11046 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11047 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11048 		    (uint_t)sizeof (ntme)));
11049 	}
11050 	return (0);
11051 }
11052 
11053 int
11054 nce2ace(ncec_t *ncec)
11055 {
11056 	int flags = 0;
11057 
11058 	if (NCE_ISREACHABLE(ncec))
11059 		flags |= ACE_F_RESOLVED;
11060 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11061 		flags |= ACE_F_AUTHORITY;
11062 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11063 		flags |= ACE_F_PUBLISH;
11064 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11065 		flags |= ACE_F_PERMANENT;
11066 	if (NCE_MYADDR(ncec))
11067 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11068 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11069 		flags |= ACE_F_UNVERIFIED;
11070 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11071 		flags |= ACE_F_AUTHORITY;
11072 	if (ncec->ncec_flags & NCE_F_DELAYED)
11073 		flags |= ACE_F_DELAYED;
11074 	return (flags);
11075 }
11076 
11077 /*
11078  * ncec_walk routine to create ipNetToMediaEntryTable
11079  */
11080 static int
11081 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11082 {
11083 	ill_t				*ill;
11084 	mib2_ipNetToMediaEntry_t	ntme;
11085 	const char			*name = "unknown";
11086 	ipaddr_t			ncec_addr;
11087 
11088 	ill = ncec->ncec_ill;
11089 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11090 	    ill->ill_net_type == IRE_LOOPBACK)
11091 		return (0);
11092 
11093 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11094 	name = ill->ill_name;
11095 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11096 	if (NCE_MYADDR(ncec)) {
11097 		ntme.ipNetToMediaType = 4;
11098 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11099 		ntme.ipNetToMediaType = 1;
11100 	} else {
11101 		ntme.ipNetToMediaType = 3;
11102 	}
11103 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11104 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11105 	    ntme.ipNetToMediaIfIndex.o_length);
11106 
11107 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11108 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11109 
11110 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11111 	ncec_addr = INADDR_BROADCAST;
11112 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11113 	    sizeof (ncec_addr));
11114 	/*
11115 	 * map all the flags to the ACE counterpart.
11116 	 */
11117 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11118 
11119 	ntme.ipNetToMediaPhysAddress.o_length =
11120 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11121 
11122 	if (!NCE_ISREACHABLE(ncec))
11123 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11124 	else {
11125 		if (ncec->ncec_lladdr != NULL) {
11126 			bcopy(ncec->ncec_lladdr,
11127 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11128 			    ntme.ipNetToMediaPhysAddress.o_length);
11129 		}
11130 	}
11131 
11132 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11133 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11134 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11135 		    (uint_t)sizeof (ntme)));
11136 	}
11137 	return (0);
11138 }
11139 
11140 /*
11141  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11142  */
11143 /* ARGSUSED */
11144 int
11145 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11146 {
11147 	switch (level) {
11148 	case MIB2_IP:
11149 	case MIB2_ICMP:
11150 		switch (name) {
11151 		default:
11152 			break;
11153 		}
11154 		return (1);
11155 	default:
11156 		return (1);
11157 	}
11158 }
11159 
11160 /*
11161  * When there exists both a 64- and 32-bit counter of a particular type
11162  * (i.e., InReceives), only the 64-bit counters are added.
11163  */
11164 void
11165 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11166 {
11167 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11168 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11169 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11170 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11171 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11172 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11173 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11174 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11175 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11176 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11177 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11178 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11179 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11180 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11181 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11182 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11183 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11184 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11185 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11186 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11187 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11188 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11189 	    o2->ipIfStatsInWrongIPVersion);
11190 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11191 	    o2->ipIfStatsInWrongIPVersion);
11192 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11193 	    o2->ipIfStatsOutSwitchIPVersion);
11194 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11195 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11196 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11197 	    o2->ipIfStatsHCInForwDatagrams);
11198 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11199 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11200 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11201 	    o2->ipIfStatsHCOutForwDatagrams);
11202 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11203 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11204 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11205 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11206 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11207 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11208 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11209 	    o2->ipIfStatsHCOutMcastOctets);
11210 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11211 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11212 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11213 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11214 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11215 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11216 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11217 }
11218 
11219 void
11220 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11221 {
11222 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11223 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11224 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11225 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11226 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11227 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11228 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11229 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11230 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11231 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11232 	    o2->ipv6IfIcmpInRouterSolicits);
11233 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11234 	    o2->ipv6IfIcmpInRouterAdvertisements);
11235 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11236 	    o2->ipv6IfIcmpInNeighborSolicits);
11237 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11238 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11239 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11240 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11241 	    o2->ipv6IfIcmpInGroupMembQueries);
11242 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11243 	    o2->ipv6IfIcmpInGroupMembResponses);
11244 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11245 	    o2->ipv6IfIcmpInGroupMembReductions);
11246 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11247 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11248 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11249 	    o2->ipv6IfIcmpOutDestUnreachs);
11250 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11251 	    o2->ipv6IfIcmpOutAdminProhibs);
11252 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11253 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11254 	    o2->ipv6IfIcmpOutParmProblems);
11255 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11256 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11257 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11258 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11259 	    o2->ipv6IfIcmpOutRouterSolicits);
11260 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11261 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11262 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11263 	    o2->ipv6IfIcmpOutNeighborSolicits);
11264 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11265 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11266 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11267 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11268 	    o2->ipv6IfIcmpOutGroupMembQueries);
11269 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11270 	    o2->ipv6IfIcmpOutGroupMembResponses);
11271 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11272 	    o2->ipv6IfIcmpOutGroupMembReductions);
11273 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11274 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11275 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11276 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11277 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11278 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11279 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11280 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11281 	    o2->ipv6IfIcmpInGroupMembTotal);
11282 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11283 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11284 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11285 	    o2->ipv6IfIcmpInGroupMembBadReports);
11286 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11287 	    o2->ipv6IfIcmpInGroupMembOurReports);
11288 }
11289 
11290 /*
11291  * Called before the options are updated to check if this packet will
11292  * be source routed from here.
11293  * This routine assumes that the options are well formed i.e. that they
11294  * have already been checked.
11295  */
11296 boolean_t
11297 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11298 {
11299 	ipoptp_t	opts;
11300 	uchar_t		*opt;
11301 	uint8_t		optval;
11302 	uint8_t		optlen;
11303 	ipaddr_t	dst;
11304 
11305 	if (IS_SIMPLE_IPH(ipha)) {
11306 		ip2dbg(("not source routed\n"));
11307 		return (B_FALSE);
11308 	}
11309 	dst = ipha->ipha_dst;
11310 	for (optval = ipoptp_first(&opts, ipha);
11311 	    optval != IPOPT_EOL;
11312 	    optval = ipoptp_next(&opts)) {
11313 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11314 		opt = opts.ipoptp_cur;
11315 		optlen = opts.ipoptp_len;
11316 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11317 		    optval, optlen));
11318 		switch (optval) {
11319 			uint32_t off;
11320 		case IPOPT_SSRR:
11321 		case IPOPT_LSRR:
11322 			/*
11323 			 * If dst is one of our addresses and there are some
11324 			 * entries left in the source route return (true).
11325 			 */
11326 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11327 				ip2dbg(("ip_source_routed: not next"
11328 				    " source route 0x%x\n",
11329 				    ntohl(dst)));
11330 				return (B_FALSE);
11331 			}
11332 			off = opt[IPOPT_OFFSET];
11333 			off--;
11334 			if (optlen < IP_ADDR_LEN ||
11335 			    off > optlen - IP_ADDR_LEN) {
11336 				/* End of source route */
11337 				ip1dbg(("ip_source_routed: end of SR\n"));
11338 				return (B_FALSE);
11339 			}
11340 			return (B_TRUE);
11341 		}
11342 	}
11343 	ip2dbg(("not source routed\n"));
11344 	return (B_FALSE);
11345 }
11346 
11347 /*
11348  * ip_unbind is called by the transports to remove a conn from
11349  * the fanout table.
11350  */
11351 void
11352 ip_unbind(conn_t *connp)
11353 {
11354 
11355 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11356 
11357 	if (is_system_labeled() && connp->conn_anon_port) {
11358 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11359 		    connp->conn_mlp_type, connp->conn_proto,
11360 		    ntohs(connp->conn_lport), B_FALSE);
11361 		connp->conn_anon_port = 0;
11362 	}
11363 	connp->conn_mlp_type = mlptSingle;
11364 
11365 	ipcl_hash_remove(connp);
11366 }
11367 
11368 /*
11369  * Used for deciding the MSS size for the upper layer. Thus
11370  * we need to check the outbound policy values in the conn.
11371  */
11372 int
11373 conn_ipsec_length(conn_t *connp)
11374 {
11375 	ipsec_latch_t *ipl;
11376 
11377 	ipl = connp->conn_latch;
11378 	if (ipl == NULL)
11379 		return (0);
11380 
11381 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11382 		return (0);
11383 
11384 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11385 }
11386 
11387 /*
11388  * Returns an estimate of the IPsec headers size. This is used if
11389  * we don't want to call into IPsec to get the exact size.
11390  */
11391 int
11392 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11393 {
11394 	ipsec_action_t *a;
11395 
11396 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11397 		return (0);
11398 
11399 	a = ixa->ixa_ipsec_action;
11400 	if (a == NULL) {
11401 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11402 		a = ixa->ixa_ipsec_policy->ipsp_act;
11403 	}
11404 	ASSERT(a != NULL);
11405 
11406 	return (a->ipa_ovhd);
11407 }
11408 
11409 /*
11410  * If there are any source route options, return the true final
11411  * destination. Otherwise, return the destination.
11412  */
11413 ipaddr_t
11414 ip_get_dst(ipha_t *ipha)
11415 {
11416 	ipoptp_t	opts;
11417 	uchar_t		*opt;
11418 	uint8_t		optval;
11419 	uint8_t		optlen;
11420 	ipaddr_t	dst;
11421 	uint32_t off;
11422 
11423 	dst = ipha->ipha_dst;
11424 
11425 	if (IS_SIMPLE_IPH(ipha))
11426 		return (dst);
11427 
11428 	for (optval = ipoptp_first(&opts, ipha);
11429 	    optval != IPOPT_EOL;
11430 	    optval = ipoptp_next(&opts)) {
11431 		opt = opts.ipoptp_cur;
11432 		optlen = opts.ipoptp_len;
11433 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11434 		switch (optval) {
11435 		case IPOPT_SSRR:
11436 		case IPOPT_LSRR:
11437 			off = opt[IPOPT_OFFSET];
11438 			/*
11439 			 * If one of the conditions is true, it means
11440 			 * end of options and dst already has the right
11441 			 * value.
11442 			 */
11443 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11444 				off = optlen - IP_ADDR_LEN;
11445 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11446 			}
11447 			return (dst);
11448 		default:
11449 			break;
11450 		}
11451 	}
11452 
11453 	return (dst);
11454 }
11455 
11456 /*
11457  * Outbound IP fragmentation routine.
11458  * Assumes the caller has checked whether or not fragmentation should
11459  * be allowed. Here we copy the DF bit from the header to all the generated
11460  * fragments.
11461  */
11462 int
11463 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11464     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11465     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11466 {
11467 	int		i1;
11468 	int		hdr_len;
11469 	mblk_t		*hdr_mp;
11470 	ipha_t		*ipha;
11471 	int		ip_data_end;
11472 	int		len;
11473 	mblk_t		*mp = mp_orig;
11474 	int		offset;
11475 	ill_t		*ill = nce->nce_ill;
11476 	ip_stack_t	*ipst = ill->ill_ipst;
11477 	mblk_t		*carve_mp;
11478 	uint32_t	frag_flag;
11479 	uint_t		priority = mp->b_band;
11480 	int		error = 0;
11481 
11482 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11483 
11484 	if (pkt_len != msgdsize(mp)) {
11485 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11486 		    pkt_len, msgdsize(mp)));
11487 		freemsg(mp);
11488 		return (EINVAL);
11489 	}
11490 
11491 	if (max_frag == 0) {
11492 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11493 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11494 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11495 		freemsg(mp);
11496 		return (EINVAL);
11497 	}
11498 
11499 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11500 	ipha = (ipha_t *)mp->b_rptr;
11501 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11502 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11503 
11504 	/*
11505 	 * Establish the starting offset.  May not be zero if we are fragging
11506 	 * a fragment that is being forwarded.
11507 	 */
11508 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11509 
11510 	/* TODO why is this test needed? */
11511 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11512 		/* TODO: notify ulp somehow */
11513 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11514 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11515 		freemsg(mp);
11516 		return (EINVAL);
11517 	}
11518 
11519 	hdr_len = IPH_HDR_LENGTH(ipha);
11520 	ipha->ipha_hdr_checksum = 0;
11521 
11522 	/*
11523 	 * Establish the number of bytes maximum per frag, after putting
11524 	 * in the header.
11525 	 */
11526 	len = (max_frag - hdr_len) & ~7;
11527 
11528 	/* Get a copy of the header for the trailing frags */
11529 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11530 	    mp);
11531 	if (hdr_mp == NULL) {
11532 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11533 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11534 		freemsg(mp);
11535 		return (ENOBUFS);
11536 	}
11537 
11538 	/* Store the starting offset, with the MoreFrags flag. */
11539 	i1 = offset | IPH_MF | frag_flag;
11540 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11541 
11542 	/* Establish the ending byte offset, based on the starting offset. */
11543 	offset <<= 3;
11544 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11545 
11546 	/* Store the length of the first fragment in the IP header. */
11547 	i1 = len + hdr_len;
11548 	ASSERT(i1 <= IP_MAXPACKET);
11549 	ipha->ipha_length = htons((uint16_t)i1);
11550 
11551 	/*
11552 	 * Compute the IP header checksum for the first frag.  We have to
11553 	 * watch out that we stop at the end of the header.
11554 	 */
11555 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11556 
11557 	/*
11558 	 * Now carve off the first frag.  Note that this will include the
11559 	 * original IP header.
11560 	 */
11561 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11562 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11563 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11564 		freeb(hdr_mp);
11565 		freemsg(mp_orig);
11566 		return (ENOBUFS);
11567 	}
11568 
11569 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11570 
11571 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11572 	    ixa_cookie);
11573 	if (error != 0 && error != EWOULDBLOCK) {
11574 		/* No point in sending the other fragments */
11575 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11576 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11577 		freeb(hdr_mp);
11578 		freemsg(mp_orig);
11579 		return (error);
11580 	}
11581 
11582 	/* No need to redo state machine in loop */
11583 	ixaflags &= ~IXAF_REACH_CONF;
11584 
11585 	/* Advance the offset to the second frag starting point. */
11586 	offset += len;
11587 	/*
11588 	 * Update hdr_len from the copied header - there might be less options
11589 	 * in the later fragments.
11590 	 */
11591 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11592 	/* Loop until done. */
11593 	for (;;) {
11594 		uint16_t	offset_and_flags;
11595 		uint16_t	ip_len;
11596 
11597 		if (ip_data_end - offset > len) {
11598 			/*
11599 			 * Carve off the appropriate amount from the original
11600 			 * datagram.
11601 			 */
11602 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11603 				mp = NULL;
11604 				break;
11605 			}
11606 			/*
11607 			 * More frags after this one.  Get another copy
11608 			 * of the header.
11609 			 */
11610 			if (carve_mp->b_datap->db_ref == 1 &&
11611 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11612 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11613 				/* Inline IP header */
11614 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11615 				    hdr_mp->b_rptr;
11616 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11617 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11618 				mp = carve_mp;
11619 			} else {
11620 				if (!(mp = copyb(hdr_mp))) {
11621 					freemsg(carve_mp);
11622 					break;
11623 				}
11624 				/* Get priority marking, if any. */
11625 				mp->b_band = priority;
11626 				mp->b_cont = carve_mp;
11627 			}
11628 			ipha = (ipha_t *)mp->b_rptr;
11629 			offset_and_flags = IPH_MF;
11630 		} else {
11631 			/*
11632 			 * Last frag.  Consume the header. Set len to
11633 			 * the length of this last piece.
11634 			 */
11635 			len = ip_data_end - offset;
11636 
11637 			/*
11638 			 * Carve off the appropriate amount from the original
11639 			 * datagram.
11640 			 */
11641 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11642 				mp = NULL;
11643 				break;
11644 			}
11645 			if (carve_mp->b_datap->db_ref == 1 &&
11646 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11647 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11648 				/* Inline IP header */
11649 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11650 				    hdr_mp->b_rptr;
11651 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11652 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11653 				mp = carve_mp;
11654 				freeb(hdr_mp);
11655 				hdr_mp = mp;
11656 			} else {
11657 				mp = hdr_mp;
11658 				/* Get priority marking, if any. */
11659 				mp->b_band = priority;
11660 				mp->b_cont = carve_mp;
11661 			}
11662 			ipha = (ipha_t *)mp->b_rptr;
11663 			/* A frag of a frag might have IPH_MF non-zero */
11664 			offset_and_flags =
11665 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11666 			    IPH_MF;
11667 		}
11668 		offset_and_flags |= (uint16_t)(offset >> 3);
11669 		offset_and_flags |= (uint16_t)frag_flag;
11670 		/* Store the offset and flags in the IP header. */
11671 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11672 
11673 		/* Store the length in the IP header. */
11674 		ip_len = (uint16_t)(len + hdr_len);
11675 		ipha->ipha_length = htons(ip_len);
11676 
11677 		/*
11678 		 * Set the IP header checksum.	Note that mp is just
11679 		 * the header, so this is easy to pass to ip_csum.
11680 		 */
11681 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11682 
11683 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11684 
11685 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11686 		    nolzid, ixa_cookie);
11687 		/* All done if we just consumed the hdr_mp. */
11688 		if (mp == hdr_mp) {
11689 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11690 			return (error);
11691 		}
11692 		if (error != 0 && error != EWOULDBLOCK) {
11693 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11694 			    mblk_t *, hdr_mp);
11695 			/* No point in sending the other fragments */
11696 			break;
11697 		}
11698 
11699 		/* Otherwise, advance and loop. */
11700 		offset += len;
11701 	}
11702 	/* Clean up following allocation failure. */
11703 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11704 	ip_drop_output("FragFails: loop ended", NULL, ill);
11705 	if (mp != hdr_mp)
11706 		freeb(hdr_mp);
11707 	if (mp != mp_orig)
11708 		freemsg(mp_orig);
11709 	return (error);
11710 }
11711 
11712 /*
11713  * Copy the header plus those options which have the copy bit set
11714  */
11715 static mblk_t *
11716 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11717     mblk_t *src)
11718 {
11719 	mblk_t	*mp;
11720 	uchar_t	*up;
11721 
11722 	/*
11723 	 * Quick check if we need to look for options without the copy bit
11724 	 * set
11725 	 */
11726 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11727 	if (!mp)
11728 		return (mp);
11729 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11730 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11731 		bcopy(rptr, mp->b_rptr, hdr_len);
11732 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11733 		return (mp);
11734 	}
11735 	up  = mp->b_rptr;
11736 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11737 	up += IP_SIMPLE_HDR_LENGTH;
11738 	rptr += IP_SIMPLE_HDR_LENGTH;
11739 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11740 	while (hdr_len > 0) {
11741 		uint32_t optval;
11742 		uint32_t optlen;
11743 
11744 		optval = *rptr;
11745 		if (optval == IPOPT_EOL)
11746 			break;
11747 		if (optval == IPOPT_NOP)
11748 			optlen = 1;
11749 		else
11750 			optlen = rptr[1];
11751 		if (optval & IPOPT_COPY) {
11752 			bcopy(rptr, up, optlen);
11753 			up += optlen;
11754 		}
11755 		rptr += optlen;
11756 		hdr_len -= optlen;
11757 	}
11758 	/*
11759 	 * Make sure that we drop an even number of words by filling
11760 	 * with EOL to the next word boundary.
11761 	 */
11762 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11763 	    hdr_len & 0x3; hdr_len++)
11764 		*up++ = IPOPT_EOL;
11765 	mp->b_wptr = up;
11766 	/* Update header length */
11767 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11768 	return (mp);
11769 }
11770 
11771 /*
11772  * Update any source route, record route, or timestamp options when
11773  * sending a packet back to ourselves.
11774  * Check that we are at end of strict source route.
11775  * The options have been sanity checked by ip_output_options().
11776  */
11777 void
11778 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11779 {
11780 	ipoptp_t	opts;
11781 	uchar_t		*opt;
11782 	uint8_t		optval;
11783 	uint8_t		optlen;
11784 	ipaddr_t	dst;
11785 	uint32_t	ts;
11786 	timestruc_t	now;
11787 
11788 	for (optval = ipoptp_first(&opts, ipha);
11789 	    optval != IPOPT_EOL;
11790 	    optval = ipoptp_next(&opts)) {
11791 		opt = opts.ipoptp_cur;
11792 		optlen = opts.ipoptp_len;
11793 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11794 		switch (optval) {
11795 			uint32_t off;
11796 		case IPOPT_SSRR:
11797 		case IPOPT_LSRR:
11798 			off = opt[IPOPT_OFFSET];
11799 			off--;
11800 			if (optlen < IP_ADDR_LEN ||
11801 			    off > optlen - IP_ADDR_LEN) {
11802 				/* End of source route */
11803 				break;
11804 			}
11805 			/*
11806 			 * This will only happen if two consecutive entries
11807 			 * in the source route contains our address or if
11808 			 * it is a packet with a loose source route which
11809 			 * reaches us before consuming the whole source route
11810 			 */
11811 
11812 			if (optval == IPOPT_SSRR) {
11813 				return;
11814 			}
11815 			/*
11816 			 * Hack: instead of dropping the packet truncate the
11817 			 * source route to what has been used by filling the
11818 			 * rest with IPOPT_NOP.
11819 			 */
11820 			opt[IPOPT_OLEN] = (uint8_t)off;
11821 			while (off < optlen) {
11822 				opt[off++] = IPOPT_NOP;
11823 			}
11824 			break;
11825 		case IPOPT_RR:
11826 			off = opt[IPOPT_OFFSET];
11827 			off--;
11828 			if (optlen < IP_ADDR_LEN ||
11829 			    off > optlen - IP_ADDR_LEN) {
11830 				/* No more room - ignore */
11831 				ip1dbg((
11832 				    "ip_output_local_options: end of RR\n"));
11833 				break;
11834 			}
11835 			dst = htonl(INADDR_LOOPBACK);
11836 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11837 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11838 			break;
11839 		case IPOPT_TS:
11840 			/* Insert timestamp if there is romm */
11841 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11842 			case IPOPT_TS_TSONLY:
11843 				off = IPOPT_TS_TIMELEN;
11844 				break;
11845 			case IPOPT_TS_PRESPEC:
11846 			case IPOPT_TS_PRESPEC_RFC791:
11847 				/* Verify that the address matched */
11848 				off = opt[IPOPT_OFFSET] - 1;
11849 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
11850 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11851 					/* Not for us */
11852 					break;
11853 				}
11854 				/* FALLTHRU */
11855 			case IPOPT_TS_TSANDADDR:
11856 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
11857 				break;
11858 			default:
11859 				/*
11860 				 * ip_*put_options should have already
11861 				 * dropped this packet.
11862 				 */
11863 				cmn_err(CE_PANIC, "ip_output_local_options: "
11864 				    "unknown IT - bug in ip_output_options?\n");
11865 				return;	/* Keep "lint" happy */
11866 			}
11867 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
11868 				/* Increase overflow counter */
11869 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
11870 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
11871 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
11872 				    (off << 4);
11873 				break;
11874 			}
11875 			off = opt[IPOPT_OFFSET] - 1;
11876 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11877 			case IPOPT_TS_PRESPEC:
11878 			case IPOPT_TS_PRESPEC_RFC791:
11879 			case IPOPT_TS_TSANDADDR:
11880 				dst = htonl(INADDR_LOOPBACK);
11881 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11882 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11883 				/* FALLTHRU */
11884 			case IPOPT_TS_TSONLY:
11885 				off = opt[IPOPT_OFFSET] - 1;
11886 				/* Compute # of milliseconds since midnight */
11887 				gethrestime(&now);
11888 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
11889 				    now.tv_nsec / (NANOSEC / MILLISEC);
11890 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
11891 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
11892 				break;
11893 			}
11894 			break;
11895 		}
11896 	}
11897 }
11898 
11899 /*
11900  * Prepend an M_DATA fastpath header, and if none present prepend a
11901  * DL_UNITDATA_REQ. Frees the mblk on failure.
11902  *
11903  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
11904  * If there is a change to them, the nce will be deleted (condemned) and
11905  * a new nce_t will be created when packets are sent. Thus we need no locks
11906  * to access those fields.
11907  *
11908  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
11909  * we place b_band in dl_priority.dl_max.
11910  */
11911 static mblk_t *
11912 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
11913 {
11914 	uint_t	hlen;
11915 	mblk_t *mp1;
11916 	uint_t	priority;
11917 	uchar_t *rptr;
11918 
11919 	rptr = mp->b_rptr;
11920 
11921 	ASSERT(DB_TYPE(mp) == M_DATA);
11922 	priority = mp->b_band;
11923 
11924 	ASSERT(nce != NULL);
11925 	if ((mp1 = nce->nce_fp_mp) != NULL) {
11926 		hlen = MBLKL(mp1);
11927 		/*
11928 		 * Check if we have enough room to prepend fastpath
11929 		 * header
11930 		 */
11931 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
11932 			rptr -= hlen;
11933 			bcopy(mp1->b_rptr, rptr, hlen);
11934 			/*
11935 			 * Set the b_rptr to the start of the link layer
11936 			 * header
11937 			 */
11938 			mp->b_rptr = rptr;
11939 			return (mp);
11940 		}
11941 		mp1 = copyb(mp1);
11942 		if (mp1 == NULL) {
11943 			ill_t *ill = nce->nce_ill;
11944 
11945 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
11946 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
11947 			freemsg(mp);
11948 			return (NULL);
11949 		}
11950 		mp1->b_band = priority;
11951 		mp1->b_cont = mp;
11952 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
11953 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
11954 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
11955 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
11956 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
11957 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
11958 		/*
11959 		 * XXX disable ICK_VALID and compute checksum
11960 		 * here; can happen if nce_fp_mp changes and
11961 		 * it can't be copied now due to insufficient
11962 		 * space. (unlikely, fp mp can change, but it
11963 		 * does not increase in length)
11964 		 */
11965 		return (mp1);
11966 	}
11967 	mp1 = copyb(nce->nce_dlur_mp);
11968 
11969 	if (mp1 == NULL) {
11970 		ill_t *ill = nce->nce_ill;
11971 
11972 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
11973 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
11974 		freemsg(mp);
11975 		return (NULL);
11976 	}
11977 	mp1->b_cont = mp;
11978 	if (priority != 0) {
11979 		mp1->b_band = priority;
11980 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
11981 		    priority;
11982 	}
11983 	return (mp1);
11984 #undef rptr
11985 }
11986 
11987 /*
11988  * Finish the outbound IPsec processing. This function is called from
11989  * ipsec_out_process() if the IPsec packet was processed
11990  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
11991  * asynchronously.
11992  *
11993  * This is common to IPv4 and IPv6.
11994  */
11995 int
11996 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
11997 {
11998 	iaflags_t	ixaflags = ixa->ixa_flags;
11999 	uint_t		pktlen;
12000 
12001 
12002 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12003 	if (ixaflags & IXAF_IS_IPV4) {
12004 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12005 
12006 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12007 		pktlen = ntohs(ipha->ipha_length);
12008 	} else {
12009 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12010 
12011 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12012 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12013 	}
12014 
12015 	/*
12016 	 * We release any hard reference on the SAs here to make
12017 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12018 	 * on the SAs.
12019 	 * If in the future we want the hard latching of the SAs in the
12020 	 * ip_xmit_attr_t then we should remove this.
12021 	 */
12022 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12023 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12024 		ixa->ixa_ipsec_esp_sa = NULL;
12025 	}
12026 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12027 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12028 		ixa->ixa_ipsec_ah_sa = NULL;
12029 	}
12030 
12031 	/* Do we need to fragment? */
12032 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12033 	    pktlen > ixa->ixa_fragsize) {
12034 		if (ixaflags & IXAF_IS_IPV4) {
12035 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12036 			/*
12037 			 * We check for the DF case in ipsec_out_process
12038 			 * hence this only handles the non-DF case.
12039 			 */
12040 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12041 			    pktlen, ixa->ixa_fragsize,
12042 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12043 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12044 			    &ixa->ixa_cookie));
12045 		} else {
12046 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12047 			if (mp == NULL) {
12048 				/* MIB and ip_drop_output already done */
12049 				return (ENOMEM);
12050 			}
12051 			pktlen += sizeof (ip6_frag_t);
12052 			if (pktlen > ixa->ixa_fragsize) {
12053 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12054 				    ixa->ixa_flags, pktlen,
12055 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12056 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12057 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12058 			}
12059 		}
12060 	}
12061 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12062 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12063 	    ixa->ixa_no_loop_zoneid, NULL));
12064 }
12065 
12066 /*
12067  * Finish the inbound IPsec processing. This function is called from
12068  * ipsec_out_process() if the IPsec packet was processed
12069  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12070  * asynchronously.
12071  *
12072  * This is common to IPv4 and IPv6.
12073  */
12074 void
12075 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12076 {
12077 	iaflags_t	iraflags = ira->ira_flags;
12078 
12079 	/* Length might have changed */
12080 	if (iraflags & IRAF_IS_IPV4) {
12081 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12082 
12083 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12084 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12085 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12086 		ira->ira_protocol = ipha->ipha_protocol;
12087 
12088 		ip_fanout_v4(mp, ipha, ira);
12089 	} else {
12090 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12091 		uint8_t		*nexthdrp;
12092 
12093 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12094 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12095 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12096 		    &nexthdrp)) {
12097 			/* Malformed packet */
12098 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12099 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12100 			freemsg(mp);
12101 			return;
12102 		}
12103 		ira->ira_protocol = *nexthdrp;
12104 		ip_fanout_v6(mp, ip6h, ira);
12105 	}
12106 }
12107 
12108 /*
12109  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12110  *
12111  * If this function returns B_TRUE, the requested SA's have been filled
12112  * into the ixa_ipsec_*_sa pointers.
12113  *
12114  * If the function returns B_FALSE, the packet has been "consumed", most
12115  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12116  *
12117  * The SA references created by the protocol-specific "select"
12118  * function will be released in ip_output_post_ipsec.
12119  */
12120 static boolean_t
12121 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12122 {
12123 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12124 	ipsec_policy_t *pp;
12125 	ipsec_action_t *ap;
12126 
12127 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12128 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12129 	    (ixa->ixa_ipsec_action != NULL));
12130 
12131 	ap = ixa->ixa_ipsec_action;
12132 	if (ap == NULL) {
12133 		pp = ixa->ixa_ipsec_policy;
12134 		ASSERT(pp != NULL);
12135 		ap = pp->ipsp_act;
12136 		ASSERT(ap != NULL);
12137 	}
12138 
12139 	/*
12140 	 * We have an action.  now, let's select SA's.
12141 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12142 	 * be cached in the conn_t.
12143 	 */
12144 	if (ap->ipa_want_esp) {
12145 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12146 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12147 			    IPPROTO_ESP);
12148 		}
12149 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12150 	}
12151 
12152 	if (ap->ipa_want_ah) {
12153 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12154 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12155 			    IPPROTO_AH);
12156 		}
12157 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12158 		/*
12159 		 * The ESP and AH processing order needs to be preserved
12160 		 * when both protocols are required (ESP should be applied
12161 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12162 		 * when both ESP and AH are required, and an AH ACQUIRE
12163 		 * is needed.
12164 		 */
12165 		if (ap->ipa_want_esp && need_ah_acquire)
12166 			need_esp_acquire = B_TRUE;
12167 	}
12168 
12169 	/*
12170 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12171 	 * Release SAs that got referenced, but will not be used until we
12172 	 * acquire _all_ of the SAs we need.
12173 	 */
12174 	if (need_ah_acquire || need_esp_acquire) {
12175 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12176 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12177 			ixa->ixa_ipsec_ah_sa = NULL;
12178 		}
12179 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12180 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12181 			ixa->ixa_ipsec_esp_sa = NULL;
12182 		}
12183 
12184 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12185 		return (B_FALSE);
12186 	}
12187 
12188 	return (B_TRUE);
12189 }
12190 
12191 /*
12192  * Handle IPsec output processing.
12193  * This function is only entered once for a given packet.
12194  * We try to do things synchronously, but if we need to have user-level
12195  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12196  * will be completed
12197  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12198  *  - when asynchronous ESP is done it will do AH
12199  *
12200  * In all cases we come back in ip_output_post_ipsec() to fragment and
12201  * send out the packet.
12202  */
12203 int
12204 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12205 {
12206 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12207 	ip_stack_t	*ipst = ixa->ixa_ipst;
12208 	ipsec_stack_t	*ipss;
12209 	ipsec_policy_t	*pp;
12210 	ipsec_action_t	*ap;
12211 
12212 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12213 
12214 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12215 	    (ixa->ixa_ipsec_action != NULL));
12216 
12217 	ipss = ipst->ips_netstack->netstack_ipsec;
12218 	if (!ipsec_loaded(ipss)) {
12219 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12220 		ip_drop_packet(mp, B_TRUE, ill,
12221 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12222 		    &ipss->ipsec_dropper);
12223 		return (ENOTSUP);
12224 	}
12225 
12226 	ap = ixa->ixa_ipsec_action;
12227 	if (ap == NULL) {
12228 		pp = ixa->ixa_ipsec_policy;
12229 		ASSERT(pp != NULL);
12230 		ap = pp->ipsp_act;
12231 		ASSERT(ap != NULL);
12232 	}
12233 
12234 	/* Handle explicit drop action and bypass. */
12235 	switch (ap->ipa_act.ipa_type) {
12236 	case IPSEC_ACT_DISCARD:
12237 	case IPSEC_ACT_REJECT:
12238 		ip_drop_packet(mp, B_FALSE, ill,
12239 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12240 		return (EHOSTUNREACH);	/* IPsec policy failure */
12241 	case IPSEC_ACT_BYPASS:
12242 		return (ip_output_post_ipsec(mp, ixa));
12243 	}
12244 
12245 	/*
12246 	 * The order of processing is first insert a IP header if needed.
12247 	 * Then insert the ESP header and then the AH header.
12248 	 */
12249 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12250 		/*
12251 		 * First get the outer IP header before sending
12252 		 * it to ESP.
12253 		 */
12254 		ipha_t *oipha, *iipha;
12255 		mblk_t *outer_mp, *inner_mp;
12256 
12257 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12258 			(void) mi_strlog(ill->ill_rq, 0,
12259 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12260 			    "ipsec_out_process: "
12261 			    "Self-Encapsulation failed: Out of memory\n");
12262 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12263 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12264 			freemsg(mp);
12265 			return (ENOBUFS);
12266 		}
12267 		inner_mp = mp;
12268 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12269 		oipha = (ipha_t *)outer_mp->b_rptr;
12270 		iipha = (ipha_t *)inner_mp->b_rptr;
12271 		*oipha = *iipha;
12272 		outer_mp->b_wptr += sizeof (ipha_t);
12273 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12274 		    sizeof (ipha_t));
12275 		oipha->ipha_protocol = IPPROTO_ENCAP;
12276 		oipha->ipha_version_and_hdr_length =
12277 		    IP_SIMPLE_HDR_VERSION;
12278 		oipha->ipha_hdr_checksum = 0;
12279 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12280 		outer_mp->b_cont = inner_mp;
12281 		mp = outer_mp;
12282 
12283 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12284 	}
12285 
12286 	/* If we need to wait for a SA then we can't return any errno */
12287 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12288 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12289 	    !ipsec_out_select_sa(mp, ixa))
12290 		return (0);
12291 
12292 	/*
12293 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12294 	 * to do the heavy lifting.
12295 	 */
12296 	if (ap->ipa_want_esp) {
12297 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12298 
12299 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12300 		if (mp == NULL) {
12301 			/*
12302 			 * Either it failed or is pending. In the former case
12303 			 * ipIfStatsInDiscards was increased.
12304 			 */
12305 			return (0);
12306 		}
12307 	}
12308 
12309 	if (ap->ipa_want_ah) {
12310 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12311 
12312 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12313 		if (mp == NULL) {
12314 			/*
12315 			 * Either it failed or is pending. In the former case
12316 			 * ipIfStatsInDiscards was increased.
12317 			 */
12318 			return (0);
12319 		}
12320 	}
12321 	/*
12322 	 * We are done with IPsec processing. Send it over
12323 	 * the wire.
12324 	 */
12325 	return (ip_output_post_ipsec(mp, ixa));
12326 }
12327 
12328 /*
12329  * ioctls that go through a down/up sequence may need to wait for the down
12330  * to complete. This involves waiting for the ire and ipif refcnts to go down
12331  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12332  */
12333 /* ARGSUSED */
12334 void
12335 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12336 {
12337 	struct iocblk *iocp;
12338 	mblk_t *mp1;
12339 	ip_ioctl_cmd_t *ipip;
12340 	int err;
12341 	sin_t	*sin;
12342 	struct lifreq *lifr;
12343 	struct ifreq *ifr;
12344 
12345 	iocp = (struct iocblk *)mp->b_rptr;
12346 	ASSERT(ipsq != NULL);
12347 	/* Existence of mp1 verified in ip_wput_nondata */
12348 	mp1 = mp->b_cont->b_cont;
12349 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12350 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12351 		/*
12352 		 * Special case where ipx_current_ipif is not set:
12353 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12354 		 * We are here as were not able to complete the operation in
12355 		 * ipif_set_values because we could not become exclusive on
12356 		 * the new ipsq.
12357 		 */
12358 		ill_t *ill = q->q_ptr;
12359 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12360 	}
12361 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12362 
12363 	if (ipip->ipi_cmd_type == IF_CMD) {
12364 		/* This a old style SIOC[GS]IF* command */
12365 		ifr = (struct ifreq *)mp1->b_rptr;
12366 		sin = (sin_t *)&ifr->ifr_addr;
12367 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12368 		/* This a new style SIOC[GS]LIF* command */
12369 		lifr = (struct lifreq *)mp1->b_rptr;
12370 		sin = (sin_t *)&lifr->lifr_addr;
12371 	} else {
12372 		sin = NULL;
12373 	}
12374 
12375 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12376 	    q, mp, ipip, mp1->b_rptr);
12377 
12378 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12379 	    int, ipip->ipi_cmd,
12380 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12381 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12382 
12383 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12384 }
12385 
12386 /*
12387  * ioctl processing
12388  *
12389  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12390  * the ioctl command in the ioctl tables, determines the copyin data size
12391  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12392  *
12393  * ioctl processing then continues when the M_IOCDATA makes its way down to
12394  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12395  * associated 'conn' is refheld till the end of the ioctl and the general
12396  * ioctl processing function ip_process_ioctl() is called to extract the
12397  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12398  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12399  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12400  * is used to extract the ioctl's arguments.
12401  *
12402  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12403  * so goes thru the serialization primitive ipsq_try_enter. Then the
12404  * appropriate function to handle the ioctl is called based on the entry in
12405  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12406  * which also refreleases the 'conn' that was refheld at the start of the
12407  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12408  *
12409  * Many exclusive ioctls go thru an internal down up sequence as part of
12410  * the operation. For example an attempt to change the IP address of an
12411  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12412  * does all the cleanup such as deleting all ires that use this address.
12413  * Then we need to wait till all references to the interface go away.
12414  */
12415 void
12416 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12417 {
12418 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12419 	ip_ioctl_cmd_t *ipip = arg;
12420 	ip_extract_func_t *extract_funcp;
12421 	cmd_info_t ci;
12422 	int err;
12423 	boolean_t entered_ipsq = B_FALSE;
12424 
12425 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12426 
12427 	if (ipip == NULL)
12428 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12429 
12430 	/*
12431 	 * SIOCLIFADDIF needs to go thru a special path since the
12432 	 * ill may not exist yet. This happens in the case of lo0
12433 	 * which is created using this ioctl.
12434 	 */
12435 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12436 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12437 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12438 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12439 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12440 		return;
12441 	}
12442 
12443 	ci.ci_ipif = NULL;
12444 	switch (ipip->ipi_cmd_type) {
12445 	case MISC_CMD:
12446 	case MSFILT_CMD:
12447 		/*
12448 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12449 		 */
12450 		if (ipip->ipi_cmd == IF_UNITSEL) {
12451 			/* ioctl comes down the ill */
12452 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12453 			ipif_refhold(ci.ci_ipif);
12454 		}
12455 		err = 0;
12456 		ci.ci_sin = NULL;
12457 		ci.ci_sin6 = NULL;
12458 		ci.ci_lifr = NULL;
12459 		extract_funcp = NULL;
12460 		break;
12461 
12462 	case IF_CMD:
12463 	case LIF_CMD:
12464 		extract_funcp = ip_extract_lifreq;
12465 		break;
12466 
12467 	case ARP_CMD:
12468 	case XARP_CMD:
12469 		extract_funcp = ip_extract_arpreq;
12470 		break;
12471 
12472 	default:
12473 		ASSERT(0);
12474 	}
12475 
12476 	if (extract_funcp != NULL) {
12477 		err = (*extract_funcp)(q, mp, ipip, &ci);
12478 		if (err != 0) {
12479 			DTRACE_PROBE4(ipif__ioctl,
12480 			    char *, "ip_process_ioctl finish err",
12481 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12482 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12483 			return;
12484 		}
12485 
12486 		/*
12487 		 * All of the extraction functions return a refheld ipif.
12488 		 */
12489 		ASSERT(ci.ci_ipif != NULL);
12490 	}
12491 
12492 	if (!(ipip->ipi_flags & IPI_WR)) {
12493 		/*
12494 		 * A return value of EINPROGRESS means the ioctl is
12495 		 * either queued and waiting for some reason or has
12496 		 * already completed.
12497 		 */
12498 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12499 		    ci.ci_lifr);
12500 		if (ci.ci_ipif != NULL) {
12501 			DTRACE_PROBE4(ipif__ioctl,
12502 			    char *, "ip_process_ioctl finish RD",
12503 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12504 			    ipif_t *, ci.ci_ipif);
12505 			ipif_refrele(ci.ci_ipif);
12506 		} else {
12507 			DTRACE_PROBE4(ipif__ioctl,
12508 			    char *, "ip_process_ioctl finish RD",
12509 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12510 		}
12511 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12512 		return;
12513 	}
12514 
12515 	ASSERT(ci.ci_ipif != NULL);
12516 
12517 	/*
12518 	 * If ipsq is non-NULL, we are already being called exclusively
12519 	 */
12520 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12521 	if (ipsq == NULL) {
12522 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12523 		    NEW_OP, B_TRUE);
12524 		if (ipsq == NULL) {
12525 			ipif_refrele(ci.ci_ipif);
12526 			return;
12527 		}
12528 		entered_ipsq = B_TRUE;
12529 	}
12530 	/*
12531 	 * Release the ipif so that ipif_down and friends that wait for
12532 	 * references to go away are not misled about the current ipif_refcnt
12533 	 * values. We are writer so we can access the ipif even after releasing
12534 	 * the ipif.
12535 	 */
12536 	ipif_refrele(ci.ci_ipif);
12537 
12538 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12539 
12540 	/*
12541 	 * A return value of EINPROGRESS means the ioctl is
12542 	 * either queued and waiting for some reason or has
12543 	 * already completed.
12544 	 */
12545 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12546 
12547 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12548 	    int, ipip->ipi_cmd,
12549 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12550 	    ipif_t *, ci.ci_ipif);
12551 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12552 
12553 	if (entered_ipsq)
12554 		ipsq_exit(ipsq);
12555 }
12556 
12557 /*
12558  * Complete the ioctl. Typically ioctls use the mi package and need to
12559  * do mi_copyout/mi_copy_done.
12560  */
12561 void
12562 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12563 {
12564 	conn_t	*connp = NULL;
12565 
12566 	if (err == EINPROGRESS)
12567 		return;
12568 
12569 	if (CONN_Q(q)) {
12570 		connp = Q_TO_CONN(q);
12571 		ASSERT(connp->conn_ref >= 2);
12572 	}
12573 
12574 	switch (mode) {
12575 	case COPYOUT:
12576 		if (err == 0)
12577 			mi_copyout(q, mp);
12578 		else
12579 			mi_copy_done(q, mp, err);
12580 		break;
12581 
12582 	case NO_COPYOUT:
12583 		mi_copy_done(q, mp, err);
12584 		break;
12585 
12586 	default:
12587 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12588 		break;
12589 	}
12590 
12591 	/*
12592 	 * The conn refhold and ioctlref placed on the conn at the start of the
12593 	 * ioctl are released here.
12594 	 */
12595 	if (connp != NULL) {
12596 		CONN_DEC_IOCTLREF(connp);
12597 		CONN_OPER_PENDING_DONE(connp);
12598 	}
12599 
12600 	if (ipsq != NULL)
12601 		ipsq_current_finish(ipsq);
12602 }
12603 
12604 /* Handles all non data messages */
12605 void
12606 ip_wput_nondata(queue_t *q, mblk_t *mp)
12607 {
12608 	mblk_t		*mp1;
12609 	struct iocblk	*iocp;
12610 	ip_ioctl_cmd_t	*ipip;
12611 	conn_t		*connp;
12612 	cred_t		*cr;
12613 	char		*proto_str;
12614 
12615 	if (CONN_Q(q))
12616 		connp = Q_TO_CONN(q);
12617 	else
12618 		connp = NULL;
12619 
12620 	switch (DB_TYPE(mp)) {
12621 	case M_IOCTL:
12622 		/*
12623 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12624 		 * will arrange to copy in associated control structures.
12625 		 */
12626 		ip_sioctl_copyin_setup(q, mp);
12627 		return;
12628 	case M_IOCDATA:
12629 		/*
12630 		 * Ensure that this is associated with one of our trans-
12631 		 * parent ioctls.  If it's not ours, discard it if we're
12632 		 * running as a driver, or pass it on if we're a module.
12633 		 */
12634 		iocp = (struct iocblk *)mp->b_rptr;
12635 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12636 		if (ipip == NULL) {
12637 			if (q->q_next == NULL) {
12638 				goto nak;
12639 			} else {
12640 				putnext(q, mp);
12641 			}
12642 			return;
12643 		}
12644 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12645 			/*
12646 			 * The ioctl is one we recognise, but is not consumed
12647 			 * by IP as a module and we are a module, so we drop
12648 			 */
12649 			goto nak;
12650 		}
12651 
12652 		/* IOCTL continuation following copyin or copyout. */
12653 		if (mi_copy_state(q, mp, NULL) == -1) {
12654 			/*
12655 			 * The copy operation failed.  mi_copy_state already
12656 			 * cleaned up, so we're out of here.
12657 			 */
12658 			return;
12659 		}
12660 		/*
12661 		 * If we just completed a copy in, we become writer and
12662 		 * continue processing in ip_sioctl_copyin_done.  If it
12663 		 * was a copy out, we call mi_copyout again.  If there is
12664 		 * nothing more to copy out, it will complete the IOCTL.
12665 		 */
12666 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12667 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12668 				mi_copy_done(q, mp, EPROTO);
12669 				return;
12670 			}
12671 			/*
12672 			 * Check for cases that need more copying.  A return
12673 			 * value of 0 means a second copyin has been started,
12674 			 * so we return; a return value of 1 means no more
12675 			 * copying is needed, so we continue.
12676 			 */
12677 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12678 			    MI_COPY_COUNT(mp) == 1) {
12679 				if (ip_copyin_msfilter(q, mp) == 0)
12680 					return;
12681 			}
12682 			/*
12683 			 * Refhold the conn, till the ioctl completes. This is
12684 			 * needed in case the ioctl ends up in the pending mp
12685 			 * list. Every mp in the ipx_pending_mp list must have
12686 			 * a refhold on the conn to resume processing. The
12687 			 * refhold is released when the ioctl completes
12688 			 * (whether normally or abnormally). An ioctlref is also
12689 			 * placed on the conn to prevent TCP from removing the
12690 			 * queue needed to send the ioctl reply back.
12691 			 * In all cases ip_ioctl_finish is called to finish
12692 			 * the ioctl and release the refholds.
12693 			 */
12694 			if (connp != NULL) {
12695 				/* This is not a reentry */
12696 				CONN_INC_REF(connp);
12697 				CONN_INC_IOCTLREF(connp);
12698 			} else {
12699 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12700 					mi_copy_done(q, mp, EINVAL);
12701 					return;
12702 				}
12703 			}
12704 
12705 			ip_process_ioctl(NULL, q, mp, ipip);
12706 
12707 		} else {
12708 			mi_copyout(q, mp);
12709 		}
12710 		return;
12711 
12712 	case M_IOCNAK:
12713 		/*
12714 		 * The only way we could get here is if a resolver didn't like
12715 		 * an IOCTL we sent it.	 This shouldn't happen.
12716 		 */
12717 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12718 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12719 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12720 		freemsg(mp);
12721 		return;
12722 	case M_IOCACK:
12723 		/* /dev/ip shouldn't see this */
12724 		goto nak;
12725 	case M_FLUSH:
12726 		if (*mp->b_rptr & FLUSHW)
12727 			flushq(q, FLUSHALL);
12728 		if (q->q_next) {
12729 			putnext(q, mp);
12730 			return;
12731 		}
12732 		if (*mp->b_rptr & FLUSHR) {
12733 			*mp->b_rptr &= ~FLUSHW;
12734 			qreply(q, mp);
12735 			return;
12736 		}
12737 		freemsg(mp);
12738 		return;
12739 	case M_CTL:
12740 		break;
12741 	case M_PROTO:
12742 	case M_PCPROTO:
12743 		/*
12744 		 * The only PROTO messages we expect are SNMP-related.
12745 		 */
12746 		switch (((union T_primitives *)mp->b_rptr)->type) {
12747 		case T_SVR4_OPTMGMT_REQ:
12748 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12749 			    "flags %x\n",
12750 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12751 
12752 			if (connp == NULL) {
12753 				proto_str = "T_SVR4_OPTMGMT_REQ";
12754 				goto protonak;
12755 			}
12756 
12757 			/*
12758 			 * All Solaris components should pass a db_credp
12759 			 * for this TPI message, hence we ASSERT.
12760 			 * But in case there is some other M_PROTO that looks
12761 			 * like a TPI message sent by some other kernel
12762 			 * component, we check and return an error.
12763 			 */
12764 			cr = msg_getcred(mp, NULL);
12765 			ASSERT(cr != NULL);
12766 			if (cr == NULL) {
12767 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12768 				if (mp != NULL)
12769 					qreply(q, mp);
12770 				return;
12771 			}
12772 
12773 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12774 				proto_str = "Bad SNMPCOM request?";
12775 				goto protonak;
12776 			}
12777 			return;
12778 		default:
12779 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12780 			    (int)*(uint_t *)mp->b_rptr));
12781 			freemsg(mp);
12782 			return;
12783 		}
12784 	default:
12785 		break;
12786 	}
12787 	if (q->q_next) {
12788 		putnext(q, mp);
12789 	} else
12790 		freemsg(mp);
12791 	return;
12792 
12793 nak:
12794 	iocp->ioc_error = EINVAL;
12795 	mp->b_datap->db_type = M_IOCNAK;
12796 	iocp->ioc_count = 0;
12797 	qreply(q, mp);
12798 	return;
12799 
12800 protonak:
12801 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12802 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12803 		qreply(q, mp);
12804 }
12805 
12806 /*
12807  * Process IP options in an outbound packet.  Verify that the nexthop in a
12808  * strict source route is onlink.
12809  * Returns non-zero if something fails in which case an ICMP error has been
12810  * sent and mp freed.
12811  *
12812  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12813  */
12814 int
12815 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12816 {
12817 	ipoptp_t	opts;
12818 	uchar_t		*opt;
12819 	uint8_t		optval;
12820 	uint8_t		optlen;
12821 	ipaddr_t	dst;
12822 	intptr_t	code = 0;
12823 	ire_t		*ire;
12824 	ip_stack_t	*ipst = ixa->ixa_ipst;
12825 	ip_recv_attr_t	iras;
12826 
12827 	ip2dbg(("ip_output_options\n"));
12828 
12829 	dst = ipha->ipha_dst;
12830 	for (optval = ipoptp_first(&opts, ipha);
12831 	    optval != IPOPT_EOL;
12832 	    optval = ipoptp_next(&opts)) {
12833 		opt = opts.ipoptp_cur;
12834 		optlen = opts.ipoptp_len;
12835 		ip2dbg(("ip_output_options: opt %d, len %d\n",
12836 		    optval, optlen));
12837 		switch (optval) {
12838 			uint32_t off;
12839 		case IPOPT_SSRR:
12840 		case IPOPT_LSRR:
12841 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12842 				ip1dbg((
12843 				    "ip_output_options: bad option offset\n"));
12844 				code = (char *)&opt[IPOPT_OLEN] -
12845 				    (char *)ipha;
12846 				goto param_prob;
12847 			}
12848 			off = opt[IPOPT_OFFSET];
12849 			ip1dbg(("ip_output_options: next hop 0x%x\n",
12850 			    ntohl(dst)));
12851 			/*
12852 			 * For strict: verify that dst is directly
12853 			 * reachable.
12854 			 */
12855 			if (optval == IPOPT_SSRR) {
12856 				ire = ire_ftable_lookup_v4(dst, 0, 0,
12857 				    IRE_IF_ALL, NULL, ALL_ZONES, ixa->ixa_tsl,
12858 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
12859 				    NULL);
12860 				if (ire == NULL) {
12861 					ip1dbg(("ip_output_options: SSRR not"
12862 					    " directly reachable: 0x%x\n",
12863 					    ntohl(dst)));
12864 					goto bad_src_route;
12865 				}
12866 				ire_refrele(ire);
12867 			}
12868 			break;
12869 		case IPOPT_RR:
12870 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12871 				ip1dbg((
12872 				    "ip_output_options: bad option offset\n"));
12873 				code = (char *)&opt[IPOPT_OLEN] -
12874 				    (char *)ipha;
12875 				goto param_prob;
12876 			}
12877 			break;
12878 		case IPOPT_TS:
12879 			/*
12880 			 * Verify that length >=5 and that there is either
12881 			 * room for another timestamp or that the overflow
12882 			 * counter is not maxed out.
12883 			 */
12884 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
12885 			if (optlen < IPOPT_MINLEN_IT) {
12886 				goto param_prob;
12887 			}
12888 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12889 				ip1dbg((
12890 				    "ip_output_options: bad option offset\n"));
12891 				code = (char *)&opt[IPOPT_OFFSET] -
12892 				    (char *)ipha;
12893 				goto param_prob;
12894 			}
12895 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12896 			case IPOPT_TS_TSONLY:
12897 				off = IPOPT_TS_TIMELEN;
12898 				break;
12899 			case IPOPT_TS_TSANDADDR:
12900 			case IPOPT_TS_PRESPEC:
12901 			case IPOPT_TS_PRESPEC_RFC791:
12902 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12903 				break;
12904 			default:
12905 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
12906 				    (char *)ipha;
12907 				goto param_prob;
12908 			}
12909 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
12910 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
12911 				/*
12912 				 * No room and the overflow counter is 15
12913 				 * already.
12914 				 */
12915 				goto param_prob;
12916 			}
12917 			break;
12918 		}
12919 	}
12920 
12921 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
12922 		return (0);
12923 
12924 	ip1dbg(("ip_output_options: error processing IP options."));
12925 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
12926 
12927 param_prob:
12928 	bzero(&iras, sizeof (iras));
12929 	iras.ira_ill = iras.ira_rill = ill;
12930 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12931 	iras.ira_rifindex = iras.ira_ruifindex;
12932 	iras.ira_flags = IRAF_IS_IPV4;
12933 
12934 	ip_drop_output("ip_output_options", mp, ill);
12935 	icmp_param_problem(mp, (uint8_t)code, &iras);
12936 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12937 	return (-1);
12938 
12939 bad_src_route:
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_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
12947 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
12948 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
12949 	return (-1);
12950 }
12951 
12952 /*
12953  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
12954  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
12955  * thru /etc/system.
12956  */
12957 #define	CONN_MAXDRAINCNT	64
12958 
12959 static void
12960 conn_drain_init(ip_stack_t *ipst)
12961 {
12962 	int i, j;
12963 	idl_tx_list_t *itl_tx;
12964 
12965 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
12966 
12967 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
12968 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
12969 		/*
12970 		 * Default value of the number of drainers is the
12971 		 * number of cpus, subject to maximum of 8 drainers.
12972 		 */
12973 		if (boot_max_ncpus != -1)
12974 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
12975 		else
12976 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
12977 	}
12978 
12979 	ipst->ips_idl_tx_list =
12980 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
12981 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
12982 		itl_tx =  &ipst->ips_idl_tx_list[i];
12983 		itl_tx->txl_drain_list =
12984 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
12985 		    sizeof (idl_t), KM_SLEEP);
12986 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
12987 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
12988 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
12989 			    MUTEX_DEFAULT, NULL);
12990 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
12991 		}
12992 	}
12993 }
12994 
12995 static void
12996 conn_drain_fini(ip_stack_t *ipst)
12997 {
12998 	int i;
12999 	idl_tx_list_t *itl_tx;
13000 
13001 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13002 		itl_tx =  &ipst->ips_idl_tx_list[i];
13003 		kmem_free(itl_tx->txl_drain_list,
13004 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13005 	}
13006 	kmem_free(ipst->ips_idl_tx_list,
13007 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13008 	ipst->ips_idl_tx_list = NULL;
13009 }
13010 
13011 /*
13012  * Flow control has blocked us from proceeding.  Insert the given conn in one
13013  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13014  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13015  * will call conn_walk_drain().  See the flow control notes at the top of this
13016  * file for more details.
13017  */
13018 void
13019 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13020 {
13021 	idl_t	*idl = tx_list->txl_drain_list;
13022 	uint_t	index;
13023 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13024 
13025 	mutex_enter(&connp->conn_lock);
13026 	if (connp->conn_state_flags & CONN_CLOSING) {
13027 		/*
13028 		 * The conn is closing as a result of which CONN_CLOSING
13029 		 * is set. Return.
13030 		 */
13031 		mutex_exit(&connp->conn_lock);
13032 		return;
13033 	} else if (connp->conn_idl == NULL) {
13034 		/*
13035 		 * Assign the next drain list round robin. We dont' use
13036 		 * a lock, and thus it may not be strictly round robin.
13037 		 * Atomicity of load/stores is enough to make sure that
13038 		 * conn_drain_list_index is always within bounds.
13039 		 */
13040 		index = tx_list->txl_drain_index;
13041 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13042 		connp->conn_idl = &tx_list->txl_drain_list[index];
13043 		index++;
13044 		if (index == ipst->ips_conn_drain_list_cnt)
13045 			index = 0;
13046 		tx_list->txl_drain_index = index;
13047 	} else {
13048 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13049 	}
13050 	mutex_exit(&connp->conn_lock);
13051 
13052 	idl = connp->conn_idl;
13053 	mutex_enter(&idl->idl_lock);
13054 	if ((connp->conn_drain_prev != NULL) ||
13055 	    (connp->conn_state_flags & CONN_CLOSING)) {
13056 		/*
13057 		 * The conn is either already in the drain list or closing.
13058 		 * (We needed to check for CONN_CLOSING again since close can
13059 		 * sneak in between dropping conn_lock and acquiring idl_lock.)
13060 		 */
13061 		mutex_exit(&idl->idl_lock);
13062 		return;
13063 	}
13064 
13065 	/*
13066 	 * The conn is not in the drain list. Insert it at the
13067 	 * tail of the drain list. The drain list is circular
13068 	 * and doubly linked. idl_conn points to the 1st element
13069 	 * in the list.
13070 	 */
13071 	if (idl->idl_conn == NULL) {
13072 		idl->idl_conn = connp;
13073 		connp->conn_drain_next = connp;
13074 		connp->conn_drain_prev = connp;
13075 	} else {
13076 		conn_t *head = idl->idl_conn;
13077 
13078 		connp->conn_drain_next = head;
13079 		connp->conn_drain_prev = head->conn_drain_prev;
13080 		head->conn_drain_prev->conn_drain_next = connp;
13081 		head->conn_drain_prev = connp;
13082 	}
13083 	/*
13084 	 * For non streams based sockets assert flow control.
13085 	 */
13086 	conn_setqfull(connp, NULL);
13087 	mutex_exit(&idl->idl_lock);
13088 }
13089 
13090 static void
13091 conn_drain_remove(conn_t *connp)
13092 {
13093 	idl_t *idl = connp->conn_idl;
13094 
13095 	if (idl != NULL) {
13096 		/*
13097 		 * Remove ourself from the drain list.
13098 		 */
13099 		if (connp->conn_drain_next == connp) {
13100 			/* Singleton in the list */
13101 			ASSERT(connp->conn_drain_prev == connp);
13102 			idl->idl_conn = NULL;
13103 		} else {
13104 			connp->conn_drain_prev->conn_drain_next =
13105 			    connp->conn_drain_next;
13106 			connp->conn_drain_next->conn_drain_prev =
13107 			    connp->conn_drain_prev;
13108 			if (idl->idl_conn == connp)
13109 				idl->idl_conn = connp->conn_drain_next;
13110 		}
13111 
13112 		/*
13113 		 * NOTE: because conn_idl is associated with a specific drain
13114 		 * list which in turn is tied to the index the TX ring
13115 		 * (txl_cookie) hashes to, and because the TX ring can change
13116 		 * over the lifetime of the conn_t, we must clear conn_idl so
13117 		 * a subsequent conn_drain_insert() will set conn_idl again
13118 		 * based on the latest txl_cookie.
13119 		 */
13120 		connp->conn_idl = NULL;
13121 	}
13122 	connp->conn_drain_next = NULL;
13123 	connp->conn_drain_prev = NULL;
13124 
13125 	conn_clrqfull(connp, NULL);
13126 	/*
13127 	 * For streams based sockets open up flow control.
13128 	 */
13129 	if (!IPCL_IS_NONSTR(connp))
13130 		enableok(connp->conn_wq);
13131 }
13132 
13133 /*
13134  * This conn is closing, and we are called from ip_close. OR
13135  * this conn is draining because flow-control on the ill has been relieved.
13136  *
13137  * We must also need to remove conn's on this idl from the list, and also
13138  * inform the sockfs upcalls about the change in flow-control.
13139  */
13140 static void
13141 conn_drain(conn_t *connp, boolean_t closing)
13142 {
13143 	idl_t *idl;
13144 	conn_t *next_connp;
13145 
13146 	/*
13147 	 * connp->conn_idl is stable at this point, and no lock is needed
13148 	 * to check it. If we are called from ip_close, close has already
13149 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13150 	 * called us only because conn_idl is non-null. If we are called thru
13151 	 * service, conn_idl could be null, but it cannot change because
13152 	 * service is single-threaded per queue, and there cannot be another
13153 	 * instance of service trying to call conn_drain_insert on this conn
13154 	 * now.
13155 	 */
13156 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13157 
13158 	/*
13159 	 * If the conn doesn't exist or is not on a drain list, bail.
13160 	 */
13161 	if (connp == NULL || connp->conn_idl == NULL ||
13162 	    connp->conn_drain_prev == NULL) {
13163 		return;
13164 	}
13165 
13166 	idl = connp->conn_idl;
13167 	ASSERT(MUTEX_HELD(&idl->idl_lock));
13168 
13169 	if (!closing) {
13170 		next_connp = connp->conn_drain_next;
13171 		while (next_connp != connp) {
13172 			conn_t *delconnp = next_connp;
13173 
13174 			next_connp = next_connp->conn_drain_next;
13175 			conn_drain_remove(delconnp);
13176 		}
13177 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13178 	}
13179 	conn_drain_remove(connp);
13180 }
13181 
13182 /*
13183  * Write service routine. Shared perimeter entry point.
13184  * The device queue's messages has fallen below the low water mark and STREAMS
13185  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13186  * each waiting conn.
13187  */
13188 void
13189 ip_wsrv(queue_t *q)
13190 {
13191 	ill_t	*ill;
13192 
13193 	ill = (ill_t *)q->q_ptr;
13194 	if (ill->ill_state_flags == 0) {
13195 		ip_stack_t *ipst = ill->ill_ipst;
13196 
13197 		/*
13198 		 * The device flow control has opened up.
13199 		 * Walk through conn drain lists and qenable the
13200 		 * first conn in each list. This makes sense only
13201 		 * if the stream is fully plumbed and setup.
13202 		 * Hence the ill_state_flags check above.
13203 		 */
13204 		ip1dbg(("ip_wsrv: walking\n"));
13205 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13206 		enableok(ill->ill_wq);
13207 	}
13208 }
13209 
13210 /*
13211  * Callback to disable flow control in IP.
13212  *
13213  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13214  * is enabled.
13215  *
13216  * When MAC_TX() is not able to send any more packets, dld sets its queue
13217  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13218  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13219  * function and wakes up corresponding mac worker threads, which in turn
13220  * calls this callback function, and disables flow control.
13221  */
13222 void
13223 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13224 {
13225 	ill_t *ill = (ill_t *)arg;
13226 	ip_stack_t *ipst = ill->ill_ipst;
13227 	idl_tx_list_t *idl_txl;
13228 
13229 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13230 	mutex_enter(&idl_txl->txl_lock);
13231 	/* add code to to set a flag to indicate idl_txl is enabled */
13232 	conn_walk_drain(ipst, idl_txl);
13233 	mutex_exit(&idl_txl->txl_lock);
13234 }
13235 
13236 /*
13237  * Flow control has been relieved and STREAMS has backenabled us; drain
13238  * all the conn lists on `tx_list'.
13239  */
13240 static void
13241 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13242 {
13243 	int i;
13244 	idl_t *idl;
13245 
13246 	IP_STAT(ipst, ip_conn_walk_drain);
13247 
13248 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13249 		idl = &tx_list->txl_drain_list[i];
13250 		mutex_enter(&idl->idl_lock);
13251 		conn_drain(idl->idl_conn, B_FALSE);
13252 		mutex_exit(&idl->idl_lock);
13253 	}
13254 }
13255 
13256 /*
13257  * Determine if the ill and multicast aspects of that packets
13258  * "matches" the conn.
13259  */
13260 boolean_t
13261 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13262 {
13263 	ill_t		*ill = ira->ira_rill;
13264 	zoneid_t	zoneid = ira->ira_zoneid;
13265 	uint_t		in_ifindex;
13266 	ipaddr_t	dst, src;
13267 
13268 	dst = ipha->ipha_dst;
13269 	src = ipha->ipha_src;
13270 
13271 	/*
13272 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13273 	 * unicast, broadcast and multicast reception to
13274 	 * conn_incoming_ifindex.
13275 	 * conn_wantpacket is called for unicast, broadcast and
13276 	 * multicast packets.
13277 	 */
13278 	in_ifindex = connp->conn_incoming_ifindex;
13279 
13280 	/* mpathd can bind to the under IPMP interface, which we allow */
13281 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13282 		if (!IS_UNDER_IPMP(ill))
13283 			return (B_FALSE);
13284 
13285 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13286 			return (B_FALSE);
13287 	}
13288 
13289 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13290 		return (B_FALSE);
13291 
13292 	if (!(ira->ira_flags & IRAF_MULTICAST))
13293 		return (B_TRUE);
13294 
13295 	if (connp->conn_multi_router) {
13296 		/* multicast packet and multicast router socket: send up */
13297 		return (B_TRUE);
13298 	}
13299 
13300 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13301 	    ipha->ipha_protocol == IPPROTO_RSVP)
13302 		return (B_TRUE);
13303 
13304 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13305 }
13306 
13307 void
13308 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13309 {
13310 	if (IPCL_IS_NONSTR(connp)) {
13311 		(*connp->conn_upcalls->su_txq_full)
13312 		    (connp->conn_upper_handle, B_TRUE);
13313 		if (flow_stopped != NULL)
13314 			*flow_stopped = B_TRUE;
13315 	} else {
13316 		queue_t *q = connp->conn_wq;
13317 
13318 		ASSERT(q != NULL);
13319 		if (!(q->q_flag & QFULL)) {
13320 			mutex_enter(QLOCK(q));
13321 			if (!(q->q_flag & QFULL)) {
13322 				/* still need to set QFULL */
13323 				q->q_flag |= QFULL;
13324 				/* set flow_stopped to true under QLOCK */
13325 				if (flow_stopped != NULL)
13326 					*flow_stopped = B_TRUE;
13327 				mutex_exit(QLOCK(q));
13328 			} else {
13329 				/* flow_stopped is left unchanged */
13330 				mutex_exit(QLOCK(q));
13331 			}
13332 		}
13333 	}
13334 }
13335 
13336 void
13337 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13338 {
13339 	if (IPCL_IS_NONSTR(connp)) {
13340 		(*connp->conn_upcalls->su_txq_full)
13341 		    (connp->conn_upper_handle, B_FALSE);
13342 		if (flow_stopped != NULL)
13343 			*flow_stopped = B_FALSE;
13344 	} else {
13345 		queue_t *q = connp->conn_wq;
13346 
13347 		ASSERT(q != NULL);
13348 		if (q->q_flag & QFULL) {
13349 			mutex_enter(QLOCK(q));
13350 			if (q->q_flag & QFULL) {
13351 				q->q_flag &= ~QFULL;
13352 				/* set flow_stopped to false under QLOCK */
13353 				if (flow_stopped != NULL)
13354 					*flow_stopped = B_FALSE;
13355 				mutex_exit(QLOCK(q));
13356 				if (q->q_flag & QWANTW)
13357 					qbackenable(q, 0);
13358 			} else {
13359 				/* flow_stopped is left unchanged */
13360 				mutex_exit(QLOCK(q));
13361 			}
13362 		}
13363 	}
13364 
13365 	mutex_enter(&connp->conn_lock);
13366 	connp->conn_blocked = B_FALSE;
13367 	mutex_exit(&connp->conn_lock);
13368 }
13369 
13370 /*
13371  * Return the length in bytes of the IPv4 headers (base header, label, and
13372  * other IP options) that will be needed based on the
13373  * ip_pkt_t structure passed by the caller.
13374  *
13375  * The returned length does not include the length of the upper level
13376  * protocol (ULP) header.
13377  * The caller needs to check that the length doesn't exceed the max for IPv4.
13378  */
13379 int
13380 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13381 {
13382 	int len;
13383 
13384 	len = IP_SIMPLE_HDR_LENGTH;
13385 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13386 		ASSERT(ipp->ipp_label_len_v4 != 0);
13387 		/* We need to round up here */
13388 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13389 	}
13390 
13391 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13392 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13393 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13394 		len += ipp->ipp_ipv4_options_len;
13395 	}
13396 	return (len);
13397 }
13398 
13399 /*
13400  * All-purpose routine to build an IPv4 header with options based
13401  * on the abstract ip_pkt_t.
13402  *
13403  * The caller has to set the source and destination address as well as
13404  * ipha_length. The caller has to massage any source route and compensate
13405  * for the ULP pseudo-header checksum due to the source route.
13406  */
13407 void
13408 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13409     uint8_t protocol)
13410 {
13411 	ipha_t	*ipha = (ipha_t *)buf;
13412 	uint8_t *cp;
13413 
13414 	/* Initialize IPv4 header */
13415 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13416 	ipha->ipha_length = 0;	/* Caller will set later */
13417 	ipha->ipha_ident = 0;
13418 	ipha->ipha_fragment_offset_and_flags = 0;
13419 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13420 	ipha->ipha_protocol = protocol;
13421 	ipha->ipha_hdr_checksum = 0;
13422 
13423 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13424 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13425 		ipha->ipha_src = ipp->ipp_addr_v4;
13426 
13427 	cp = (uint8_t *)&ipha[1];
13428 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13429 		ASSERT(ipp->ipp_label_len_v4 != 0);
13430 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13431 		cp += ipp->ipp_label_len_v4;
13432 		/* We need to round up here */
13433 		while ((uintptr_t)cp & 0x3) {
13434 			*cp++ = IPOPT_NOP;
13435 		}
13436 	}
13437 
13438 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13439 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13440 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13441 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13442 		cp += ipp->ipp_ipv4_options_len;
13443 	}
13444 	ipha->ipha_version_and_hdr_length =
13445 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13446 
13447 	ASSERT((int)(cp - buf) == buf_len);
13448 }
13449 
13450 /* Allocate the private structure */
13451 static int
13452 ip_priv_alloc(void **bufp)
13453 {
13454 	void	*buf;
13455 
13456 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13457 		return (ENOMEM);
13458 
13459 	*bufp = buf;
13460 	return (0);
13461 }
13462 
13463 /* Function to delete the private structure */
13464 void
13465 ip_priv_free(void *buf)
13466 {
13467 	ASSERT(buf != NULL);
13468 	kmem_free(buf, sizeof (ip_priv_t));
13469 }
13470 
13471 /*
13472  * The entry point for IPPF processing.
13473  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13474  * routine just returns.
13475  *
13476  * When called, ip_process generates an ipp_packet_t structure
13477  * which holds the state information for this packet and invokes the
13478  * the classifier (via ipp_packet_process). The classification, depending on
13479  * configured filters, results in a list of actions for this packet. Invoking
13480  * an action may cause the packet to be dropped, in which case we return NULL.
13481  * proc indicates the callout position for
13482  * this packet and ill is the interface this packet arrived on or will leave
13483  * on (inbound and outbound resp.).
13484  *
13485  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13486  * on the ill corrsponding to the destination IP address.
13487  */
13488 mblk_t *
13489 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13490 {
13491 	ip_priv_t	*priv;
13492 	ipp_action_id_t	aid;
13493 	int		rc = 0;
13494 	ipp_packet_t	*pp;
13495 
13496 	/* If the classifier is not loaded, return  */
13497 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13498 		return (mp);
13499 	}
13500 
13501 	ASSERT(mp != NULL);
13502 
13503 	/* Allocate the packet structure */
13504 	rc = ipp_packet_alloc(&pp, "ip", aid);
13505 	if (rc != 0)
13506 		goto drop;
13507 
13508 	/* Allocate the private structure */
13509 	rc = ip_priv_alloc((void **)&priv);
13510 	if (rc != 0) {
13511 		ipp_packet_free(pp);
13512 		goto drop;
13513 	}
13514 	priv->proc = proc;
13515 	priv->ill_index = ill_get_upper_ifindex(rill);
13516 
13517 	ipp_packet_set_private(pp, priv, ip_priv_free);
13518 	ipp_packet_set_data(pp, mp);
13519 
13520 	/* Invoke the classifier */
13521 	rc = ipp_packet_process(&pp);
13522 	if (pp != NULL) {
13523 		mp = ipp_packet_get_data(pp);
13524 		ipp_packet_free(pp);
13525 		if (rc != 0)
13526 			goto drop;
13527 		return (mp);
13528 	} else {
13529 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13530 		mp = NULL;
13531 	}
13532 drop:
13533 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13534 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13535 		ip_drop_input("ip_process", mp, ill);
13536 	} else {
13537 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13538 		ip_drop_output("ip_process", mp, ill);
13539 	}
13540 	freemsg(mp);
13541 	return (NULL);
13542 }
13543 
13544 /*
13545  * Propagate a multicast group membership operation (add/drop) on
13546  * all the interfaces crossed by the related multirt routes.
13547  * The call is considered successful if the operation succeeds
13548  * on at least one interface.
13549  *
13550  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13551  * multicast addresses with the ire argument being the first one.
13552  * We walk the bucket to find all the of those.
13553  *
13554  * Common to IPv4 and IPv6.
13555  */
13556 static int
13557 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13558     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13559     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13560     mcast_record_t fmode, const in6_addr_t *v6src)
13561 {
13562 	ire_t		*ire_gw;
13563 	irb_t		*irb;
13564 	int		ifindex;
13565 	int		error = 0;
13566 	int		result;
13567 	ip_stack_t	*ipst = ire->ire_ipst;
13568 	ipaddr_t	group;
13569 	boolean_t	isv6;
13570 	int		match_flags;
13571 
13572 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13573 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13574 		isv6 = B_FALSE;
13575 	} else {
13576 		isv6 = B_TRUE;
13577 	}
13578 
13579 	irb = ire->ire_bucket;
13580 	ASSERT(irb != NULL);
13581 
13582 	result = 0;
13583 	irb_refhold(irb);
13584 	for (; ire != NULL; ire = ire->ire_next) {
13585 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13586 			continue;
13587 
13588 		/* We handle -ifp routes by matching on the ill if set */
13589 		match_flags = MATCH_IRE_TYPE;
13590 		if (ire->ire_ill != NULL)
13591 			match_flags |= MATCH_IRE_ILL;
13592 
13593 		if (isv6) {
13594 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13595 				continue;
13596 
13597 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13598 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13599 			    match_flags, 0, ipst, NULL);
13600 		} else {
13601 			if (ire->ire_addr != group)
13602 				continue;
13603 
13604 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13605 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13606 			    match_flags, 0, ipst, NULL);
13607 		}
13608 		/* No interface route exists for the gateway; skip this ire. */
13609 		if (ire_gw == NULL)
13610 			continue;
13611 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13612 			ire_refrele(ire_gw);
13613 			continue;
13614 		}
13615 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13616 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13617 
13618 		/*
13619 		 * The operation is considered a success if
13620 		 * it succeeds at least once on any one interface.
13621 		 */
13622 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13623 		    fmode, v6src);
13624 		if (error == 0)
13625 			result = CGTP_MCAST_SUCCESS;
13626 
13627 		ire_refrele(ire_gw);
13628 	}
13629 	irb_refrele(irb);
13630 	/*
13631 	 * Consider the call as successful if we succeeded on at least
13632 	 * one interface. Otherwise, return the last encountered error.
13633 	 */
13634 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13635 }
13636 
13637 /*
13638  * Return the expected CGTP hooks version number.
13639  */
13640 int
13641 ip_cgtp_filter_supported(void)
13642 {
13643 	return (ip_cgtp_filter_rev);
13644 }
13645 
13646 /*
13647  * CGTP hooks can be registered by invoking this function.
13648  * Checks that the version number matches.
13649  */
13650 int
13651 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13652 {
13653 	netstack_t *ns;
13654 	ip_stack_t *ipst;
13655 
13656 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13657 		return (ENOTSUP);
13658 
13659 	ns = netstack_find_by_stackid(stackid);
13660 	if (ns == NULL)
13661 		return (EINVAL);
13662 	ipst = ns->netstack_ip;
13663 	ASSERT(ipst != NULL);
13664 
13665 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13666 		netstack_rele(ns);
13667 		return (EALREADY);
13668 	}
13669 
13670 	ipst->ips_ip_cgtp_filter_ops = ops;
13671 
13672 	ill_set_inputfn_all(ipst);
13673 
13674 	netstack_rele(ns);
13675 	return (0);
13676 }
13677 
13678 /*
13679  * CGTP hooks can be unregistered by invoking this function.
13680  * Returns ENXIO if there was no registration.
13681  * Returns EBUSY if the ndd variable has not been turned off.
13682  */
13683 int
13684 ip_cgtp_filter_unregister(netstackid_t stackid)
13685 {
13686 	netstack_t *ns;
13687 	ip_stack_t *ipst;
13688 
13689 	ns = netstack_find_by_stackid(stackid);
13690 	if (ns == NULL)
13691 		return (EINVAL);
13692 	ipst = ns->netstack_ip;
13693 	ASSERT(ipst != NULL);
13694 
13695 	if (ipst->ips_ip_cgtp_filter) {
13696 		netstack_rele(ns);
13697 		return (EBUSY);
13698 	}
13699 
13700 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13701 		netstack_rele(ns);
13702 		return (ENXIO);
13703 	}
13704 	ipst->ips_ip_cgtp_filter_ops = NULL;
13705 
13706 	ill_set_inputfn_all(ipst);
13707 
13708 	netstack_rele(ns);
13709 	return (0);
13710 }
13711 
13712 /*
13713  * Check whether there is a CGTP filter registration.
13714  * Returns non-zero if there is a registration, otherwise returns zero.
13715  * Note: returns zero if bad stackid.
13716  */
13717 int
13718 ip_cgtp_filter_is_registered(netstackid_t stackid)
13719 {
13720 	netstack_t *ns;
13721 	ip_stack_t *ipst;
13722 	int ret;
13723 
13724 	ns = netstack_find_by_stackid(stackid);
13725 	if (ns == NULL)
13726 		return (0);
13727 	ipst = ns->netstack_ip;
13728 	ASSERT(ipst != NULL);
13729 
13730 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13731 		ret = 1;
13732 	else
13733 		ret = 0;
13734 
13735 	netstack_rele(ns);
13736 	return (ret);
13737 }
13738 
13739 static int
13740 ip_squeue_switch(int val)
13741 {
13742 	int rval;
13743 
13744 	switch (val) {
13745 	case IP_SQUEUE_ENTER_NODRAIN:
13746 		rval = SQ_NODRAIN;
13747 		break;
13748 	case IP_SQUEUE_ENTER:
13749 		rval = SQ_PROCESS;
13750 		break;
13751 	case IP_SQUEUE_FILL:
13752 	default:
13753 		rval = SQ_FILL;
13754 		break;
13755 	}
13756 	return (rval);
13757 }
13758 
13759 static void *
13760 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13761 {
13762 	kstat_t *ksp;
13763 
13764 	ip_stat_t template = {
13765 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
13766 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
13767 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
13768 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13769 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13770 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13771 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13772 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13773 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13774 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13775 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13776 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13777 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13778 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13779 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13780 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13781 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13782 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13783 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13784 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13785 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13786 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13787 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13788 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13789 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13790 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13791 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13792 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13793 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13794 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13795 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
13796 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
13797 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
13798 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
13799 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
13800 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
13801 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
13802 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
13803 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
13804 	};
13805 
13806 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13807 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13808 	    KSTAT_FLAG_VIRTUAL, stackid);
13809 
13810 	if (ksp == NULL)
13811 		return (NULL);
13812 
13813 	bcopy(&template, ip_statisticsp, sizeof (template));
13814 	ksp->ks_data = (void *)ip_statisticsp;
13815 	ksp->ks_private = (void *)(uintptr_t)stackid;
13816 
13817 	kstat_install(ksp);
13818 	return (ksp);
13819 }
13820 
13821 static void
13822 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13823 {
13824 	if (ksp != NULL) {
13825 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13826 		kstat_delete_netstack(ksp, stackid);
13827 	}
13828 }
13829 
13830 static void *
13831 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13832 {
13833 	kstat_t	*ksp;
13834 
13835 	ip_named_kstat_t template = {
13836 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
13837 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
13838 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
13839 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
13840 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
13841 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
13842 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
13843 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
13844 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
13845 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
13846 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
13847 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
13848 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
13849 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
13850 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
13851 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
13852 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
13853 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
13854 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
13855 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
13856 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
13857 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
13858 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
13859 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
13860 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
13861 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
13862 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
13863 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
13864 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
13865 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
13866 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
13867 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
13868 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
13869 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
13870 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
13871 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
13872 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
13873 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
13874 	};
13875 
13876 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
13877 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
13878 	if (ksp == NULL || ksp->ks_data == NULL)
13879 		return (NULL);
13880 
13881 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
13882 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
13883 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
13884 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
13885 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
13886 
13887 	template.netToMediaEntrySize.value.i32 =
13888 	    sizeof (mib2_ipNetToMediaEntry_t);
13889 
13890 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
13891 
13892 	bcopy(&template, ksp->ks_data, sizeof (template));
13893 	ksp->ks_update = ip_kstat_update;
13894 	ksp->ks_private = (void *)(uintptr_t)stackid;
13895 
13896 	kstat_install(ksp);
13897 	return (ksp);
13898 }
13899 
13900 static void
13901 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
13902 {
13903 	if (ksp != NULL) {
13904 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13905 		kstat_delete_netstack(ksp, stackid);
13906 	}
13907 }
13908 
13909 static int
13910 ip_kstat_update(kstat_t *kp, int rw)
13911 {
13912 	ip_named_kstat_t *ipkp;
13913 	mib2_ipIfStatsEntry_t ipmib;
13914 	ill_walk_context_t ctx;
13915 	ill_t *ill;
13916 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
13917 	netstack_t	*ns;
13918 	ip_stack_t	*ipst;
13919 
13920 	if (kp == NULL || kp->ks_data == NULL)
13921 		return (EIO);
13922 
13923 	if (rw == KSTAT_WRITE)
13924 		return (EACCES);
13925 
13926 	ns = netstack_find_by_stackid(stackid);
13927 	if (ns == NULL)
13928 		return (-1);
13929 	ipst = ns->netstack_ip;
13930 	if (ipst == NULL) {
13931 		netstack_rele(ns);
13932 		return (-1);
13933 	}
13934 	ipkp = (ip_named_kstat_t *)kp->ks_data;
13935 
13936 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
13937 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
13938 	ill = ILL_START_WALK_V4(&ctx, ipst);
13939 	for (; ill != NULL; ill = ill_next(&ctx, ill))
13940 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
13941 	rw_exit(&ipst->ips_ill_g_lock);
13942 
13943 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
13944 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
13945 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
13946 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
13947 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
13948 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
13949 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
13950 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
13951 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
13952 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
13953 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
13954 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
13955 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
13956 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
13957 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
13958 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
13959 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
13960 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
13961 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
13962 
13963 	ipkp->routingDiscards.value.ui32 =	0;
13964 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
13965 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
13966 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
13967 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
13968 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
13969 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
13970 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
13971 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
13972 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
13973 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
13974 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
13975 
13976 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
13977 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
13978 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
13979 
13980 	netstack_rele(ns);
13981 
13982 	return (0);
13983 }
13984 
13985 static void *
13986 icmp_kstat_init(netstackid_t stackid)
13987 {
13988 	kstat_t	*ksp;
13989 
13990 	icmp_named_kstat_t template = {
13991 		{ "inMsgs",		KSTAT_DATA_UINT32 },
13992 		{ "inErrors",		KSTAT_DATA_UINT32 },
13993 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
13994 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
13995 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
13996 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
13997 		{ "inRedirects",	KSTAT_DATA_UINT32 },
13998 		{ "inEchos",		KSTAT_DATA_UINT32 },
13999 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14000 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14001 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14002 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14003 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14004 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14005 		{ "outErrors",		KSTAT_DATA_UINT32 },
14006 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14007 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14008 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14009 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14010 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14011 		{ "outEchos",		KSTAT_DATA_UINT32 },
14012 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14013 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14014 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14015 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14016 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14017 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14018 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14019 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14020 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14021 		{ "outDrops",		KSTAT_DATA_UINT32 },
14022 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14023 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14024 	};
14025 
14026 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14027 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14028 	if (ksp == NULL || ksp->ks_data == NULL)
14029 		return (NULL);
14030 
14031 	bcopy(&template, ksp->ks_data, sizeof (template));
14032 
14033 	ksp->ks_update = icmp_kstat_update;
14034 	ksp->ks_private = (void *)(uintptr_t)stackid;
14035 
14036 	kstat_install(ksp);
14037 	return (ksp);
14038 }
14039 
14040 static void
14041 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14042 {
14043 	if (ksp != NULL) {
14044 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14045 		kstat_delete_netstack(ksp, stackid);
14046 	}
14047 }
14048 
14049 static int
14050 icmp_kstat_update(kstat_t *kp, int rw)
14051 {
14052 	icmp_named_kstat_t *icmpkp;
14053 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14054 	netstack_t	*ns;
14055 	ip_stack_t	*ipst;
14056 
14057 	if ((kp == NULL) || (kp->ks_data == NULL))
14058 		return (EIO);
14059 
14060 	if (rw == KSTAT_WRITE)
14061 		return (EACCES);
14062 
14063 	ns = netstack_find_by_stackid(stackid);
14064 	if (ns == NULL)
14065 		return (-1);
14066 	ipst = ns->netstack_ip;
14067 	if (ipst == NULL) {
14068 		netstack_rele(ns);
14069 		return (-1);
14070 	}
14071 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14072 
14073 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14074 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14075 	icmpkp->inDestUnreachs.value.ui32 =
14076 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14077 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14078 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14079 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14080 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14081 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14082 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14083 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14084 	icmpkp->inTimestampReps.value.ui32 =
14085 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14086 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14087 	icmpkp->inAddrMaskReps.value.ui32 =
14088 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14089 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14090 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14091 	icmpkp->outDestUnreachs.value.ui32 =
14092 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14093 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14094 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14095 	icmpkp->outSrcQuenchs.value.ui32 =
14096 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14097 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14098 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14099 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14100 	icmpkp->outTimestamps.value.ui32 =
14101 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14102 	icmpkp->outTimestampReps.value.ui32 =
14103 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14104 	icmpkp->outAddrMasks.value.ui32 =
14105 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14106 	icmpkp->outAddrMaskReps.value.ui32 =
14107 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14108 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14109 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14110 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14111 	icmpkp->outFragNeeded.value.ui32 =
14112 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14113 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14114 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14115 	icmpkp->inBadRedirects.value.ui32 =
14116 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14117 
14118 	netstack_rele(ns);
14119 	return (0);
14120 }
14121 
14122 /*
14123  * This is the fanout function for raw socket opened for SCTP.  Note
14124  * that it is called after SCTP checks that there is no socket which
14125  * wants a packet.  Then before SCTP handles this out of the blue packet,
14126  * this function is called to see if there is any raw socket for SCTP.
14127  * If there is and it is bound to the correct address, the packet will
14128  * be sent to that socket.  Note that only one raw socket can be bound to
14129  * a port.  This is assured in ipcl_sctp_hash_insert();
14130  */
14131 void
14132 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14133     ip_recv_attr_t *ira)
14134 {
14135 	conn_t		*connp;
14136 	queue_t		*rq;
14137 	boolean_t	secure;
14138 	ill_t		*ill = ira->ira_ill;
14139 	ip_stack_t	*ipst = ill->ill_ipst;
14140 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14141 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14142 	iaflags_t	iraflags = ira->ira_flags;
14143 	ill_t		*rill = ira->ira_rill;
14144 
14145 	secure = iraflags & IRAF_IPSEC_SECURE;
14146 
14147 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14148 	    ira, ipst);
14149 	if (connp == NULL) {
14150 		/*
14151 		 * Although raw sctp is not summed, OOB chunks must be.
14152 		 * Drop the packet here if the sctp checksum failed.
14153 		 */
14154 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14155 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
14156 			freemsg(mp);
14157 			return;
14158 		}
14159 		ira->ira_ill = ira->ira_rill = NULL;
14160 		sctp_ootb_input(mp, ira, ipst);
14161 		ira->ira_ill = ill;
14162 		ira->ira_rill = rill;
14163 		return;
14164 	}
14165 	rq = connp->conn_rq;
14166 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14167 		CONN_DEC_REF(connp);
14168 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14169 		freemsg(mp);
14170 		return;
14171 	}
14172 	if (((iraflags & IRAF_IS_IPV4) ?
14173 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14174 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14175 	    secure) {
14176 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14177 		    ip6h, ira);
14178 		if (mp == NULL) {
14179 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14180 			/* Note that mp is NULL */
14181 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14182 			CONN_DEC_REF(connp);
14183 			return;
14184 		}
14185 	}
14186 
14187 	if (iraflags & IRAF_ICMP_ERROR) {
14188 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14189 	} else {
14190 		ill_t *rill = ira->ira_rill;
14191 
14192 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14193 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14194 		ira->ira_ill = ira->ira_rill = NULL;
14195 		(connp->conn_recv)(connp, mp, NULL, ira);
14196 		ira->ira_ill = ill;
14197 		ira->ira_rill = rill;
14198 	}
14199 	CONN_DEC_REF(connp);
14200 }
14201 
14202 /*
14203  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14204  * header before the ip payload.
14205  */
14206 static void
14207 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14208 {
14209 	int len = (mp->b_wptr - mp->b_rptr);
14210 	mblk_t *ip_mp;
14211 
14212 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14213 	if (is_fp_mp || len != fp_mp_len) {
14214 		if (len > fp_mp_len) {
14215 			/*
14216 			 * fastpath header and ip header in the first mblk
14217 			 */
14218 			mp->b_rptr += fp_mp_len;
14219 		} else {
14220 			/*
14221 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14222 			 * attach the fastpath header before ip header.
14223 			 */
14224 			ip_mp = mp->b_cont;
14225 			freeb(mp);
14226 			mp = ip_mp;
14227 			mp->b_rptr += (fp_mp_len - len);
14228 		}
14229 	} else {
14230 		ip_mp = mp->b_cont;
14231 		freeb(mp);
14232 		mp = ip_mp;
14233 	}
14234 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14235 	freemsg(mp);
14236 }
14237 
14238 /*
14239  * Normal post fragmentation function.
14240  *
14241  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14242  * using the same state machine.
14243  *
14244  * We return an error on failure. In particular we return EWOULDBLOCK
14245  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14246  * (currently by canputnext failure resulting in backenabling from GLD.)
14247  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14248  * indication that they can flow control until ip_wsrv() tells then to restart.
14249  *
14250  * If the nce passed by caller is incomplete, this function
14251  * queues the packet and if necessary, sends ARP request and bails.
14252  * If the Neighbor Cache passed is fully resolved, we simply prepend
14253  * the link-layer header to the packet, do ipsec hw acceleration
14254  * work if necessary, and send the packet out on the wire.
14255  */
14256 /* ARGSUSED6 */
14257 int
14258 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14259     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14260 {
14261 	queue_t		*wq;
14262 	ill_t		*ill = nce->nce_ill;
14263 	ip_stack_t	*ipst = ill->ill_ipst;
14264 	uint64_t	delta;
14265 	boolean_t	isv6 = ill->ill_isv6;
14266 	boolean_t	fp_mp;
14267 	ncec_t		*ncec = nce->nce_common;
14268 	int64_t		now = LBOLT_FASTPATH64;
14269 	boolean_t	is_probe;
14270 
14271 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14272 
14273 	ASSERT(mp != NULL);
14274 	ASSERT(mp->b_datap->db_type == M_DATA);
14275 	ASSERT(pkt_len == msgdsize(mp));
14276 
14277 	/*
14278 	 * If we have already been here and are coming back after ARP/ND.
14279 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14280 	 * in that case since they have seen the packet when it came here
14281 	 * the first time.
14282 	 */
14283 	if (ixaflags & IXAF_NO_TRACE)
14284 		goto sendit;
14285 
14286 	if (ixaflags & IXAF_IS_IPV4) {
14287 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14288 
14289 		ASSERT(!isv6);
14290 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14291 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14292 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14293 			int	error;
14294 
14295 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14296 			    ipst->ips_ipv4firewall_physical_out,
14297 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14298 			DTRACE_PROBE1(ip4__physical__out__end,
14299 			    mblk_t *, mp);
14300 			if (mp == NULL)
14301 				return (error);
14302 
14303 			/* The length could have changed */
14304 			pkt_len = msgdsize(mp);
14305 		}
14306 		if (ipst->ips_ip4_observe.he_interested) {
14307 			/*
14308 			 * Note that for TX the zoneid is the sending
14309 			 * zone, whether or not MLP is in play.
14310 			 * Since the szone argument is the IP zoneid (i.e.,
14311 			 * zero for exclusive-IP zones) and ipobs wants
14312 			 * the system zoneid, we map it here.
14313 			 */
14314 			szone = IP_REAL_ZONEID(szone, ipst);
14315 
14316 			/*
14317 			 * On the outbound path the destination zone will be
14318 			 * unknown as we're sending this packet out on the
14319 			 * wire.
14320 			 */
14321 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14322 			    ill, ipst);
14323 		}
14324 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14325 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14326 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14327 	} else {
14328 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14329 
14330 		ASSERT(isv6);
14331 		ASSERT(pkt_len ==
14332 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14333 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14334 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14335 			int	error;
14336 
14337 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14338 			    ipst->ips_ipv6firewall_physical_out,
14339 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14340 			DTRACE_PROBE1(ip6__physical__out__end,
14341 			    mblk_t *, mp);
14342 			if (mp == NULL)
14343 				return (error);
14344 
14345 			/* The length could have changed */
14346 			pkt_len = msgdsize(mp);
14347 		}
14348 		if (ipst->ips_ip6_observe.he_interested) {
14349 			/* See above */
14350 			szone = IP_REAL_ZONEID(szone, ipst);
14351 
14352 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14353 			    ill, ipst);
14354 		}
14355 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14356 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14357 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14358 	}
14359 
14360 sendit:
14361 	/*
14362 	 * We check the state without a lock because the state can never
14363 	 * move "backwards" to initial or incomplete.
14364 	 */
14365 	switch (ncec->ncec_state) {
14366 	case ND_REACHABLE:
14367 	case ND_STALE:
14368 	case ND_DELAY:
14369 	case ND_PROBE:
14370 		mp = ip_xmit_attach_llhdr(mp, nce);
14371 		if (mp == NULL) {
14372 			/*
14373 			 * ip_xmit_attach_llhdr has increased
14374 			 * ipIfStatsOutDiscards and called ip_drop_output()
14375 			 */
14376 			return (ENOBUFS);
14377 		}
14378 		/*
14379 		 * check if nce_fastpath completed and we tagged on a
14380 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14381 		 */
14382 		fp_mp = (mp->b_datap->db_type == M_DATA);
14383 
14384 		if (fp_mp &&
14385 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14386 			ill_dld_direct_t *idd;
14387 
14388 			idd = &ill->ill_dld_capab->idc_direct;
14389 			/*
14390 			 * Send the packet directly to DLD, where it
14391 			 * may be queued depending on the availability
14392 			 * of transmit resources at the media layer.
14393 			 * Return value should be taken into
14394 			 * account and flow control the TCP.
14395 			 */
14396 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14397 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14398 			    pkt_len);
14399 
14400 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14401 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14402 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14403 			} else {
14404 				uintptr_t cookie;
14405 
14406 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14407 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14408 					if (ixacookie != NULL)
14409 						*ixacookie = cookie;
14410 					return (EWOULDBLOCK);
14411 				}
14412 			}
14413 		} else {
14414 			wq = ill->ill_wq;
14415 
14416 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14417 			    !canputnext(wq)) {
14418 				if (ixacookie != NULL)
14419 					*ixacookie = 0;
14420 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14421 				    nce->nce_fp_mp != NULL ?
14422 				    MBLKL(nce->nce_fp_mp) : 0);
14423 				return (EWOULDBLOCK);
14424 			}
14425 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14426 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14427 			    pkt_len);
14428 			putnext(wq, mp);
14429 		}
14430 
14431 		/*
14432 		 * The rest of this function implements Neighbor Unreachability
14433 		 * detection. Determine if the ncec is eligible for NUD.
14434 		 */
14435 		if (ncec->ncec_flags & NCE_F_NONUD)
14436 			return (0);
14437 
14438 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14439 
14440 		/*
14441 		 * Check for upper layer advice
14442 		 */
14443 		if (ixaflags & IXAF_REACH_CONF) {
14444 			timeout_id_t tid;
14445 
14446 			/*
14447 			 * It should be o.k. to check the state without
14448 			 * a lock here, at most we lose an advice.
14449 			 */
14450 			ncec->ncec_last = TICK_TO_MSEC(now);
14451 			if (ncec->ncec_state != ND_REACHABLE) {
14452 				mutex_enter(&ncec->ncec_lock);
14453 				ncec->ncec_state = ND_REACHABLE;
14454 				tid = ncec->ncec_timeout_id;
14455 				ncec->ncec_timeout_id = 0;
14456 				mutex_exit(&ncec->ncec_lock);
14457 				(void) untimeout(tid);
14458 				if (ip_debug > 2) {
14459 					/* ip1dbg */
14460 					pr_addr_dbg("ip_xmit: state"
14461 					    " for %s changed to"
14462 					    " REACHABLE\n", AF_INET6,
14463 					    &ncec->ncec_addr);
14464 				}
14465 			}
14466 			return (0);
14467 		}
14468 
14469 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14470 		ip1dbg(("ip_xmit: delta = %" PRId64
14471 		    " ill_reachable_time = %d \n", delta,
14472 		    ill->ill_reachable_time));
14473 		if (delta > (uint64_t)ill->ill_reachable_time) {
14474 			mutex_enter(&ncec->ncec_lock);
14475 			switch (ncec->ncec_state) {
14476 			case ND_REACHABLE:
14477 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14478 				/* FALLTHROUGH */
14479 			case ND_STALE:
14480 				/*
14481 				 * ND_REACHABLE is identical to
14482 				 * ND_STALE in this specific case. If
14483 				 * reachable time has expired for this
14484 				 * neighbor (delta is greater than
14485 				 * reachable time), conceptually, the
14486 				 * neighbor cache is no longer in
14487 				 * REACHABLE state, but already in
14488 				 * STALE state.  So the correct
14489 				 * transition here is to ND_DELAY.
14490 				 */
14491 				ncec->ncec_state = ND_DELAY;
14492 				mutex_exit(&ncec->ncec_lock);
14493 				nce_restart_timer(ncec,
14494 				    ipst->ips_delay_first_probe_time);
14495 				if (ip_debug > 3) {
14496 					/* ip2dbg */
14497 					pr_addr_dbg("ip_xmit: state"
14498 					    " for %s changed to"
14499 					    " DELAY\n", AF_INET6,
14500 					    &ncec->ncec_addr);
14501 				}
14502 				break;
14503 			case ND_DELAY:
14504 			case ND_PROBE:
14505 				mutex_exit(&ncec->ncec_lock);
14506 				/* Timers have already started */
14507 				break;
14508 			case ND_UNREACHABLE:
14509 				/*
14510 				 * nce_timer has detected that this ncec
14511 				 * is unreachable and initiated deleting
14512 				 * this ncec.
14513 				 * This is a harmless race where we found the
14514 				 * ncec before it was deleted and have
14515 				 * just sent out a packet using this
14516 				 * unreachable ncec.
14517 				 */
14518 				mutex_exit(&ncec->ncec_lock);
14519 				break;
14520 			default:
14521 				ASSERT(0);
14522 				mutex_exit(&ncec->ncec_lock);
14523 			}
14524 		}
14525 		return (0);
14526 
14527 	case ND_INCOMPLETE:
14528 		/*
14529 		 * the state could have changed since we didn't hold the lock.
14530 		 * Re-verify state under lock.
14531 		 */
14532 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14533 		mutex_enter(&ncec->ncec_lock);
14534 		if (NCE_ISREACHABLE(ncec)) {
14535 			mutex_exit(&ncec->ncec_lock);
14536 			goto sendit;
14537 		}
14538 		/* queue the packet */
14539 		nce_queue_mp(ncec, mp, is_probe);
14540 		mutex_exit(&ncec->ncec_lock);
14541 		DTRACE_PROBE2(ip__xmit__incomplete,
14542 		    (ncec_t *), ncec, (mblk_t *), mp);
14543 		return (0);
14544 
14545 	case ND_INITIAL:
14546 		/*
14547 		 * State could have changed since we didn't hold the lock, so
14548 		 * re-verify state.
14549 		 */
14550 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14551 		mutex_enter(&ncec->ncec_lock);
14552 		if (NCE_ISREACHABLE(ncec))  {
14553 			mutex_exit(&ncec->ncec_lock);
14554 			goto sendit;
14555 		}
14556 		nce_queue_mp(ncec, mp, is_probe);
14557 		if (ncec->ncec_state == ND_INITIAL) {
14558 			ncec->ncec_state = ND_INCOMPLETE;
14559 			mutex_exit(&ncec->ncec_lock);
14560 			/*
14561 			 * figure out the source we want to use
14562 			 * and resolve it.
14563 			 */
14564 			ip_ndp_resolve(ncec);
14565 		} else  {
14566 			mutex_exit(&ncec->ncec_lock);
14567 		}
14568 		return (0);
14569 
14570 	case ND_UNREACHABLE:
14571 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14572 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14573 		    mp, ill);
14574 		freemsg(mp);
14575 		return (0);
14576 
14577 	default:
14578 		ASSERT(0);
14579 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14580 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14581 		    mp, ill);
14582 		freemsg(mp);
14583 		return (ENETUNREACH);
14584 	}
14585 }
14586 
14587 /*
14588  * Return B_TRUE if the buffers differ in length or content.
14589  * This is used for comparing extension header buffers.
14590  * Note that an extension header would be declared different
14591  * even if all that changed was the next header value in that header i.e.
14592  * what really changed is the next extension header.
14593  */
14594 boolean_t
14595 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14596     uint_t blen)
14597 {
14598 	if (!b_valid)
14599 		blen = 0;
14600 
14601 	if (alen != blen)
14602 		return (B_TRUE);
14603 	if (alen == 0)
14604 		return (B_FALSE);	/* Both zero length */
14605 	return (bcmp(abuf, bbuf, alen));
14606 }
14607 
14608 /*
14609  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14610  * Return B_FALSE if memory allocation fails - don't change any state!
14611  */
14612 boolean_t
14613 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14614     const void *src, uint_t srclen)
14615 {
14616 	void *dst;
14617 
14618 	if (!src_valid)
14619 		srclen = 0;
14620 
14621 	ASSERT(*dstlenp == 0);
14622 	if (src != NULL && srclen != 0) {
14623 		dst = mi_alloc(srclen, BPRI_MED);
14624 		if (dst == NULL)
14625 			return (B_FALSE);
14626 	} else {
14627 		dst = NULL;
14628 	}
14629 	if (*dstp != NULL)
14630 		mi_free(*dstp);
14631 	*dstp = dst;
14632 	*dstlenp = dst == NULL ? 0 : srclen;
14633 	return (B_TRUE);
14634 }
14635 
14636 /*
14637  * Replace what is in *dst, *dstlen with the source.
14638  * Assumes ip_allocbuf has already been called.
14639  */
14640 void
14641 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14642     const void *src, uint_t srclen)
14643 {
14644 	if (!src_valid)
14645 		srclen = 0;
14646 
14647 	ASSERT(*dstlenp == srclen);
14648 	if (src != NULL && srclen != 0)
14649 		bcopy(src, *dstp, srclen);
14650 }
14651 
14652 /*
14653  * Free the storage pointed to by the members of an ip_pkt_t.
14654  */
14655 void
14656 ip_pkt_free(ip_pkt_t *ipp)
14657 {
14658 	uint_t	fields = ipp->ipp_fields;
14659 
14660 	if (fields & IPPF_HOPOPTS) {
14661 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14662 		ipp->ipp_hopopts = NULL;
14663 		ipp->ipp_hopoptslen = 0;
14664 	}
14665 	if (fields & IPPF_RTHDRDSTOPTS) {
14666 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14667 		ipp->ipp_rthdrdstopts = NULL;
14668 		ipp->ipp_rthdrdstoptslen = 0;
14669 	}
14670 	if (fields & IPPF_DSTOPTS) {
14671 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14672 		ipp->ipp_dstopts = NULL;
14673 		ipp->ipp_dstoptslen = 0;
14674 	}
14675 	if (fields & IPPF_RTHDR) {
14676 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14677 		ipp->ipp_rthdr = NULL;
14678 		ipp->ipp_rthdrlen = 0;
14679 	}
14680 	if (fields & IPPF_IPV4_OPTIONS) {
14681 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14682 		ipp->ipp_ipv4_options = NULL;
14683 		ipp->ipp_ipv4_options_len = 0;
14684 	}
14685 	if (fields & IPPF_LABEL_V4) {
14686 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14687 		ipp->ipp_label_v4 = NULL;
14688 		ipp->ipp_label_len_v4 = 0;
14689 	}
14690 	if (fields & IPPF_LABEL_V6) {
14691 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14692 		ipp->ipp_label_v6 = NULL;
14693 		ipp->ipp_label_len_v6 = 0;
14694 	}
14695 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14696 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14697 }
14698 
14699 /*
14700  * Copy from src to dst and allocate as needed.
14701  * Returns zero or ENOMEM.
14702  *
14703  * The caller must initialize dst to zero.
14704  */
14705 int
14706 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14707 {
14708 	uint_t	fields = src->ipp_fields;
14709 
14710 	/* Start with fields that don't require memory allocation */
14711 	dst->ipp_fields = fields &
14712 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14713 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14714 
14715 	dst->ipp_addr = src->ipp_addr;
14716 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14717 	dst->ipp_hoplimit = src->ipp_hoplimit;
14718 	dst->ipp_tclass = src->ipp_tclass;
14719 	dst->ipp_type_of_service = src->ipp_type_of_service;
14720 
14721 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14722 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14723 		return (0);
14724 
14725 	if (fields & IPPF_HOPOPTS) {
14726 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14727 		if (dst->ipp_hopopts == NULL) {
14728 			ip_pkt_free(dst);
14729 			return (ENOMEM);
14730 		}
14731 		dst->ipp_fields |= IPPF_HOPOPTS;
14732 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14733 		    src->ipp_hopoptslen);
14734 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14735 	}
14736 	if (fields & IPPF_RTHDRDSTOPTS) {
14737 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14738 		    kmflag);
14739 		if (dst->ipp_rthdrdstopts == NULL) {
14740 			ip_pkt_free(dst);
14741 			return (ENOMEM);
14742 		}
14743 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14744 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14745 		    src->ipp_rthdrdstoptslen);
14746 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14747 	}
14748 	if (fields & IPPF_DSTOPTS) {
14749 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14750 		if (dst->ipp_dstopts == NULL) {
14751 			ip_pkt_free(dst);
14752 			return (ENOMEM);
14753 		}
14754 		dst->ipp_fields |= IPPF_DSTOPTS;
14755 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14756 		    src->ipp_dstoptslen);
14757 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14758 	}
14759 	if (fields & IPPF_RTHDR) {
14760 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14761 		if (dst->ipp_rthdr == NULL) {
14762 			ip_pkt_free(dst);
14763 			return (ENOMEM);
14764 		}
14765 		dst->ipp_fields |= IPPF_RTHDR;
14766 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14767 		    src->ipp_rthdrlen);
14768 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14769 	}
14770 	if (fields & IPPF_IPV4_OPTIONS) {
14771 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14772 		    kmflag);
14773 		if (dst->ipp_ipv4_options == NULL) {
14774 			ip_pkt_free(dst);
14775 			return (ENOMEM);
14776 		}
14777 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14778 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14779 		    src->ipp_ipv4_options_len);
14780 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14781 	}
14782 	if (fields & IPPF_LABEL_V4) {
14783 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14784 		if (dst->ipp_label_v4 == NULL) {
14785 			ip_pkt_free(dst);
14786 			return (ENOMEM);
14787 		}
14788 		dst->ipp_fields |= IPPF_LABEL_V4;
14789 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14790 		    src->ipp_label_len_v4);
14791 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14792 	}
14793 	if (fields & IPPF_LABEL_V6) {
14794 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14795 		if (dst->ipp_label_v6 == NULL) {
14796 			ip_pkt_free(dst);
14797 			return (ENOMEM);
14798 		}
14799 		dst->ipp_fields |= IPPF_LABEL_V6;
14800 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14801 		    src->ipp_label_len_v6);
14802 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14803 	}
14804 	if (fields & IPPF_FRAGHDR) {
14805 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14806 		if (dst->ipp_fraghdr == NULL) {
14807 			ip_pkt_free(dst);
14808 			return (ENOMEM);
14809 		}
14810 		dst->ipp_fields |= IPPF_FRAGHDR;
14811 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14812 		    src->ipp_fraghdrlen);
14813 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14814 	}
14815 	return (0);
14816 }
14817 
14818 /*
14819  * Returns INADDR_ANY if no source route
14820  */
14821 ipaddr_t
14822 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14823 {
14824 	ipaddr_t	nexthop = INADDR_ANY;
14825 	ipoptp_t	opts;
14826 	uchar_t		*opt;
14827 	uint8_t		optval;
14828 	uint8_t		optlen;
14829 	uint32_t	totallen;
14830 
14831 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14832 		return (INADDR_ANY);
14833 
14834 	totallen = ipp->ipp_ipv4_options_len;
14835 	if (totallen & 0x3)
14836 		return (INADDR_ANY);
14837 
14838 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14839 	    optval != IPOPT_EOL;
14840 	    optval = ipoptp_next(&opts)) {
14841 		opt = opts.ipoptp_cur;
14842 		switch (optval) {
14843 			uint8_t off;
14844 		case IPOPT_SSRR:
14845 		case IPOPT_LSRR:
14846 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14847 				break;
14848 			}
14849 			optlen = opts.ipoptp_len;
14850 			off = opt[IPOPT_OFFSET];
14851 			off--;
14852 			if (optlen < IP_ADDR_LEN ||
14853 			    off > optlen - IP_ADDR_LEN) {
14854 				/* End of source route */
14855 				break;
14856 			}
14857 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
14858 			if (nexthop == htonl(INADDR_LOOPBACK)) {
14859 				/* Ignore */
14860 				nexthop = INADDR_ANY;
14861 				break;
14862 			}
14863 			break;
14864 		}
14865 	}
14866 	return (nexthop);
14867 }
14868 
14869 /*
14870  * Reverse a source route.
14871  */
14872 void
14873 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
14874 {
14875 	ipaddr_t	tmp;
14876 	ipoptp_t	opts;
14877 	uchar_t		*opt;
14878 	uint8_t		optval;
14879 	uint32_t	totallen;
14880 
14881 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14882 		return;
14883 
14884 	totallen = ipp->ipp_ipv4_options_len;
14885 	if (totallen & 0x3)
14886 		return;
14887 
14888 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14889 	    optval != IPOPT_EOL;
14890 	    optval = ipoptp_next(&opts)) {
14891 		uint8_t off1, off2;
14892 
14893 		opt = opts.ipoptp_cur;
14894 		switch (optval) {
14895 		case IPOPT_SSRR:
14896 		case IPOPT_LSRR:
14897 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14898 				break;
14899 			}
14900 			off1 = IPOPT_MINOFF_SR - 1;
14901 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
14902 			while (off2 > off1) {
14903 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
14904 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
14905 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
14906 				off2 -= IP_ADDR_LEN;
14907 				off1 += IP_ADDR_LEN;
14908 			}
14909 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
14910 			break;
14911 		}
14912 	}
14913 }
14914 
14915 /*
14916  * Returns NULL if no routing header
14917  */
14918 in6_addr_t *
14919 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
14920 {
14921 	in6_addr_t	*nexthop = NULL;
14922 	ip6_rthdr0_t	*rthdr;
14923 
14924 	if (!(ipp->ipp_fields & IPPF_RTHDR))
14925 		return (NULL);
14926 
14927 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
14928 	if (rthdr->ip6r0_segleft == 0)
14929 		return (NULL);
14930 
14931 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
14932 	return (nexthop);
14933 }
14934 
14935 zoneid_t
14936 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
14937     zoneid_t lookup_zoneid)
14938 {
14939 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
14940 	ire_t		*ire;
14941 	int		ire_flags = MATCH_IRE_TYPE;
14942 	zoneid_t	zoneid = ALL_ZONES;
14943 
14944 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
14945 		return (ALL_ZONES);
14946 
14947 	if (lookup_zoneid != ALL_ZONES)
14948 		ire_flags |= MATCH_IRE_ZONEONLY;
14949 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
14950 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
14951 	if (ire != NULL) {
14952 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
14953 		ire_refrele(ire);
14954 	}
14955 	return (zoneid);
14956 }
14957 
14958 zoneid_t
14959 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
14960     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
14961 {
14962 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
14963 	ire_t		*ire;
14964 	int		ire_flags = MATCH_IRE_TYPE;
14965 	zoneid_t	zoneid = ALL_ZONES;
14966 
14967 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
14968 		return (ALL_ZONES);
14969 
14970 	if (IN6_IS_ADDR_LINKLOCAL(addr))
14971 		ire_flags |= MATCH_IRE_ILL;
14972 
14973 	if (lookup_zoneid != ALL_ZONES)
14974 		ire_flags |= MATCH_IRE_ZONEONLY;
14975 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
14976 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
14977 	if (ire != NULL) {
14978 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
14979 		ire_refrele(ire);
14980 	}
14981 	return (zoneid);
14982 }
14983 
14984 /*
14985  * IP obserability hook support functions.
14986  */
14987 static void
14988 ipobs_init(ip_stack_t *ipst)
14989 {
14990 	netid_t id;
14991 
14992 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
14993 
14994 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
14995 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
14996 
14997 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
14998 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
14999 }
15000 
15001 static void
15002 ipobs_fini(ip_stack_t *ipst)
15003 {
15004 
15005 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15006 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15007 }
15008 
15009 /*
15010  * hook_pkt_observe_t is composed in network byte order so that the
15011  * entire mblk_t chain handed into hook_run can be used as-is.
15012  * The caveat is that use of the fields, such as the zone fields,
15013  * requires conversion into host byte order first.
15014  */
15015 void
15016 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15017     const ill_t *ill, ip_stack_t *ipst)
15018 {
15019 	hook_pkt_observe_t *hdr;
15020 	uint64_t grifindex;
15021 	mblk_t *imp;
15022 
15023 	imp = allocb(sizeof (*hdr), BPRI_HI);
15024 	if (imp == NULL)
15025 		return;
15026 
15027 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15028 	/*
15029 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15030 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15031 	 */
15032 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15033 	imp->b_cont = mp;
15034 
15035 	ASSERT(DB_TYPE(mp) == M_DATA);
15036 
15037 	if (IS_UNDER_IPMP(ill))
15038 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15039 	else
15040 		grifindex = 0;
15041 
15042 	hdr->hpo_version = 1;
15043 	hdr->hpo_htype = htons(htype);
15044 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15045 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15046 	hdr->hpo_grifindex = htonl(grifindex);
15047 	hdr->hpo_zsrc = htonl(zsrc);
15048 	hdr->hpo_zdst = htonl(zdst);
15049 	hdr->hpo_pkt = imp;
15050 	hdr->hpo_ctx = ipst->ips_netstack;
15051 
15052 	if (ill->ill_isv6) {
15053 		hdr->hpo_family = AF_INET6;
15054 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15055 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15056 	} else {
15057 		hdr->hpo_family = AF_INET;
15058 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15059 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15060 	}
15061 
15062 	imp->b_cont = NULL;
15063 	freemsg(imp);
15064 }
15065 
15066 /*
15067  * Utility routine that checks if `v4srcp' is a valid address on underlying
15068  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15069  * associated with `v4srcp' on success.  NOTE: if this is not called from
15070  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15071  * group during or after this lookup.
15072  */
15073 boolean_t
15074 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15075 {
15076 	ipif_t *ipif;
15077 
15078 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15079 	if (ipif != NULL) {
15080 		if (ipifp != NULL)
15081 			*ipifp = ipif;
15082 		else
15083 			ipif_refrele(ipif);
15084 		return (B_TRUE);
15085 	}
15086 
15087 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15088 	    *v4srcp));
15089 	return (B_FALSE);
15090 }
15091