xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision b8052df9f609edb713f6828c9eecc3d7be19dfb3)
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  * Copyright (c) 2017 OmniTI Computer Consulting, Inc. All rights reserved.
26  * Copyright (c) 2016 by Delphix. All rights reserved.
27  * Copyright 2020 OmniOS Community Edition (OmniOSce) Association.
28  * Copyright 2021 Joyent, Inc.
29  */
30 
31 #include <sys/types.h>
32 #include <sys/stream.h>
33 #include <sys/dlpi.h>
34 #include <sys/stropts.h>
35 #include <sys/sysmacros.h>
36 #include <sys/strsubr.h>
37 #include <sys/strlog.h>
38 #include <sys/strsun.h>
39 #include <sys/zone.h>
40 #define	_SUN_TPI_VERSION 2
41 #include <sys/tihdr.h>
42 #include <sys/xti_inet.h>
43 #include <sys/ddi.h>
44 #include <sys/suntpi.h>
45 #include <sys/cmn_err.h>
46 #include <sys/debug.h>
47 #include <sys/kobj.h>
48 #include <sys/modctl.h>
49 #include <sys/atomic.h>
50 #include <sys/policy.h>
51 #include <sys/priv.h>
52 #include <sys/taskq.h>
53 
54 #include <sys/systm.h>
55 #include <sys/param.h>
56 #include <sys/kmem.h>
57 #include <sys/sdt.h>
58 #include <sys/socket.h>
59 #include <sys/vtrace.h>
60 #include <sys/isa_defs.h>
61 #include <sys/mac.h>
62 #include <net/if.h>
63 #include <net/if_arp.h>
64 #include <net/route.h>
65 #include <sys/sockio.h>
66 #include <netinet/in.h>
67 #include <net/if_dl.h>
68 
69 #include <inet/common.h>
70 #include <inet/mi.h>
71 #include <inet/mib2.h>
72 #include <inet/nd.h>
73 #include <inet/arp.h>
74 #include <inet/snmpcom.h>
75 #include <inet/optcom.h>
76 #include <inet/kstatcom.h>
77 
78 #include <netinet/igmp_var.h>
79 #include <netinet/ip6.h>
80 #include <netinet/icmp6.h>
81 #include <netinet/sctp.h>
82 
83 #include <inet/ip.h>
84 #include <inet/ip_impl.h>
85 #include <inet/ip6.h>
86 #include <inet/ip6_asp.h>
87 #include <inet/tcp.h>
88 #include <inet/tcp_impl.h>
89 #include <inet/ip_multi.h>
90 #include <inet/ip_if.h>
91 #include <inet/ip_ire.h>
92 #include <inet/ip_ftable.h>
93 #include <inet/ip_rts.h>
94 #include <inet/ip_ndp.h>
95 #include <inet/ip_listutils.h>
96 #include <netinet/igmp.h>
97 #include <netinet/ip_mroute.h>
98 #include <inet/ipp_common.h>
99 #include <inet/cc.h>
100 
101 #include <net/pfkeyv2.h>
102 #include <inet/sadb.h>
103 #include <inet/ipsec_impl.h>
104 #include <inet/iptun/iptun_impl.h>
105 #include <inet/ipdrop.h>
106 #include <inet/ip_netinfo.h>
107 #include <inet/ilb_ip.h>
108 
109 #include <sys/ethernet.h>
110 #include <net/if_types.h>
111 #include <sys/cpuvar.h>
112 
113 #include <ipp/ipp.h>
114 #include <ipp/ipp_impl.h>
115 #include <ipp/ipgpc/ipgpc.h>
116 
117 #include <sys/pattr.h>
118 #include <inet/ipclassifier.h>
119 #include <inet/sctp_ip.h>
120 #include <inet/sctp/sctp_impl.h>
121 #include <inet/udp_impl.h>
122 #include <inet/rawip_impl.h>
123 #include <inet/rts_impl.h>
124 
125 #include <sys/tsol/label.h>
126 #include <sys/tsol/tnet.h>
127 
128 #include <sys/squeue_impl.h>
129 #include <inet/ip_arp.h>
130 
131 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
132 
133 /*
134  * Values for squeue switch:
135  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
136  * IP_SQUEUE_ENTER: SQ_PROCESS
137  * IP_SQUEUE_FILL: SQ_FILL
138  */
139 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
140 
141 int ip_squeue_flag;
142 
143 /*
144  * Setable in /etc/system
145  */
146 int ip_poll_normal_ms = 100;
147 int ip_poll_normal_ticks = 0;
148 int ip_modclose_ackwait_ms = 3000;
149 
150 /*
151  * It would be nice to have these present only in DEBUG systems, but the
152  * current design of the global symbol checking logic requires them to be
153  * unconditionally present.
154  */
155 uint_t ip_thread_data;			/* TSD key for debug support */
156 krwlock_t ip_thread_rwlock;
157 list_t	ip_thread_list;
158 
159 /*
160  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
161  */
162 
163 struct listptr_s {
164 	mblk_t	*lp_head;	/* pointer to the head of the list */
165 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
166 };
167 
168 typedef struct listptr_s listptr_t;
169 
170 /*
171  * This is used by ip_snmp_get_mib2_ip_route_media and
172  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
173  */
174 typedef struct iproutedata_s {
175 	uint_t		ird_idx;
176 	uint_t		ird_flags;	/* see below */
177 	listptr_t	ird_route;	/* ipRouteEntryTable */
178 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
179 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
180 } iproutedata_t;
181 
182 /* Include ire_testhidden and IRE_IF_CLONE routes */
183 #define	IRD_REPORT_ALL	0x01
184 
185 /*
186  * Cluster specific hooks. These should be NULL when booted as a non-cluster
187  */
188 
189 /*
190  * Hook functions to enable cluster networking
191  * On non-clustered systems these vectors must always be NULL.
192  *
193  * Hook function to Check ip specified ip address is a shared ip address
194  * in the cluster
195  *
196  */
197 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
198     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
199 
200 /*
201  * Hook function to generate cluster wide ip fragment identifier
202  */
203 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
204     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
205     void *args) = NULL;
206 
207 /*
208  * Hook function to generate cluster wide SPI.
209  */
210 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
211     void *) = NULL;
212 
213 /*
214  * Hook function to verify if the SPI is already utlized.
215  */
216 
217 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
218 
219 /*
220  * Hook function to delete the SPI from the cluster wide repository.
221  */
222 
223 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
224 
225 /*
226  * Hook function to inform the cluster when packet received on an IDLE SA
227  */
228 
229 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
230     in6_addr_t, in6_addr_t, void *) = NULL;
231 
232 /*
233  * Synchronization notes:
234  *
235  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
236  * MT level protection given by STREAMS. IP uses a combination of its own
237  * internal serialization mechanism and standard Solaris locking techniques.
238  * The internal serialization is per phyint.  This is used to serialize
239  * plumbing operations, IPMP operations, most set ioctls, etc.
240  *
241  * Plumbing is a long sequence of operations involving message
242  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
243  * involved in plumbing operations. A natural model is to serialize these
244  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
245  * parallel without any interference. But various set ioctls on hme0 are best
246  * serialized, along with IPMP operations and processing of DLPI control
247  * messages received from drivers on a per phyint basis. This serialization is
248  * provided by the ipsq_t and primitives operating on this. Details can
249  * be found in ip_if.c above the core primitives operating on ipsq_t.
250  *
251  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
252  * Simiarly lookup of an ire by a thread also returns a refheld ire.
253  * In addition ipif's and ill's referenced by the ire are also indirectly
254  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
255  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
256  * address of an ipif has to go through the ipsq_t. This ensures that only
257  * one such exclusive operation proceeds at any time on the ipif. It then
258  * waits for all refcnts
259  * associated with this ipif to come down to zero. The address is changed
260  * only after the ipif has been quiesced. Then the ipif is brought up again.
261  * More details are described above the comment in ip_sioctl_flags.
262  *
263  * Packet processing is based mostly on IREs and are fully multi-threaded
264  * using standard Solaris MT techniques.
265  *
266  * There are explicit locks in IP to handle:
267  * - The ip_g_head list maintained by mi_open_link() and friends.
268  *
269  * - The reassembly data structures (one lock per hash bucket)
270  *
271  * - conn_lock is meant to protect conn_t fields. The fields actually
272  *   protected by conn_lock are documented in the conn_t definition.
273  *
274  * - ire_lock to protect some of the fields of the ire, IRE tables
275  *   (one lock per hash bucket). Refer to ip_ire.c for details.
276  *
277  * - ndp_g_lock and ncec_lock for protecting NCEs.
278  *
279  * - ill_lock protects fields of the ill and ipif. Details in ip.h
280  *
281  * - ill_g_lock: This is a global reader/writer lock. Protects the following
282  *	* The AVL tree based global multi list of all ills.
283  *	* The linked list of all ipifs of an ill
284  *	* The <ipsq-xop> mapping
285  *	* <ill-phyint> association
286  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
287  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
288  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
289  *   writer for the actual duration of the insertion/deletion/change.
290  *
291  * - ill_lock:  This is a per ill mutex.
292  *   It protects some members of the ill_t struct; see ip.h for details.
293  *   It also protects the <ill-phyint> assoc.
294  *   It also protects the list of ipifs hanging off the ill.
295  *
296  * - ipsq_lock: This is a per ipsq_t mutex lock.
297  *   This protects some members of the ipsq_t struct; see ip.h for details.
298  *   It also protects the <ipsq-ipxop> mapping
299  *
300  * - ipx_lock: This is a per ipxop_t mutex lock.
301  *   This protects some members of the ipxop_t struct; see ip.h for details.
302  *
303  * - phyint_lock: This is a per phyint mutex lock. Protects just the
304  *   phyint_flags
305  *
306  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
307  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
308  *   uniqueness check also done atomically.
309  *
310  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
311  *   group list linked by ill_usesrc_grp_next. It also protects the
312  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
313  *   group is being added or deleted.  This lock is taken as a reader when
314  *   walking the list/group(eg: to get the number of members in a usesrc group).
315  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
316  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
317  *   example, it is not necessary to take this lock in the initial portion
318  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
319  *   operations are executed exclusively and that ensures that the "usesrc
320  *   group state" cannot change. The "usesrc group state" change can happen
321  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
322  *
323  * Changing <ill-phyint>, <ipsq-xop> assocications:
324  *
325  * To change the <ill-phyint> association, the ill_g_lock must be held
326  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
327  * must be held.
328  *
329  * To change the <ipsq-xop> association, the ill_g_lock must be held as
330  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
331  * This is only done when ills are added or removed from IPMP groups.
332  *
333  * To add or delete an ipif from the list of ipifs hanging off the ill,
334  * ill_g_lock (writer) and ill_lock must be held and the thread must be
335  * a writer on the associated ipsq.
336  *
337  * To add or delete an ill to the system, the ill_g_lock must be held as
338  * writer and the thread must be a writer on the associated ipsq.
339  *
340  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
341  * must be a writer on the associated ipsq.
342  *
343  * Lock hierarchy
344  *
345  * Some lock hierarchy scenarios are listed below.
346  *
347  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
348  * ill_g_lock -> ill_lock(s) -> phyint_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
350  * ill_g_lock -> ip_addr_avail_lock
351  * conn_lock -> irb_lock -> ill_lock -> ire_lock
352  * ill_g_lock -> ip_g_nd_lock
353  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
354  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
355  * arl_lock -> ill_lock
356  * ips_ire_dep_lock -> irb_lock
357  *
358  * When more than 1 ill lock is needed to be held, all ill lock addresses
359  * are sorted on address and locked starting from highest addressed lock
360  * downward.
361  *
362  * Multicast scenarios
363  * ips_ill_g_lock -> ill_mcast_lock
364  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
365  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
366  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
367  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
368  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
369  *
370  * IPsec scenarios
371  *
372  * ipsa_lock -> ill_g_lock -> ill_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
417  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
418  *
419  * IPsec notes :
420  *
421  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
422  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
423  * ip_xmit_attr_t has the
424  * information used by the IPsec code for applying the right level of
425  * protection. The information initialized by IP in the ip_xmit_attr_t
426  * is determined by the per-socket policy or global policy in the system.
427  * For inbound datagrams, the ip_recv_attr_t
428  * starts out with nothing in it. It gets filled
429  * with the right information if it goes through the AH/ESP code, which
430  * happens if the incoming packet is secure. The information initialized
431  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
432  * the policy requirements needed by per-socket policy or global policy
433  * is met or not.
434  *
435  * For fully connected sockets i.e dst, src [addr, port] is known,
436  * conn_policy_cached is set indicating that policy has been cached.
437  * conn_in_enforce_policy may or may not be set depending on whether
438  * there is a global policy match or per-socket policy match.
439  * Policy inheriting happpens in ip_policy_set once the destination is known.
440  * Once the right policy is set on the conn_t, policy cannot change for
441  * this socket. This makes life simpler for TCP (UDP ?) where
442  * re-transmissions go out with the same policy. For symmetry, policy
443  * is cached for fully connected UDP sockets also. Thus if policy is cached,
444  * it also implies that policy is latched i.e policy cannot change
445  * on these sockets. As we have the right policy on the conn, we don't
446  * have to lookup global policy for every outbound and inbound datagram
447  * and thus serving as an optimization. Note that a global policy change
448  * does not affect fully connected sockets if they have policy. If fully
449  * connected sockets did not have any policy associated with it, global
450  * policy change may affect them.
451  *
452  * IP Flow control notes:
453  * ---------------------
454  * Non-TCP streams are flow controlled by IP. The way this is accomplished
455  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
456  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
457  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
458  * functions.
459  *
460  * Per Tx ring udp flow control:
461  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
462  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
463  *
464  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
465  * To achieve best performance, outgoing traffic need to be fanned out among
466  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
467  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
468  * the address of connp as fanout hint to mac_tx(). Under flow controlled
469  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
470  * cookie points to a specific Tx ring that is blocked. The cookie is used to
471  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
472  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
473  * connp's. The drain list is not a single list but a configurable number of
474  * lists.
475  *
476  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
477  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
478  * which is equal to 128. This array in turn contains a pointer to idl_t[],
479  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
480  * list will point to the list of connp's that are flow controlled.
481  *
482  *                      ---------------   -------   -------   -------
483  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
484  *                   |  ---------------   -------   -------   -------
485  *                   |  ---------------   -------   -------   -------
486  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
487  * ----------------  |  ---------------   -------   -------   -------
488  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
489  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
490  *                   |  ---------------   -------   -------   -------
491  *                   .        .              .         .         .
492  *                   |  ---------------   -------   -------   -------
493  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
494  *                      ---------------   -------   -------   -------
495  *                      ---------------   -------   -------   -------
496  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
497  *                   |  ---------------   -------   -------   -------
498  *                   |  ---------------   -------   -------   -------
499  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
500  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
501  * ----------------  |        .              .         .         .
502  *                   |  ---------------   -------   -------   -------
503  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
504  *                      ---------------   -------   -------   -------
505  *     .....
506  * ----------------
507  * |idl_tx_list[n]|-> ...
508  * ----------------
509  *
510  * When mac_tx() returns a cookie, the cookie is hashed into an index into
511  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
512  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
513  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
514  * Further, conn_blocked is set to indicate that the conn is blocked.
515  *
516  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
517  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
518  * is again hashed to locate the appropriate idl_tx_list, which is then
519  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
520  * the drain list and calls conn_drain_remove() to clear flow control (via
521  * calling su_txq_full() or clearing QFULL), and remove the conn from the
522  * drain list.
523  *
524  * Note that the drain list is not a single list but a (configurable) array of
525  * lists (8 elements by default).  Synchronization between drain insertion and
526  * flow control wakeup is handled by using idl_txl->txl_lock, and only
527  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
528  *
529  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
530  * On the send side, if the packet cannot be sent down to the driver by IP
531  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
532  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
533  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
534  * control has been relieved, the blocked conns in the 0'th drain list are
535  * drained as in the non-STREAMS case.
536  *
537  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
538  * is done when the conn is inserted into the drain list (conn_drain_insert())
539  * and cleared when the conn is removed from the it (conn_drain_remove()).
540  *
541  * IPQOS notes:
542  *
543  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
544  * and IPQoS modules. IPPF includes hooks in IP at different control points
545  * (callout positions) which direct packets to IPQoS modules for policy
546  * processing. Policies, if present, are global.
547  *
548  * The callout positions are located in the following paths:
549  *		o local_in (packets destined for this host)
550  *		o local_out (packets orginating from this host )
551  *		o fwd_in  (packets forwarded by this m/c - inbound)
552  *		o fwd_out (packets forwarded by this m/c - outbound)
553  * Hooks at these callout points can be enabled/disabled using the ndd variable
554  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
555  * By default all the callout positions are enabled.
556  *
557  * Outbound (local_out)
558  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
559  *
560  * Inbound (local_in)
561  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
562  *
563  * Forwarding (in and out)
564  * Hooks are placed in ire_recv_forward_v4/v6.
565  *
566  * IP Policy Framework processing (IPPF processing)
567  * Policy processing for a packet is initiated by ip_process, which ascertains
568  * that the classifier (ipgpc) is loaded and configured, failing which the
569  * packet resumes normal processing in IP. If the clasifier is present, the
570  * packet is acted upon by one or more IPQoS modules (action instances), per
571  * filters configured in ipgpc and resumes normal IP processing thereafter.
572  * An action instance can drop a packet in course of its processing.
573  *
574  * Zones notes:
575  *
576  * The partitioning rules for networking are as follows:
577  * 1) Packets coming from a zone must have a source address belonging to that
578  * zone.
579  * 2) Packets coming from a zone can only be sent on a physical interface on
580  * which the zone has an IP address.
581  * 3) Between two zones on the same machine, packet delivery is only allowed if
582  * there's a matching route for the destination and zone in the forwarding
583  * table.
584  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
585  * different zones can bind to the same port with the wildcard address
586  * (INADDR_ANY).
587  *
588  * The granularity of interface partitioning is at the logical interface level.
589  * Therefore, every zone has its own IP addresses, and incoming packets can be
590  * attributed to a zone unambiguously. A logical interface is placed into a zone
591  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
592  * structure. Rule (1) is implemented by modifying the source address selection
593  * algorithm so that the list of eligible addresses is filtered based on the
594  * sending process zone.
595  *
596  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
597  * across all zones, depending on their type. Here is the break-up:
598  *
599  * IRE type				Shared/exclusive
600  * --------				----------------
601  * IRE_BROADCAST			Exclusive
602  * IRE_DEFAULT (default routes)		Shared (*)
603  * IRE_LOCAL				Exclusive (x)
604  * IRE_LOOPBACK				Exclusive
605  * IRE_PREFIX (net routes)		Shared (*)
606  * IRE_IF_NORESOLVER (interface routes)	Exclusive
607  * IRE_IF_RESOLVER (interface routes)	Exclusive
608  * IRE_IF_CLONE (interface routes)	Exclusive
609  * IRE_HOST (host routes)		Shared (*)
610  *
611  * (*) A zone can only use a default or off-subnet route if the gateway is
612  * directly reachable from the zone, that is, if the gateway's address matches
613  * one of the zone's logical interfaces.
614  *
615  * (x) IRE_LOCAL are handled a bit differently.
616  * When ip_restrict_interzone_loopback is set (the default),
617  * ire_route_recursive restricts loopback using an IRE_LOCAL
618  * between zone to the case when L2 would have conceptually looped the packet
619  * back, i.e. the loopback which is required since neither Ethernet drivers
620  * nor Ethernet hardware loops them back. This is the case when the normal
621  * routes (ignoring IREs with different zoneids) would send out the packet on
622  * the same ill as the ill with which is IRE_LOCAL is associated.
623  *
624  * Multiple zones can share a common broadcast address; typically all zones
625  * share the 255.255.255.255 address. Incoming as well as locally originated
626  * broadcast packets must be dispatched to all the zones on the broadcast
627  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
628  * since some zones may not be on the 10.16.72/24 network. To handle this, each
629  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
630  * sent to every zone that has an IRE_BROADCAST entry for the destination
631  * address on the input ill, see ip_input_broadcast().
632  *
633  * Applications in different zones can join the same multicast group address.
634  * The same logic applies for multicast as for broadcast. ip_input_multicast
635  * dispatches packets to all zones that have members on the physical interface.
636  */
637 
638 /*
639  * Squeue Fanout flags:
640  *	0: No fanout.
641  *	1: Fanout across all squeues
642  */
643 boolean_t	ip_squeue_fanout = 0;
644 
645 /*
646  * Maximum dups allowed per packet.
647  */
648 uint_t ip_max_frag_dups = 10;
649 
650 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
651 		    cred_t *credp, boolean_t isv6);
652 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
653 
654 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
655 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
656 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
657     ip_recv_attr_t *);
658 static void	icmp_options_update(ipha_t *);
659 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
660 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
661 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
662 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
663     ip_recv_attr_t *);
664 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
665 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
666     ip_recv_attr_t *);
667 
668 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
669 char		*ip_dot_addr(ipaddr_t, char *);
670 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
671 static char	*ip_dot_saddr(uchar_t *, char *);
672 static int	ip_lrput(queue_t *, mblk_t *);
673 ipaddr_t	ip_net_mask(ipaddr_t);
674 char		*ip_nv_lookup(nv_t *, int);
675 int		ip_rput(queue_t *, mblk_t *);
676 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
677 		    void *dummy_arg);
678 int		ip_snmp_get(queue_t *, mblk_t *, int, boolean_t);
679 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
680 		    mib2_ipIfStatsEntry_t *, ip_stack_t *, boolean_t);
681 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
682 		    ip_stack_t *, boolean_t);
683 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *,
684 		    boolean_t);
685 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
687 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
689 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst, boolean_t);
691 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst, boolean_t);
693 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
698 		    ip_stack_t *ipst);
699 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
700 		    ip_stack_t *ipst);
701 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
702 		    ip_stack_t *ipst);
703 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
704 		    ip_stack_t *ipst);
705 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
706 		    ip_stack_t *ipst);
707 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
708 		    ip_stack_t *ipst);
709 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
710 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
711 static void	ip_snmp_get2_v4_media(ncec_t *, void *);
712 static void	ip_snmp_get2_v6_media(ncec_t *, void *);
713 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
714 
715 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
716 		    mblk_t *);
717 
718 static void	conn_drain_init(ip_stack_t *);
719 static void	conn_drain_fini(ip_stack_t *);
720 static void	conn_drain(conn_t *connp, boolean_t closing);
721 
722 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
723 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
724 
725 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
726 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
727 static void	ip_stack_fini(netstackid_t stackid, void *arg);
728 
729 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
730     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
731     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
732     const in6_addr_t *);
733 
734 static int	ip_squeue_switch(int);
735 
736 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
737 static void	ip_kstat_fini(netstackid_t, kstat_t *);
738 static int	ip_kstat_update(kstat_t *kp, int rw);
739 static void	*icmp_kstat_init(netstackid_t);
740 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
741 static int	icmp_kstat_update(kstat_t *kp, int rw);
742 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
743 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
744 
745 static void	ipobs_init(ip_stack_t *);
746 static void	ipobs_fini(ip_stack_t *);
747 
748 static int	ip_tp_cpu_update(cpu_setup_t, int, void *);
749 
750 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
751 
752 static long ip_rput_pullups;
753 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
754 
755 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
756 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
757 
758 int	ip_debug;
759 
760 /*
761  * Multirouting/CGTP stuff
762  */
763 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
764 
765 /*
766  * IP tunables related declarations. Definitions are in ip_tunables.c
767  */
768 extern mod_prop_info_t ip_propinfo_tbl[];
769 extern int ip_propinfo_count;
770 
771 /*
772  * Table of IP ioctls encoding the various properties of the ioctl and
773  * indexed based on the last byte of the ioctl command. Occasionally there
774  * is a clash, and there is more than 1 ioctl with the same last byte.
775  * In such a case 1 ioctl is encoded in the ndx table and the remaining
776  * ioctls are encoded in the misc table. An entry in the ndx table is
777  * retrieved by indexing on the last byte of the ioctl command and comparing
778  * the ioctl command with the value in the ndx table. In the event of a
779  * mismatch the misc table is then searched sequentially for the desired
780  * ioctl command.
781  *
782  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
783  */
784 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
785 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
786 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
787 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
788 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
789 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
790 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
791 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
792 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
793 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
794 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
795 
796 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
797 			MISC_CMD, ip_siocaddrt, NULL },
798 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
799 			MISC_CMD, ip_siocdelrt, NULL },
800 
801 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
802 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
803 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
804 			IF_CMD, ip_sioctl_get_addr, NULL },
805 
806 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
807 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
808 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
809 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
810 
811 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
812 			IPI_PRIV | IPI_WR,
813 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
814 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
815 			IPI_MODOK | IPI_GET_CMD,
816 			IF_CMD, ip_sioctl_get_flags, NULL },
817 
818 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
819 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
820 
821 	/* copyin size cannot be coded for SIOCGIFCONF */
822 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
823 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
824 
825 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
826 			IF_CMD, ip_sioctl_mtu, NULL },
827 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
828 			IF_CMD, ip_sioctl_get_mtu, NULL },
829 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
830 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
831 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
832 			IF_CMD, ip_sioctl_brdaddr, NULL },
833 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
834 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
835 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
836 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
837 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
838 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
839 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
840 			IF_CMD, ip_sioctl_metric, NULL },
841 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
842 
843 	/* See 166-168 below for extended SIOC*XARP ioctls */
844 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
845 			ARP_CMD, ip_sioctl_arp, NULL },
846 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
847 			ARP_CMD, ip_sioctl_arp, NULL },
848 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
849 			ARP_CMD, ip_sioctl_arp, NULL },
850 
851 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
852 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
853 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
854 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
855 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
856 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
857 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
858 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
859 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
860 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
861 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
862 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
863 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
864 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
865 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
866 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
867 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
868 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
869 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
870 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
871 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
872 
873 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
874 			MISC_CMD, if_unitsel, if_unitsel_restart },
875 
876 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
877 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
878 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
879 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
880 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
881 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
882 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
883 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
884 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
885 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
886 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
887 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
888 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
889 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
890 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
891 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
892 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
893 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
894 
895 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
896 			IPI_PRIV | IPI_WR | IPI_MODOK,
897 			IF_CMD, ip_sioctl_sifname, NULL },
898 
899 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
900 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
901 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
902 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
903 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
904 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
905 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
906 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
907 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
908 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
909 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
910 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
911 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
912 
913 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
914 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
915 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
916 			IF_CMD, ip_sioctl_get_muxid, NULL },
917 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
918 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
919 
920 	/* Both if and lif variants share same func */
921 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
922 			IF_CMD, ip_sioctl_get_lifindex, NULL },
923 	/* Both if and lif variants share same func */
924 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
925 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
926 
927 	/* copyin size cannot be coded for SIOCGIFCONF */
928 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
929 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
930 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
931 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
932 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
933 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
934 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
935 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
936 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
937 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
938 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
939 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
940 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
941 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
942 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
943 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
944 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
945 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
946 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
947 
948 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
949 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
950 			ip_sioctl_removeif_restart },
951 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
952 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
953 			LIF_CMD, ip_sioctl_addif, NULL },
954 #define	SIOCLIFADDR_NDX 112
955 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
956 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
957 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
958 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
959 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
960 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
961 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
962 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
963 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
964 			IPI_PRIV | IPI_WR,
965 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
966 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
967 			IPI_GET_CMD | IPI_MODOK,
968 			LIF_CMD, ip_sioctl_get_flags, NULL },
969 
970 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
971 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
972 
973 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
974 			ip_sioctl_get_lifconf, NULL },
975 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
976 			LIF_CMD, ip_sioctl_mtu, NULL },
977 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
978 			LIF_CMD, ip_sioctl_get_mtu, NULL },
979 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
980 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
981 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
982 			LIF_CMD, ip_sioctl_brdaddr, NULL },
983 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
984 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
985 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
986 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
987 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
988 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
989 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
990 			LIF_CMD, ip_sioctl_metric, NULL },
991 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
992 			IPI_PRIV | IPI_WR | IPI_MODOK,
993 			LIF_CMD, ip_sioctl_slifname,
994 			ip_sioctl_slifname_restart },
995 
996 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
997 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
998 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
999 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1000 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1001 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1002 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1003 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1004 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1005 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1006 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1007 			LIF_CMD, ip_sioctl_token, NULL },
1008 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1009 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1010 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1011 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1012 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1013 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1014 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1015 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1016 
1017 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1018 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1019 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1020 			LIF_CMD, ip_siocdelndp_v6, NULL },
1021 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1022 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1023 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1024 			LIF_CMD, ip_siocsetndp_v6, NULL },
1025 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1026 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1027 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1028 			MISC_CMD, ip_sioctl_tonlink, NULL },
1029 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1030 			MISC_CMD, ip_sioctl_tmysite, NULL },
1031 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 
1034 	/* Old *IPSECONFIG ioctls are now deprecated, now see spdsock.c */
1035 	/* 149 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 150 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 151 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 152 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 
1040 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 
1042 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1043 			LIF_CMD, ip_sioctl_get_binding, NULL },
1044 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1045 			IPI_PRIV | IPI_WR,
1046 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1047 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1048 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1049 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1050 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1051 
1052 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1053 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 
1057 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 
1059 	/* These are handled in ip_sioctl_copyin_setup itself */
1060 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1061 			MISC_CMD, NULL, NULL },
1062 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1063 			MISC_CMD, NULL, NULL },
1064 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1065 
1066 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1067 			ip_sioctl_get_lifconf, NULL },
1068 
1069 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1070 			XARP_CMD, ip_sioctl_arp, NULL },
1071 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1072 			XARP_CMD, ip_sioctl_arp, NULL },
1073 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1074 			XARP_CMD, ip_sioctl_arp, NULL },
1075 
1076 	/* SIOCPOPSOCKFS is not handled by IP */
1077 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1078 
1079 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1080 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1081 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1082 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1083 			ip_sioctl_slifzone_restart },
1084 	/* 172-174 are SCTP ioctls and not handled by IP */
1085 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1087 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1088 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1089 			IPI_GET_CMD, LIF_CMD,
1090 			ip_sioctl_get_lifusesrc, 0 },
1091 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1092 			IPI_PRIV | IPI_WR,
1093 			LIF_CMD, ip_sioctl_slifusesrc,
1094 			NULL },
1095 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1096 			ip_sioctl_get_lifsrcof, NULL },
1097 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1098 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1099 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1100 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1101 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1102 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1103 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1104 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1105 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* SIOCSENABLESDP is handled by SDP */
1107 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1108 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1109 	/* 185 */ { SIOCGIFHWADDR, sizeof (struct ifreq), IPI_GET_CMD,
1110 			IF_CMD, ip_sioctl_get_ifhwaddr, NULL },
1111 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1112 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1113 			ip_sioctl_ilb_cmd, NULL },
1114 	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1115 	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1116 	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1117 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1118 	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1119 			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart },
1120 	/* 192 */ { SIOCGLIFHWADDR, sizeof (struct lifreq), IPI_GET_CMD,
1121 			LIF_CMD, ip_sioctl_get_lifhwaddr, NULL }
1122 };
1123 
1124 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1125 
1126 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1127 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1128 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1129 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1130 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1131 	{ ND_GET,	0, 0, 0, NULL, NULL },
1132 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1133 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1134 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1135 		MISC_CMD, mrt_ioctl},
1136 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1137 		MISC_CMD, mrt_ioctl},
1138 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1139 		MISC_CMD, mrt_ioctl}
1140 };
1141 
1142 int ip_misc_ioctl_count =
1143     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1144 
1145 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1146 					/* Settable in /etc/system */
1147 /* Defined in ip_ire.c */
1148 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1149 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1150 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1151 
1152 static nv_t	ire_nv_arr[] = {
1153 	{ IRE_BROADCAST, "BROADCAST" },
1154 	{ IRE_LOCAL, "LOCAL" },
1155 	{ IRE_LOOPBACK, "LOOPBACK" },
1156 	{ IRE_DEFAULT, "DEFAULT" },
1157 	{ IRE_PREFIX, "PREFIX" },
1158 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1159 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1160 	{ IRE_IF_CLONE, "IF_CLONE" },
1161 	{ IRE_HOST, "HOST" },
1162 	{ IRE_MULTICAST, "MULTICAST" },
1163 	{ IRE_NOROUTE, "NOROUTE" },
1164 	{ 0 }
1165 };
1166 
1167 nv_t	*ire_nv_tbl = ire_nv_arr;
1168 
1169 /* Simple ICMP IP Header Template */
1170 static ipha_t icmp_ipha = {
1171 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1172 };
1173 
1174 struct module_info ip_mod_info = {
1175 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1176 	IP_MOD_LOWAT
1177 };
1178 
1179 /*
1180  * Duplicate static symbols within a module confuses mdb; so we avoid the
1181  * problem by making the symbols here distinct from those in udp.c.
1182  */
1183 
1184 /*
1185  * Entry points for IP as a device and as a module.
1186  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1187  */
1188 static struct qinit iprinitv4 = {
1189 	ip_rput, NULL, ip_openv4, ip_close, NULL, &ip_mod_info
1190 };
1191 
1192 struct qinit iprinitv6 = {
1193 	ip_rput_v6, NULL, ip_openv6, ip_close, NULL, &ip_mod_info
1194 };
1195 
1196 static struct qinit ipwinit = {
1197 	ip_wput_nondata, ip_wsrv, NULL, NULL, NULL, &ip_mod_info
1198 };
1199 
1200 static struct qinit iplrinit = {
1201 	ip_lrput, NULL, ip_openv4, ip_close, NULL, &ip_mod_info
1202 };
1203 
1204 static struct qinit iplwinit = {
1205 	ip_lwput, NULL, NULL, NULL, NULL, &ip_mod_info
1206 };
1207 
1208 /* For AF_INET aka /dev/ip */
1209 struct streamtab ipinfov4 = {
1210 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1211 };
1212 
1213 /* For AF_INET6 aka /dev/ip6 */
1214 struct streamtab ipinfov6 = {
1215 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1216 };
1217 
1218 #ifdef	DEBUG
1219 boolean_t skip_sctp_cksum = B_FALSE;
1220 #endif
1221 
1222 /*
1223  * Generate an ICMP fragmentation needed message.
1224  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1225  * constructed by the caller.
1226  */
1227 void
1228 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1229 {
1230 	icmph_t	icmph;
1231 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1232 
1233 	mp = icmp_pkt_err_ok(mp, ira);
1234 	if (mp == NULL)
1235 		return;
1236 
1237 	bzero(&icmph, sizeof (icmph_t));
1238 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1239 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1240 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1241 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1242 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1243 
1244 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1245 }
1246 
1247 /*
1248  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1249  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1250  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1251  * Likewise, if the ICMP error is misformed (too short, etc), then it
1252  * returns NULL. The caller uses this to determine whether or not to send
1253  * to raw sockets.
1254  *
1255  * All error messages are passed to the matching transport stream.
1256  *
1257  * The following cases are handled by icmp_inbound:
1258  * 1) It needs to send a reply back and possibly delivering it
1259  *    to the "interested" upper clients.
1260  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1261  * 3) It needs to change some values in IP only.
1262  * 4) It needs to change some values in IP and upper layers e.g TCP
1263  *    by delivering an error to the upper layers.
1264  *
1265  * We handle the above three cases in the context of IPsec in the
1266  * following way :
1267  *
1268  * 1) Send the reply back in the same way as the request came in.
1269  *    If it came in encrypted, it goes out encrypted. If it came in
1270  *    clear, it goes out in clear. Thus, this will prevent chosen
1271  *    plain text attack.
1272  * 2) The client may or may not expect things to come in secure.
1273  *    If it comes in secure, the policy constraints are checked
1274  *    before delivering it to the upper layers. If it comes in
1275  *    clear, ipsec_inbound_accept_clear will decide whether to
1276  *    accept this in clear or not. In both the cases, if the returned
1277  *    message (IP header + 8 bytes) that caused the icmp message has
1278  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1279  *    sending up. If there are only 8 bytes of returned message, then
1280  *    upper client will not be notified.
1281  * 3) Check with global policy to see whether it matches the constaints.
1282  *    But this will be done only if icmp_accept_messages_in_clear is
1283  *    zero.
1284  * 4) If we need to change both in IP and ULP, then the decision taken
1285  *    while affecting the values in IP and while delivering up to TCP
1286  *    should be the same.
1287  *
1288  *	There are two cases.
1289  *
1290  *	a) If we reject data at the IP layer (ipsec_check_global_policy()
1291  *	   failed), we will not deliver it to the ULP, even though they
1292  *	   are *willing* to accept in *clear*. This is fine as our global
1293  *	   disposition to icmp messages asks us reject the datagram.
1294  *
1295  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1296  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1297  *	   to deliver it to ULP (policy failed), it can lead to
1298  *	   consistency problems. The cases known at this time are
1299  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1300  *	   values :
1301  *
1302  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1303  *	     and Upper layer rejects. Then the communication will
1304  *	     come to a stop. This is solved by making similar decisions
1305  *	     at both levels. Currently, when we are unable to deliver
1306  *	     to the Upper Layer (due to policy failures) while IP has
1307  *	     adjusted dce_pmtu, the next outbound datagram would
1308  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1309  *	     will be with the right level of protection. Thus the right
1310  *	     value will be communicated even if we are not able to
1311  *	     communicate when we get from the wire initially. But this
1312  *	     assumes there would be at least one outbound datagram after
1313  *	     IP has adjusted its dce_pmtu value. To make things
1314  *	     simpler, we accept in clear after the validation of
1315  *	     AH/ESP headers.
1316  *
1317  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1318  *	     upper layer depending on the level of protection the upper
1319  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1320  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1321  *	     should be accepted in clear when the Upper layer expects secure.
1322  *	     Thus the communication may get aborted by some bad ICMP
1323  *	     packets.
1324  */
1325 mblk_t *
1326 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1327 {
1328 	icmph_t		*icmph;
1329 	ipha_t		*ipha;		/* Outer header */
1330 	int		ip_hdr_length;	/* Outer header length */
1331 	boolean_t	interested;
1332 	ipif_t		*ipif;
1333 	uint32_t	ts;
1334 	uint32_t	*tsp;
1335 	timestruc_t	now;
1336 	ill_t		*ill = ira->ira_ill;
1337 	ip_stack_t	*ipst = ill->ill_ipst;
1338 	zoneid_t	zoneid = ira->ira_zoneid;
1339 	int		len_needed;
1340 	mblk_t		*mp_ret = NULL;
1341 
1342 	ipha = (ipha_t *)mp->b_rptr;
1343 
1344 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1345 
1346 	ip_hdr_length = ira->ira_ip_hdr_length;
1347 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1348 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1349 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1350 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1351 			freemsg(mp);
1352 			return (NULL);
1353 		}
1354 		/* Last chance to get real. */
1355 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1356 		if (ipha == NULL) {
1357 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1358 			freemsg(mp);
1359 			return (NULL);
1360 		}
1361 	}
1362 
1363 	/* The IP header will always be a multiple of four bytes */
1364 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1365 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1366 	    icmph->icmph_code));
1367 
1368 	/*
1369 	 * We will set "interested" to "true" if we should pass a copy to
1370 	 * the transport or if we handle the packet locally.
1371 	 */
1372 	interested = B_FALSE;
1373 	switch (icmph->icmph_type) {
1374 	case ICMP_ECHO_REPLY:
1375 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1376 		break;
1377 	case ICMP_DEST_UNREACHABLE:
1378 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1379 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1380 		interested = B_TRUE;	/* Pass up to transport */
1381 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1382 		break;
1383 	case ICMP_SOURCE_QUENCH:
1384 		interested = B_TRUE;	/* Pass up to transport */
1385 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1386 		break;
1387 	case ICMP_REDIRECT:
1388 		if (!ipst->ips_ip_ignore_redirect)
1389 			interested = B_TRUE;
1390 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1391 		break;
1392 	case ICMP_ECHO_REQUEST:
1393 		/*
1394 		 * Whether to respond to echo requests that come in as IP
1395 		 * broadcasts or as IP multicast is subject to debate
1396 		 * (what isn't?).  We aim to please, you pick it.
1397 		 * Default is do it.
1398 		 */
1399 		if (ira->ira_flags & IRAF_MULTICAST) {
1400 			/* multicast: respond based on tunable */
1401 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1402 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1403 			/* broadcast: respond based on tunable */
1404 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1405 		} else {
1406 			/* unicast: always respond */
1407 			interested = B_TRUE;
1408 		}
1409 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1410 		if (!interested) {
1411 			/* We never pass these to RAW sockets */
1412 			freemsg(mp);
1413 			return (NULL);
1414 		}
1415 
1416 		/* Check db_ref to make sure we can modify the packet. */
1417 		if (mp->b_datap->db_ref > 1) {
1418 			mblk_t	*mp1;
1419 
1420 			mp1 = copymsg(mp);
1421 			freemsg(mp);
1422 			if (!mp1) {
1423 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1424 				return (NULL);
1425 			}
1426 			mp = mp1;
1427 			ipha = (ipha_t *)mp->b_rptr;
1428 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1429 		}
1430 		icmph->icmph_type = ICMP_ECHO_REPLY;
1431 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1432 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1433 		return (NULL);
1434 
1435 	case ICMP_ROUTER_ADVERTISEMENT:
1436 	case ICMP_ROUTER_SOLICITATION:
1437 		break;
1438 	case ICMP_TIME_EXCEEDED:
1439 		interested = B_TRUE;	/* Pass up to transport */
1440 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1441 		break;
1442 	case ICMP_PARAM_PROBLEM:
1443 		interested = B_TRUE;	/* Pass up to transport */
1444 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1445 		break;
1446 	case ICMP_TIME_STAMP_REQUEST:
1447 		/* Response to Time Stamp Requests is local policy. */
1448 		if (ipst->ips_ip_g_resp_to_timestamp) {
1449 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1450 				interested =
1451 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1452 			else
1453 				interested = B_TRUE;
1454 		}
1455 		if (!interested) {
1456 			/* We never pass these to RAW sockets */
1457 			freemsg(mp);
1458 			return (NULL);
1459 		}
1460 
1461 		/* Make sure we have enough of the packet */
1462 		len_needed = ip_hdr_length + ICMPH_SIZE +
1463 		    3 * sizeof (uint32_t);
1464 
1465 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1466 			ipha = ip_pullup(mp, len_needed, ira);
1467 			if (ipha == NULL) {
1468 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1469 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1470 				    mp, ill);
1471 				freemsg(mp);
1472 				return (NULL);
1473 			}
1474 			/* Refresh following the pullup. */
1475 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1476 		}
1477 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1478 		/* Check db_ref to make sure we can modify the packet. */
1479 		if (mp->b_datap->db_ref > 1) {
1480 			mblk_t	*mp1;
1481 
1482 			mp1 = copymsg(mp);
1483 			freemsg(mp);
1484 			if (!mp1) {
1485 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1486 				return (NULL);
1487 			}
1488 			mp = mp1;
1489 			ipha = (ipha_t *)mp->b_rptr;
1490 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1491 		}
1492 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1493 		tsp = (uint32_t *)&icmph[1];
1494 		tsp++;		/* Skip past 'originate time' */
1495 		/* Compute # of milliseconds since midnight */
1496 		gethrestime(&now);
1497 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1498 		    NSEC2MSEC(now.tv_nsec);
1499 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1500 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1501 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1502 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1503 		return (NULL);
1504 
1505 	case ICMP_TIME_STAMP_REPLY:
1506 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1507 		break;
1508 	case ICMP_INFO_REQUEST:
1509 		/* Per RFC 1122 3.2.2.7, ignore this. */
1510 	case ICMP_INFO_REPLY:
1511 		break;
1512 	case ICMP_ADDRESS_MASK_REQUEST:
1513 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1514 			interested =
1515 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1516 		} else {
1517 			interested = B_TRUE;
1518 		}
1519 		if (!interested) {
1520 			/* We never pass these to RAW sockets */
1521 			freemsg(mp);
1522 			return (NULL);
1523 		}
1524 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1525 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1526 			ipha = ip_pullup(mp, len_needed, ira);
1527 			if (ipha == NULL) {
1528 				BUMP_MIB(ill->ill_ip_mib,
1529 				    ipIfStatsInTruncatedPkts);
1530 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1531 				    ill);
1532 				freemsg(mp);
1533 				return (NULL);
1534 			}
1535 			/* Refresh following the pullup. */
1536 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1537 		}
1538 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1539 		/* Check db_ref to make sure we can modify the packet. */
1540 		if (mp->b_datap->db_ref > 1) {
1541 			mblk_t	*mp1;
1542 
1543 			mp1 = copymsg(mp);
1544 			freemsg(mp);
1545 			if (!mp1) {
1546 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1547 				return (NULL);
1548 			}
1549 			mp = mp1;
1550 			ipha = (ipha_t *)mp->b_rptr;
1551 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1552 		}
1553 		/*
1554 		 * Need the ipif with the mask be the same as the source
1555 		 * address of the mask reply. For unicast we have a specific
1556 		 * ipif. For multicast/broadcast we only handle onlink
1557 		 * senders, and use the source address to pick an ipif.
1558 		 */
1559 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1560 		if (ipif == NULL) {
1561 			/* Broadcast or multicast */
1562 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1563 			if (ipif == NULL) {
1564 				freemsg(mp);
1565 				return (NULL);
1566 			}
1567 		}
1568 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1569 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1570 		ipif_refrele(ipif);
1571 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1572 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1573 		return (NULL);
1574 
1575 	case ICMP_ADDRESS_MASK_REPLY:
1576 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1577 		break;
1578 	default:
1579 		interested = B_TRUE;	/* Pass up to transport */
1580 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1581 		break;
1582 	}
1583 	/*
1584 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1585 	 * if there isn't one.
1586 	 */
1587 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1588 		/* If there is an ICMP client and we want one too, copy it. */
1589 
1590 		if (!interested) {
1591 			/* Caller will deliver to RAW sockets */
1592 			return (mp);
1593 		}
1594 		mp_ret = copymsg(mp);
1595 		if (mp_ret == NULL) {
1596 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1597 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1598 		}
1599 	} else if (!interested) {
1600 		/* Neither we nor raw sockets are interested. Drop packet now */
1601 		freemsg(mp);
1602 		return (NULL);
1603 	}
1604 
1605 	/*
1606 	 * ICMP error or redirect packet. Make sure we have enough of
1607 	 * the header and that db_ref == 1 since we might end up modifying
1608 	 * the packet.
1609 	 */
1610 	if (mp->b_cont != NULL) {
1611 		if (ip_pullup(mp, -1, ira) == NULL) {
1612 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1613 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1614 			    mp, ill);
1615 			freemsg(mp);
1616 			return (mp_ret);
1617 		}
1618 	}
1619 
1620 	if (mp->b_datap->db_ref > 1) {
1621 		mblk_t	*mp1;
1622 
1623 		mp1 = copymsg(mp);
1624 		if (mp1 == NULL) {
1625 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1626 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1627 			freemsg(mp);
1628 			return (mp_ret);
1629 		}
1630 		freemsg(mp);
1631 		mp = mp1;
1632 	}
1633 
1634 	/*
1635 	 * In case mp has changed, verify the message before any further
1636 	 * processes.
1637 	 */
1638 	ipha = (ipha_t *)mp->b_rptr;
1639 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1640 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1641 		freemsg(mp);
1642 		return (mp_ret);
1643 	}
1644 
1645 	switch (icmph->icmph_type) {
1646 	case ICMP_REDIRECT:
1647 		icmp_redirect_v4(mp, ipha, icmph, ira);
1648 		break;
1649 	case ICMP_DEST_UNREACHABLE:
1650 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1651 			/* Update DCE and adjust MTU is icmp header if needed */
1652 			icmp_inbound_too_big_v4(icmph, ira);
1653 		}
1654 		/* FALLTHROUGH */
1655 	default:
1656 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1657 		break;
1658 	}
1659 	return (mp_ret);
1660 }
1661 
1662 /*
1663  * Send an ICMP echo, timestamp or address mask reply.
1664  * The caller has already updated the payload part of the packet.
1665  * We handle the ICMP checksum, IP source address selection and feed
1666  * the packet into ip_output_simple.
1667  */
1668 static void
1669 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1670     ip_recv_attr_t *ira)
1671 {
1672 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1673 	ill_t		*ill = ira->ira_ill;
1674 	ip_stack_t	*ipst = ill->ill_ipst;
1675 	ip_xmit_attr_t	ixas;
1676 
1677 	/* Send out an ICMP packet */
1678 	icmph->icmph_checksum = 0;
1679 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1680 	/* Reset time to live. */
1681 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1682 	{
1683 		/* Swap source and destination addresses */
1684 		ipaddr_t tmp;
1685 
1686 		tmp = ipha->ipha_src;
1687 		ipha->ipha_src = ipha->ipha_dst;
1688 		ipha->ipha_dst = tmp;
1689 	}
1690 	ipha->ipha_ident = 0;
1691 	if (!IS_SIMPLE_IPH(ipha))
1692 		icmp_options_update(ipha);
1693 
1694 	bzero(&ixas, sizeof (ixas));
1695 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1696 	ixas.ixa_zoneid = ira->ira_zoneid;
1697 	ixas.ixa_cred = kcred;
1698 	ixas.ixa_cpid = NOPID;
1699 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1700 	ixas.ixa_ifindex = 0;
1701 	ixas.ixa_ipst = ipst;
1702 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1703 
1704 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1705 		/*
1706 		 * This packet should go out the same way as it
1707 		 * came in i.e in clear, independent of the IPsec policy
1708 		 * for transmitting packets.
1709 		 */
1710 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1711 	} else {
1712 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1713 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1714 			/* Note: mp already consumed and ip_drop_packet done */
1715 			return;
1716 		}
1717 	}
1718 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1719 		/*
1720 		 * Not one or our addresses (IRE_LOCALs), thus we let
1721 		 * ip_output_simple pick the source.
1722 		 */
1723 		ipha->ipha_src = INADDR_ANY;
1724 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1725 	}
1726 	/* Should we send with DF and use dce_pmtu? */
1727 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1728 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1729 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1730 	}
1731 
1732 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1733 
1734 	(void) ip_output_simple(mp, &ixas);
1735 	ixa_cleanup(&ixas);
1736 }
1737 
1738 /*
1739  * Verify the ICMP messages for either for ICMP error or redirect packet.
1740  * The caller should have fully pulled up the message. If it's a redirect
1741  * packet, only basic checks on IP header will be done; otherwise, verify
1742  * the packet by looking at the included ULP header.
1743  *
1744  * Called before icmp_inbound_error_fanout_v4 is called.
1745  */
1746 static boolean_t
1747 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1748 {
1749 	ill_t		*ill = ira->ira_ill;
1750 	int		hdr_length;
1751 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1752 	conn_t		*connp;
1753 	ipha_t		*ipha;	/* Inner IP header */
1754 
1755 	ipha = (ipha_t *)&icmph[1];
1756 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1757 		goto truncated;
1758 
1759 	hdr_length = IPH_HDR_LENGTH(ipha);
1760 
1761 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1762 		goto discard_pkt;
1763 
1764 	if (hdr_length < sizeof (ipha_t))
1765 		goto truncated;
1766 
1767 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1768 		goto truncated;
1769 
1770 	/*
1771 	 * Stop here for ICMP_REDIRECT.
1772 	 */
1773 	if (icmph->icmph_type == ICMP_REDIRECT)
1774 		return (B_TRUE);
1775 
1776 	/*
1777 	 * ICMP errors only.
1778 	 */
1779 	switch (ipha->ipha_protocol) {
1780 	case IPPROTO_UDP:
1781 		/*
1782 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1783 		 * transport header.
1784 		 */
1785 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1786 		    mp->b_wptr)
1787 			goto truncated;
1788 		break;
1789 	case IPPROTO_TCP: {
1790 		tcpha_t		*tcpha;
1791 
1792 		/*
1793 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1794 		 * transport header.
1795 		 */
1796 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1797 		    mp->b_wptr)
1798 			goto truncated;
1799 
1800 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1801 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1802 		    ipst);
1803 		if (connp == NULL)
1804 			goto discard_pkt;
1805 
1806 		if ((connp->conn_verifyicmp != NULL) &&
1807 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1808 			CONN_DEC_REF(connp);
1809 			goto discard_pkt;
1810 		}
1811 		CONN_DEC_REF(connp);
1812 		break;
1813 	}
1814 	case IPPROTO_SCTP:
1815 		/*
1816 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1817 		 * transport header.
1818 		 */
1819 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1820 		    mp->b_wptr)
1821 			goto truncated;
1822 		break;
1823 	case IPPROTO_ESP:
1824 	case IPPROTO_AH:
1825 		break;
1826 	case IPPROTO_ENCAP:
1827 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1828 		    mp->b_wptr)
1829 			goto truncated;
1830 		break;
1831 	default:
1832 		break;
1833 	}
1834 
1835 	return (B_TRUE);
1836 
1837 discard_pkt:
1838 	/* Bogus ICMP error. */
1839 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1840 	return (B_FALSE);
1841 
1842 truncated:
1843 	/* We pulled up everthing already. Must be truncated */
1844 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1845 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1846 	return (B_FALSE);
1847 }
1848 
1849 /* Table from RFC 1191 */
1850 static int icmp_frag_size_table[] =
1851 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1852 
1853 /*
1854  * Process received ICMP Packet too big.
1855  * Just handles the DCE create/update, including using the above table of
1856  * PMTU guesses. The caller is responsible for validating the packet before
1857  * passing it in and also to fanout the ICMP error to any matching transport
1858  * conns. Assumes the message has been fully pulled up and verified.
1859  *
1860  * Before getting here, the caller has called icmp_inbound_verify_v4()
1861  * that should have verified with ULP to prevent undoing the changes we're
1862  * going to make to DCE. For example, TCP might have verified that the packet
1863  * which generated error is in the send window.
1864  *
1865  * In some cases modified this MTU in the ICMP header packet; the caller
1866  * should pass to the matching ULP after this returns.
1867  */
1868 static void
1869 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1870 {
1871 	dce_t		*dce;
1872 	int		old_mtu;
1873 	int		mtu, orig_mtu;
1874 	ipaddr_t	dst;
1875 	boolean_t	disable_pmtud;
1876 	ill_t		*ill = ira->ira_ill;
1877 	ip_stack_t	*ipst = ill->ill_ipst;
1878 	uint_t		hdr_length;
1879 	ipha_t		*ipha;
1880 
1881 	/* Caller already pulled up everything. */
1882 	ipha = (ipha_t *)&icmph[1];
1883 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1884 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1885 	ASSERT(ill != NULL);
1886 
1887 	hdr_length = IPH_HDR_LENGTH(ipha);
1888 
1889 	/*
1890 	 * We handle path MTU for source routed packets since the DCE
1891 	 * is looked up using the final destination.
1892 	 */
1893 	dst = ip_get_dst(ipha);
1894 
1895 	dce = dce_lookup_and_add_v4(dst, ipst);
1896 	if (dce == NULL) {
1897 		/* Couldn't add a unique one - ENOMEM */
1898 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1899 		    ntohl(dst)));
1900 		return;
1901 	}
1902 
1903 	/* Check for MTU discovery advice as described in RFC 1191 */
1904 	mtu = ntohs(icmph->icmph_du_mtu);
1905 	orig_mtu = mtu;
1906 	disable_pmtud = B_FALSE;
1907 
1908 	mutex_enter(&dce->dce_lock);
1909 	if (dce->dce_flags & DCEF_PMTU)
1910 		old_mtu = dce->dce_pmtu;
1911 	else
1912 		old_mtu = ill->ill_mtu;
1913 
1914 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1915 		uint32_t length;
1916 		int	i;
1917 
1918 		/*
1919 		 * Use the table from RFC 1191 to figure out
1920 		 * the next "plateau" based on the length in
1921 		 * the original IP packet.
1922 		 */
1923 		length = ntohs(ipha->ipha_length);
1924 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1925 		    uint32_t, length);
1926 		if (old_mtu <= length &&
1927 		    old_mtu >= length - hdr_length) {
1928 			/*
1929 			 * Handle broken BSD 4.2 systems that
1930 			 * return the wrong ipha_length in ICMP
1931 			 * errors.
1932 			 */
1933 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1934 			    length, old_mtu));
1935 			length -= hdr_length;
1936 		}
1937 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1938 			if (length > icmp_frag_size_table[i])
1939 				break;
1940 		}
1941 		if (i == A_CNT(icmp_frag_size_table)) {
1942 			/* Smaller than IP_MIN_MTU! */
1943 			ip1dbg(("Too big for packet size %d\n",
1944 			    length));
1945 			disable_pmtud = B_TRUE;
1946 			mtu = ipst->ips_ip_pmtu_min;
1947 		} else {
1948 			mtu = icmp_frag_size_table[i];
1949 			ip1dbg(("Calculated mtu %d, packet size %d, "
1950 			    "before %d\n", mtu, length, old_mtu));
1951 			if (mtu < ipst->ips_ip_pmtu_min) {
1952 				mtu = ipst->ips_ip_pmtu_min;
1953 				disable_pmtud = B_TRUE;
1954 			}
1955 		}
1956 	}
1957 	if (disable_pmtud)
1958 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1959 	else
1960 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1961 
1962 	dce->dce_pmtu = MIN(old_mtu, mtu);
1963 	/* Prepare to send the new max frag size for the ULP. */
1964 	icmph->icmph_du_zero = 0;
1965 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1966 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1967 	    dce, int, orig_mtu, int, mtu);
1968 
1969 	/* We now have a PMTU for sure */
1970 	dce->dce_flags |= DCEF_PMTU;
1971 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1972 	mutex_exit(&dce->dce_lock);
1973 	/*
1974 	 * After dropping the lock the new value is visible to everyone.
1975 	 * Then we bump the generation number so any cached values reinspect
1976 	 * the dce_t.
1977 	 */
1978 	dce_increment_generation(dce);
1979 	dce_refrele(dce);
1980 }
1981 
1982 /*
1983  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1984  * calls this function.
1985  */
1986 static mblk_t *
1987 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1988 {
1989 	int length;
1990 
1991 	ASSERT(mp->b_datap->db_type == M_DATA);
1992 
1993 	/* icmp_inbound_v4 has already pulled up the whole error packet */
1994 	ASSERT(mp->b_cont == NULL);
1995 
1996 	/*
1997 	 * The length that we want to overlay is the inner header
1998 	 * and what follows it.
1999 	 */
2000 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
2001 
2002 	/*
2003 	 * Overlay the inner header and whatever follows it over the
2004 	 * outer header.
2005 	 */
2006 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2007 
2008 	/* Adjust for what we removed */
2009 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2010 	return (mp);
2011 }
2012 
2013 /*
2014  * Try to pass the ICMP message upstream in case the ULP cares.
2015  *
2016  * If the packet that caused the ICMP error is secure, we send
2017  * it to AH/ESP to make sure that the attached packet has a
2018  * valid association. ipha in the code below points to the
2019  * IP header of the packet that caused the error.
2020  *
2021  * For IPsec cases, we let the next-layer-up (which has access to
2022  * cached policy on the conn_t, or can query the SPD directly)
2023  * subtract out any IPsec overhead if they must.  We therefore make no
2024  * adjustments here for IPsec overhead.
2025  *
2026  * IFN could have been generated locally or by some router.
2027  *
2028  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2029  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2030  *	    This happens because IP adjusted its value of MTU on an
2031  *	    earlier IFN message and could not tell the upper layer,
2032  *	    the new adjusted value of MTU e.g. Packet was encrypted
2033  *	    or there was not enough information to fanout to upper
2034  *	    layers. Thus on the next outbound datagram, ire_send_wire
2035  *	    generates the IFN, where IPsec processing has *not* been
2036  *	    done.
2037  *
2038  *	    Note that we retain ixa_fragsize across IPsec thus once
2039  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2040  *	    no change the fragsize even if the path MTU changes before
2041  *	    we reach ip_output_post_ipsec.
2042  *
2043  *	    In the local case, IRAF_LOOPBACK will be set indicating
2044  *	    that IFN was generated locally.
2045  *
2046  * ROUTER : IFN could be secure or non-secure.
2047  *
2048  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2049  *	      packet in error has AH/ESP headers to validate the AH/ESP
2050  *	      headers. AH/ESP will verify whether there is a valid SA or
2051  *	      not and send it back. We will fanout again if we have more
2052  *	      data in the packet.
2053  *
2054  *	      If the packet in error does not have AH/ESP, we handle it
2055  *	      like any other case.
2056  *
2057  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2058  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2059  *	      valid SA or not and send it back. We will fanout again if
2060  *	      we have more data in the packet.
2061  *
2062  *	      If the packet in error does not have AH/ESP, we handle it
2063  *	      like any other case.
2064  *
2065  * The caller must have called icmp_inbound_verify_v4.
2066  */
2067 static void
2068 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2069 {
2070 	uint16_t	*up;	/* Pointer to ports in ULP header */
2071 	uint32_t	ports;	/* reversed ports for fanout */
2072 	ipha_t		ripha;	/* With reversed addresses */
2073 	ipha_t		*ipha;  /* Inner IP header */
2074 	uint_t		hdr_length; /* Inner IP header length */
2075 	tcpha_t		*tcpha;
2076 	conn_t		*connp;
2077 	ill_t		*ill = ira->ira_ill;
2078 	ip_stack_t	*ipst = ill->ill_ipst;
2079 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2080 	ill_t		*rill = ira->ira_rill;
2081 
2082 	/* Caller already pulled up everything. */
2083 	ipha = (ipha_t *)&icmph[1];
2084 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2085 	ASSERT(mp->b_cont == NULL);
2086 
2087 	hdr_length = IPH_HDR_LENGTH(ipha);
2088 	ira->ira_protocol = ipha->ipha_protocol;
2089 
2090 	/*
2091 	 * We need a separate IP header with the source and destination
2092 	 * addresses reversed to do fanout/classification because the ipha in
2093 	 * the ICMP error is in the form we sent it out.
2094 	 */
2095 	ripha.ipha_src = ipha->ipha_dst;
2096 	ripha.ipha_dst = ipha->ipha_src;
2097 	ripha.ipha_protocol = ipha->ipha_protocol;
2098 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2099 
2100 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2101 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2102 	    ntohl(ipha->ipha_dst),
2103 	    icmph->icmph_type, icmph->icmph_code));
2104 
2105 	switch (ipha->ipha_protocol) {
2106 	case IPPROTO_UDP:
2107 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2108 
2109 		/* Attempt to find a client stream based on port. */
2110 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2111 		    ntohs(up[0]), ntohs(up[1])));
2112 
2113 		/* Note that we send error to all matches. */
2114 		ira->ira_flags |= IRAF_ICMP_ERROR;
2115 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2116 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2117 		return;
2118 
2119 	case IPPROTO_TCP:
2120 		/*
2121 		 * Find a TCP client stream for this packet.
2122 		 * Note that we do a reverse lookup since the header is
2123 		 * in the form we sent it out.
2124 		 */
2125 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2126 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2127 		    ipst);
2128 		if (connp == NULL)
2129 			goto discard_pkt;
2130 
2131 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2132 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2133 			mp = ipsec_check_inbound_policy(mp, connp,
2134 			    ipha, NULL, ira);
2135 			if (mp == NULL) {
2136 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2137 				/* Note that mp is NULL */
2138 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2139 				CONN_DEC_REF(connp);
2140 				return;
2141 			}
2142 		}
2143 
2144 		ira->ira_flags |= IRAF_ICMP_ERROR;
2145 		ira->ira_ill = ira->ira_rill = NULL;
2146 		if (IPCL_IS_TCP(connp)) {
2147 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2148 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2149 			    SQTAG_TCP_INPUT_ICMP_ERR);
2150 		} else {
2151 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2152 			(connp->conn_recv)(connp, mp, NULL, ira);
2153 			CONN_DEC_REF(connp);
2154 		}
2155 		ira->ira_ill = ill;
2156 		ira->ira_rill = rill;
2157 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2158 		return;
2159 
2160 	case IPPROTO_SCTP:
2161 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2162 		/* Find a SCTP client stream for this packet. */
2163 		((uint16_t *)&ports)[0] = up[1];
2164 		((uint16_t *)&ports)[1] = up[0];
2165 
2166 		ira->ira_flags |= IRAF_ICMP_ERROR;
2167 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2168 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2169 		return;
2170 
2171 	case IPPROTO_ESP:
2172 	case IPPROTO_AH:
2173 		if (!ipsec_loaded(ipss)) {
2174 			ip_proto_not_sup(mp, ira);
2175 			return;
2176 		}
2177 
2178 		if (ipha->ipha_protocol == IPPROTO_ESP)
2179 			mp = ipsecesp_icmp_error(mp, ira);
2180 		else
2181 			mp = ipsecah_icmp_error(mp, ira);
2182 		if (mp == NULL)
2183 			return;
2184 
2185 		/* Just in case ipsec didn't preserve the NULL b_cont */
2186 		if (mp->b_cont != NULL) {
2187 			if (!pullupmsg(mp, -1))
2188 				goto discard_pkt;
2189 		}
2190 
2191 		/*
2192 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2193 		 * correct, but we don't use them any more here.
2194 		 *
2195 		 * If succesful, the mp has been modified to not include
2196 		 * the ESP/AH header so we can fanout to the ULP's icmp
2197 		 * error handler.
2198 		 */
2199 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2200 			goto truncated;
2201 
2202 		/* Verify the modified message before any further processes. */
2203 		ipha = (ipha_t *)mp->b_rptr;
2204 		hdr_length = IPH_HDR_LENGTH(ipha);
2205 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2206 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2207 			freemsg(mp);
2208 			return;
2209 		}
2210 
2211 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2212 		return;
2213 
2214 	case IPPROTO_ENCAP: {
2215 		/* Look for self-encapsulated packets that caused an error */
2216 		ipha_t *in_ipha;
2217 
2218 		/*
2219 		 * Caller has verified that length has to be
2220 		 * at least the size of IP header.
2221 		 */
2222 		ASSERT(hdr_length >= sizeof (ipha_t));
2223 		/*
2224 		 * Check the sanity of the inner IP header like
2225 		 * we did for the outer header.
2226 		 */
2227 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2228 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2229 			goto discard_pkt;
2230 		}
2231 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2232 			goto discard_pkt;
2233 		}
2234 		/* Check for Self-encapsulated tunnels */
2235 		if (in_ipha->ipha_src == ipha->ipha_src &&
2236 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2237 
2238 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2239 			    in_ipha);
2240 			if (mp == NULL)
2241 				goto discard_pkt;
2242 
2243 			/*
2244 			 * Just in case self_encap didn't preserve the NULL
2245 			 * b_cont
2246 			 */
2247 			if (mp->b_cont != NULL) {
2248 				if (!pullupmsg(mp, -1))
2249 					goto discard_pkt;
2250 			}
2251 			/*
2252 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2253 			 * longer correct, but we don't use them any more here.
2254 			 */
2255 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2256 				goto truncated;
2257 
2258 			/*
2259 			 * Verify the modified message before any further
2260 			 * processes.
2261 			 */
2262 			ipha = (ipha_t *)mp->b_rptr;
2263 			hdr_length = IPH_HDR_LENGTH(ipha);
2264 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2265 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2266 				freemsg(mp);
2267 				return;
2268 			}
2269 
2270 			/*
2271 			 * The packet in error is self-encapsualted.
2272 			 * And we are finding it further encapsulated
2273 			 * which we could not have possibly generated.
2274 			 */
2275 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2276 				goto discard_pkt;
2277 			}
2278 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2279 			return;
2280 		}
2281 		/* No self-encapsulated */
2282 	}
2283 	/* FALLTHROUGH */
2284 	case IPPROTO_IPV6:
2285 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2286 		    &ripha.ipha_dst, ipst)) != NULL) {
2287 			ira->ira_flags |= IRAF_ICMP_ERROR;
2288 			connp->conn_recvicmp(connp, mp, NULL, ira);
2289 			CONN_DEC_REF(connp);
2290 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2291 			return;
2292 		}
2293 		/*
2294 		 * No IP tunnel is interested, fallthrough and see
2295 		 * if a raw socket will want it.
2296 		 */
2297 		/* FALLTHROUGH */
2298 	default:
2299 		ira->ira_flags |= IRAF_ICMP_ERROR;
2300 		ip_fanout_proto_v4(mp, &ripha, ira);
2301 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2302 		return;
2303 	}
2304 	/* NOTREACHED */
2305 discard_pkt:
2306 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2307 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2308 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2309 	freemsg(mp);
2310 	return;
2311 
2312 truncated:
2313 	/* We pulled up everthing already. Must be truncated */
2314 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2315 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2316 	freemsg(mp);
2317 }
2318 
2319 /*
2320  * Common IP options parser.
2321  *
2322  * Setup routine: fill in *optp with options-parsing state, then
2323  * tail-call ipoptp_next to return the first option.
2324  */
2325 uint8_t
2326 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2327 {
2328 	uint32_t totallen; /* total length of all options */
2329 
2330 	totallen = ipha->ipha_version_and_hdr_length -
2331 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2332 	totallen <<= 2;
2333 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2334 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2335 	optp->ipoptp_flags = 0;
2336 	return (ipoptp_next(optp));
2337 }
2338 
2339 /* Like above but without an ipha_t */
2340 uint8_t
2341 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2342 {
2343 	optp->ipoptp_next = opt;
2344 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2345 	optp->ipoptp_flags = 0;
2346 	return (ipoptp_next(optp));
2347 }
2348 
2349 /*
2350  * Common IP options parser: extract next option.
2351  */
2352 uint8_t
2353 ipoptp_next(ipoptp_t *optp)
2354 {
2355 	uint8_t *end = optp->ipoptp_end;
2356 	uint8_t *cur = optp->ipoptp_next;
2357 	uint8_t opt, len, pointer;
2358 
2359 	/*
2360 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2361 	 * has been corrupted.
2362 	 */
2363 	ASSERT(cur <= end);
2364 
2365 	if (cur == end)
2366 		return (IPOPT_EOL);
2367 
2368 	opt = cur[IPOPT_OPTVAL];
2369 
2370 	/*
2371 	 * Skip any NOP options.
2372 	 */
2373 	while (opt == IPOPT_NOP) {
2374 		cur++;
2375 		if (cur == end)
2376 			return (IPOPT_EOL);
2377 		opt = cur[IPOPT_OPTVAL];
2378 	}
2379 
2380 	if (opt == IPOPT_EOL)
2381 		return (IPOPT_EOL);
2382 
2383 	/*
2384 	 * Option requiring a length.
2385 	 */
2386 	if ((cur + 1) >= end) {
2387 		optp->ipoptp_flags |= IPOPTP_ERROR;
2388 		return (IPOPT_EOL);
2389 	}
2390 	len = cur[IPOPT_OLEN];
2391 	if (len < 2) {
2392 		optp->ipoptp_flags |= IPOPTP_ERROR;
2393 		return (IPOPT_EOL);
2394 	}
2395 	optp->ipoptp_cur = cur;
2396 	optp->ipoptp_len = len;
2397 	optp->ipoptp_next = cur + len;
2398 	if (cur + len > end) {
2399 		optp->ipoptp_flags |= IPOPTP_ERROR;
2400 		return (IPOPT_EOL);
2401 	}
2402 
2403 	/*
2404 	 * For the options which require a pointer field, make sure
2405 	 * its there, and make sure it points to either something
2406 	 * inside this option, or the end of the option.
2407 	 */
2408 	pointer = IPOPT_EOL;
2409 	switch (opt) {
2410 	case IPOPT_RR:
2411 	case IPOPT_TS:
2412 	case IPOPT_LSRR:
2413 	case IPOPT_SSRR:
2414 		if (len <= IPOPT_OFFSET) {
2415 			optp->ipoptp_flags |= IPOPTP_ERROR;
2416 			return (opt);
2417 		}
2418 		pointer = cur[IPOPT_OFFSET];
2419 		if (pointer - 1 > len) {
2420 			optp->ipoptp_flags |= IPOPTP_ERROR;
2421 			return (opt);
2422 		}
2423 		break;
2424 	}
2425 
2426 	/*
2427 	 * Sanity check the pointer field based on the type of the
2428 	 * option.
2429 	 */
2430 	switch (opt) {
2431 	case IPOPT_RR:
2432 	case IPOPT_SSRR:
2433 	case IPOPT_LSRR:
2434 		if (pointer < IPOPT_MINOFF_SR)
2435 			optp->ipoptp_flags |= IPOPTP_ERROR;
2436 		break;
2437 	case IPOPT_TS:
2438 		if (pointer < IPOPT_MINOFF_IT)
2439 			optp->ipoptp_flags |= IPOPTP_ERROR;
2440 		/*
2441 		 * Note that the Internet Timestamp option also
2442 		 * contains two four bit fields (the Overflow field,
2443 		 * and the Flag field), which follow the pointer
2444 		 * field.  We don't need to check that these fields
2445 		 * fall within the length of the option because this
2446 		 * was implicitely done above.  We've checked that the
2447 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2448 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2449 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2450 		 */
2451 		ASSERT(len > IPOPT_POS_OV_FLG);
2452 		break;
2453 	}
2454 
2455 	return (opt);
2456 }
2457 
2458 /*
2459  * Use the outgoing IP header to create an IP_OPTIONS option the way
2460  * it was passed down from the application.
2461  *
2462  * This is compatible with BSD in that it returns
2463  * the reverse source route with the final destination
2464  * as the last entry. The first 4 bytes of the option
2465  * will contain the final destination.
2466  */
2467 int
2468 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2469 {
2470 	ipoptp_t	opts;
2471 	uchar_t		*opt;
2472 	uint8_t		optval;
2473 	uint8_t		optlen;
2474 	uint32_t	len = 0;
2475 	uchar_t		*buf1 = buf;
2476 	uint32_t	totallen;
2477 	ipaddr_t	dst;
2478 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2479 
2480 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2481 		return (0);
2482 
2483 	totallen = ipp->ipp_ipv4_options_len;
2484 	if (totallen & 0x3)
2485 		return (0);
2486 
2487 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2488 	len += IP_ADDR_LEN;
2489 	bzero(buf1, IP_ADDR_LEN);
2490 
2491 	dst = connp->conn_faddr_v4;
2492 
2493 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2494 	    optval != IPOPT_EOL;
2495 	    optval = ipoptp_next(&opts)) {
2496 		int	off;
2497 
2498 		opt = opts.ipoptp_cur;
2499 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2500 			break;
2501 		}
2502 		optlen = opts.ipoptp_len;
2503 
2504 		switch (optval) {
2505 		case IPOPT_SSRR:
2506 		case IPOPT_LSRR:
2507 
2508 			/*
2509 			 * Insert destination as the first entry in the source
2510 			 * route and move down the entries on step.
2511 			 * The last entry gets placed at buf1.
2512 			 */
2513 			buf[IPOPT_OPTVAL] = optval;
2514 			buf[IPOPT_OLEN] = optlen;
2515 			buf[IPOPT_OFFSET] = optlen;
2516 
2517 			off = optlen - IP_ADDR_LEN;
2518 			if (off < 0) {
2519 				/* No entries in source route */
2520 				break;
2521 			}
2522 			/* Last entry in source route if not already set */
2523 			if (dst == INADDR_ANY)
2524 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2525 			off -= IP_ADDR_LEN;
2526 
2527 			while (off > 0) {
2528 				bcopy(opt + off,
2529 				    buf + off + IP_ADDR_LEN,
2530 				    IP_ADDR_LEN);
2531 				off -= IP_ADDR_LEN;
2532 			}
2533 			/* ipha_dst into first slot */
2534 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2535 			    IP_ADDR_LEN);
2536 			buf += optlen;
2537 			len += optlen;
2538 			break;
2539 
2540 		default:
2541 			bcopy(opt, buf, optlen);
2542 			buf += optlen;
2543 			len += optlen;
2544 			break;
2545 		}
2546 	}
2547 done:
2548 	/* Pad the resulting options */
2549 	while (len & 0x3) {
2550 		*buf++ = IPOPT_EOL;
2551 		len++;
2552 	}
2553 	return (len);
2554 }
2555 
2556 /*
2557  * Update any record route or timestamp options to include this host.
2558  * Reverse any source route option.
2559  * This routine assumes that the options are well formed i.e. that they
2560  * have already been checked.
2561  */
2562 static void
2563 icmp_options_update(ipha_t *ipha)
2564 {
2565 	ipoptp_t	opts;
2566 	uchar_t		*opt;
2567 	uint8_t		optval;
2568 	ipaddr_t	src;		/* Our local address */
2569 	ipaddr_t	dst;
2570 
2571 	ip2dbg(("icmp_options_update\n"));
2572 	src = ipha->ipha_src;
2573 	dst = ipha->ipha_dst;
2574 
2575 	for (optval = ipoptp_first(&opts, ipha);
2576 	    optval != IPOPT_EOL;
2577 	    optval = ipoptp_next(&opts)) {
2578 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2579 		opt = opts.ipoptp_cur;
2580 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2581 		    optval, opts.ipoptp_len));
2582 		switch (optval) {
2583 			int off1, off2;
2584 		case IPOPT_SSRR:
2585 		case IPOPT_LSRR:
2586 			/*
2587 			 * Reverse the source route.  The first entry
2588 			 * should be the next to last one in the current
2589 			 * source route (the last entry is our address).
2590 			 * The last entry should be the final destination.
2591 			 */
2592 			off1 = IPOPT_MINOFF_SR - 1;
2593 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2594 			if (off2 < 0) {
2595 				/* No entries in source route */
2596 				ip1dbg((
2597 				    "icmp_options_update: bad src route\n"));
2598 				break;
2599 			}
2600 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2601 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2602 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2603 			off2 -= IP_ADDR_LEN;
2604 
2605 			while (off1 < off2) {
2606 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2607 				bcopy((char *)opt + off2, (char *)opt + off1,
2608 				    IP_ADDR_LEN);
2609 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2610 				off1 += IP_ADDR_LEN;
2611 				off2 -= IP_ADDR_LEN;
2612 			}
2613 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2614 			break;
2615 		}
2616 	}
2617 }
2618 
2619 /*
2620  * Process received ICMP Redirect messages.
2621  * Assumes the caller has verified that the headers are in the pulled up mblk.
2622  * Consumes mp.
2623  */
2624 static void
2625 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2626 {
2627 	ire_t		*ire, *nire;
2628 	ire_t		*prev_ire;
2629 	ipaddr_t	src, dst, gateway;
2630 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2631 	ipha_t		*inner_ipha;	/* Inner IP header */
2632 
2633 	/* Caller already pulled up everything. */
2634 	inner_ipha = (ipha_t *)&icmph[1];
2635 	src = ipha->ipha_src;
2636 	dst = inner_ipha->ipha_dst;
2637 	gateway = icmph->icmph_rd_gateway;
2638 	/* Make sure the new gateway is reachable somehow. */
2639 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2640 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2641 	/*
2642 	 * Make sure we had a route for the dest in question and that
2643 	 * that route was pointing to the old gateway (the source of the
2644 	 * redirect packet.)
2645 	 * We do longest match and then compare ire_gateway_addr below.
2646 	 */
2647 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2648 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2649 	/*
2650 	 * Check that
2651 	 *	the redirect was not from ourselves
2652 	 *	the new gateway and the old gateway are directly reachable
2653 	 */
2654 	if (prev_ire == NULL || ire == NULL ||
2655 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2656 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2657 	    !(ire->ire_type & IRE_IF_ALL) ||
2658 	    prev_ire->ire_gateway_addr != src) {
2659 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2660 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2661 		freemsg(mp);
2662 		if (ire != NULL)
2663 			ire_refrele(ire);
2664 		if (prev_ire != NULL)
2665 			ire_refrele(prev_ire);
2666 		return;
2667 	}
2668 
2669 	ire_refrele(prev_ire);
2670 	ire_refrele(ire);
2671 
2672 	/*
2673 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2674 	 * require TOS routing
2675 	 */
2676 	switch (icmph->icmph_code) {
2677 	case 0:
2678 	case 1:
2679 		/* TODO: TOS specificity for cases 2 and 3 */
2680 	case 2:
2681 	case 3:
2682 		break;
2683 	default:
2684 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2685 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2686 		freemsg(mp);
2687 		return;
2688 	}
2689 	/*
2690 	 * Create a Route Association.  This will allow us to remember that
2691 	 * someone we believe told us to use the particular gateway.
2692 	 */
2693 	ire = ire_create(
2694 	    (uchar_t *)&dst,			/* dest addr */
2695 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2696 	    (uchar_t *)&gateway,		/* gateway addr */
2697 	    IRE_HOST,
2698 	    NULL,				/* ill */
2699 	    ALL_ZONES,
2700 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2701 	    NULL,				/* tsol_gc_t */
2702 	    ipst);
2703 
2704 	if (ire == NULL) {
2705 		freemsg(mp);
2706 		return;
2707 	}
2708 	nire = ire_add(ire);
2709 	/* Check if it was a duplicate entry */
2710 	if (nire != NULL && nire != ire) {
2711 		ASSERT(nire->ire_identical_ref > 1);
2712 		ire_delete(nire);
2713 		ire_refrele(nire);
2714 		nire = NULL;
2715 	}
2716 	ire = nire;
2717 	if (ire != NULL) {
2718 		ire_refrele(ire);		/* Held in ire_add */
2719 
2720 		/* tell routing sockets that we received a redirect */
2721 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2722 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2723 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2724 	}
2725 
2726 	/*
2727 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2728 	 * This together with the added IRE has the effect of
2729 	 * modifying an existing redirect.
2730 	 */
2731 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2732 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2733 	if (prev_ire != NULL) {
2734 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2735 			ire_delete(prev_ire);
2736 		ire_refrele(prev_ire);
2737 	}
2738 
2739 	freemsg(mp);
2740 }
2741 
2742 /*
2743  * Generate an ICMP parameter problem message.
2744  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2745  * constructed by the caller.
2746  */
2747 static void
2748 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2749 {
2750 	icmph_t	icmph;
2751 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2752 
2753 	mp = icmp_pkt_err_ok(mp, ira);
2754 	if (mp == NULL)
2755 		return;
2756 
2757 	bzero(&icmph, sizeof (icmph_t));
2758 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2759 	icmph.icmph_pp_ptr = ptr;
2760 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2761 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2762 }
2763 
2764 /*
2765  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2766  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2767  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2768  * an icmp error packet can be sent.
2769  * Assigns an appropriate source address to the packet. If ipha_dst is
2770  * one of our addresses use it for source. Otherwise let ip_output_simple
2771  * pick the source address.
2772  */
2773 static void
2774 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2775 {
2776 	ipaddr_t dst;
2777 	icmph_t	*icmph;
2778 	ipha_t	*ipha;
2779 	uint_t	len_needed;
2780 	size_t	msg_len;
2781 	mblk_t	*mp1;
2782 	ipaddr_t src;
2783 	ire_t	*ire;
2784 	ip_xmit_attr_t ixas;
2785 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2786 
2787 	ipha = (ipha_t *)mp->b_rptr;
2788 
2789 	bzero(&ixas, sizeof (ixas));
2790 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2791 	ixas.ixa_zoneid = ira->ira_zoneid;
2792 	ixas.ixa_ifindex = 0;
2793 	ixas.ixa_ipst = ipst;
2794 	ixas.ixa_cred = kcred;
2795 	ixas.ixa_cpid = NOPID;
2796 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2797 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2798 
2799 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2800 		/*
2801 		 * Apply IPsec based on how IPsec was applied to
2802 		 * the packet that had the error.
2803 		 *
2804 		 * If it was an outbound packet that caused the ICMP
2805 		 * error, then the caller will have setup the IRA
2806 		 * appropriately.
2807 		 */
2808 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2809 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2810 			/* Note: mp already consumed and ip_drop_packet done */
2811 			return;
2812 		}
2813 	} else {
2814 		/*
2815 		 * This is in clear. The icmp message we are building
2816 		 * here should go out in clear, independent of our policy.
2817 		 */
2818 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2819 	}
2820 
2821 	/* Remember our eventual destination */
2822 	dst = ipha->ipha_src;
2823 
2824 	/*
2825 	 * If the packet was for one of our unicast addresses, make
2826 	 * sure we respond with that as the source. Otherwise
2827 	 * have ip_output_simple pick the source address.
2828 	 */
2829 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2830 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2831 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2832 	if (ire != NULL) {
2833 		ire_refrele(ire);
2834 		src = ipha->ipha_dst;
2835 	} else {
2836 		src = INADDR_ANY;
2837 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2838 	}
2839 
2840 	/*
2841 	 * Check if we can send back more then 8 bytes in addition to
2842 	 * the IP header.  We try to send 64 bytes of data and the internal
2843 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2844 	 */
2845 	len_needed = IPH_HDR_LENGTH(ipha);
2846 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2847 	    ipha->ipha_protocol == IPPROTO_IPV6) {
2848 		/*
2849 		 * NOTE: It is posssible that the inner packet is poorly
2850 		 * formed (e.g. IP version is corrupt, or v6 extension headers
2851 		 * got cut off).  The receiver of the ICMP message should see
2852 		 * what we saw.  In the absence of a sane inner-packet (which
2853 		 * protocol types IPPPROTO_ENCAP and IPPROTO_IPV6 indicate
2854 		 * would be an IP header), we should send the size of what is
2855 		 * normally expected to be there (either sizeof (ipha_t) or
2856 		 * sizeof (ip6_t).  It may be useful for diagnostic purposes.
2857 		 *
2858 		 * ALSO NOTE: "inner_ip6h" is the inner packet header, v4 or v6.
2859 		 */
2860 		ip6_t *inner_ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2861 
2862 		if (!pullupmsg(mp, -1)) {
2863 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2864 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2865 			freemsg(mp);
2866 			return;
2867 		}
2868 		ipha = (ipha_t *)mp->b_rptr;
2869 
2870 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2871 			/*
2872 			 * Check the inner IP version here to guard against
2873 			 * bogons.
2874 			 */
2875 			if (IPH_HDR_VERSION(inner_ip6h) == IPV4_VERSION) {
2876 				len_needed +=
2877 				    IPH_HDR_LENGTH(((uchar_t *)inner_ip6h));
2878 			} else {
2879 				len_needed = sizeof (ipha_t);
2880 			}
2881 		} else {
2882 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2883 			/* function called next-line checks inner IP version */
2884 			len_needed += ip_hdr_length_v6(mp, inner_ip6h);
2885 		}
2886 	}
2887 	len_needed += ipst->ips_ip_icmp_return;
2888 	msg_len = msgdsize(mp);
2889 	if (msg_len > len_needed) {
2890 		(void) adjmsg(mp, len_needed - msg_len);
2891 		msg_len = len_needed;
2892 	}
2893 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2894 	if (mp1 == NULL) {
2895 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2896 		freemsg(mp);
2897 		return;
2898 	}
2899 	mp1->b_cont = mp;
2900 	mp = mp1;
2901 
2902 	/*
2903 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2904 	 * node generates be accepted in peace by all on-host destinations.
2905 	 * If we do NOT assume that all on-host destinations trust
2906 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2907 	 * (Look for IXAF_TRUSTED_ICMP).
2908 	 */
2909 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2910 
2911 	ipha = (ipha_t *)mp->b_rptr;
2912 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2913 	*ipha = icmp_ipha;
2914 	ipha->ipha_src = src;
2915 	ipha->ipha_dst = dst;
2916 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2917 	msg_len += sizeof (icmp_ipha) + len;
2918 	if (msg_len > IP_MAXPACKET) {
2919 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
2920 		msg_len = IP_MAXPACKET;
2921 	}
2922 	ipha->ipha_length = htons((uint16_t)msg_len);
2923 	icmph = (icmph_t *)&ipha[1];
2924 	bcopy(stuff, icmph, len);
2925 	icmph->icmph_checksum = 0;
2926 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2927 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2928 
2929 	(void) ip_output_simple(mp, &ixas);
2930 	ixa_cleanup(&ixas);
2931 }
2932 
2933 /*
2934  * Determine if an ICMP error packet can be sent given the rate limit.
2935  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2936  * in milliseconds) and a burst size. Burst size number of packets can
2937  * be sent arbitrarely closely spaced.
2938  * The state is tracked using two variables to implement an approximate
2939  * token bucket filter:
2940  *	icmp_pkt_err_last - lbolt value when the last burst started
2941  *	icmp_pkt_err_sent - number of packets sent in current burst
2942  */
2943 boolean_t
2944 icmp_err_rate_limit(ip_stack_t *ipst)
2945 {
2946 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2947 	uint_t refilled; /* Number of packets refilled in tbf since last */
2948 	/* Guard against changes by loading into local variable */
2949 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2950 
2951 	if (err_interval == 0)
2952 		return (B_FALSE);
2953 
2954 	if (ipst->ips_icmp_pkt_err_last > now) {
2955 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2956 		ipst->ips_icmp_pkt_err_last = 0;
2957 		ipst->ips_icmp_pkt_err_sent = 0;
2958 	}
2959 	/*
2960 	 * If we are in a burst update the token bucket filter.
2961 	 * Update the "last" time to be close to "now" but make sure
2962 	 * we don't loose precision.
2963 	 */
2964 	if (ipst->ips_icmp_pkt_err_sent != 0) {
2965 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2966 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
2967 			ipst->ips_icmp_pkt_err_sent = 0;
2968 		} else {
2969 			ipst->ips_icmp_pkt_err_sent -= refilled;
2970 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2971 		}
2972 	}
2973 	if (ipst->ips_icmp_pkt_err_sent == 0) {
2974 		/* Start of new burst */
2975 		ipst->ips_icmp_pkt_err_last = now;
2976 	}
2977 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2978 		ipst->ips_icmp_pkt_err_sent++;
2979 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2980 		    ipst->ips_icmp_pkt_err_sent));
2981 		return (B_FALSE);
2982 	}
2983 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
2984 	return (B_TRUE);
2985 }
2986 
2987 /*
2988  * Check if it is ok to send an IPv4 ICMP error packet in
2989  * response to the IPv4 packet in mp.
2990  * Free the message and return null if no
2991  * ICMP error packet should be sent.
2992  */
2993 static mblk_t *
2994 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2995 {
2996 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2997 	icmph_t	*icmph;
2998 	ipha_t	*ipha;
2999 	uint_t	len_needed;
3000 
3001 	if (!mp)
3002 		return (NULL);
3003 	ipha = (ipha_t *)mp->b_rptr;
3004 	if (ip_csum_hdr(ipha)) {
3005 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3006 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
3007 		freemsg(mp);
3008 		return (NULL);
3009 	}
3010 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
3011 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
3012 	    CLASSD(ipha->ipha_dst) ||
3013 	    CLASSD(ipha->ipha_src) ||
3014 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3015 		/* Note: only errors to the fragment with offset 0 */
3016 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3017 		freemsg(mp);
3018 		return (NULL);
3019 	}
3020 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3021 		/*
3022 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3023 		 * errors in response to any ICMP errors.
3024 		 */
3025 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3026 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3027 			if (!pullupmsg(mp, len_needed)) {
3028 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3029 				freemsg(mp);
3030 				return (NULL);
3031 			}
3032 			ipha = (ipha_t *)mp->b_rptr;
3033 		}
3034 		icmph = (icmph_t *)
3035 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3036 		switch (icmph->icmph_type) {
3037 		case ICMP_DEST_UNREACHABLE:
3038 		case ICMP_SOURCE_QUENCH:
3039 		case ICMP_TIME_EXCEEDED:
3040 		case ICMP_PARAM_PROBLEM:
3041 		case ICMP_REDIRECT:
3042 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3043 			freemsg(mp);
3044 			return (NULL);
3045 		default:
3046 			break;
3047 		}
3048 	}
3049 	/*
3050 	 * If this is a labeled system, then check to see if we're allowed to
3051 	 * send a response to this particular sender.  If not, then just drop.
3052 	 */
3053 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3054 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3055 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3056 		freemsg(mp);
3057 		return (NULL);
3058 	}
3059 	if (icmp_err_rate_limit(ipst)) {
3060 		/*
3061 		 * Only send ICMP error packets every so often.
3062 		 * This should be done on a per port/source basis,
3063 		 * but for now this will suffice.
3064 		 */
3065 		freemsg(mp);
3066 		return (NULL);
3067 	}
3068 	return (mp);
3069 }
3070 
3071 /*
3072  * Called when a packet was sent out the same link that it arrived on.
3073  * Check if it is ok to send a redirect and then send it.
3074  */
3075 void
3076 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3077     ip_recv_attr_t *ira)
3078 {
3079 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3080 	ipaddr_t	src, nhop;
3081 	mblk_t		*mp1;
3082 	ire_t		*nhop_ire;
3083 
3084 	/*
3085 	 * Check the source address to see if it originated
3086 	 * on the same logical subnet it is going back out on.
3087 	 * If so, we should be able to send it a redirect.
3088 	 * Avoid sending a redirect if the destination
3089 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3090 	 * or if the packet was source routed out this interface.
3091 	 *
3092 	 * We avoid sending a redirect if the
3093 	 * destination is directly connected
3094 	 * because it is possible that multiple
3095 	 * IP subnets may have been configured on
3096 	 * the link, and the source may not
3097 	 * be on the same subnet as ip destination,
3098 	 * even though they are on the same
3099 	 * physical link.
3100 	 */
3101 	if ((ire->ire_type & IRE_ONLINK) ||
3102 	    ip_source_routed(ipha, ipst))
3103 		return;
3104 
3105 	nhop_ire = ire_nexthop(ire);
3106 	if (nhop_ire == NULL)
3107 		return;
3108 
3109 	nhop = nhop_ire->ire_addr;
3110 
3111 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3112 		ire_t	*ire2;
3113 
3114 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3115 		mutex_enter(&nhop_ire->ire_lock);
3116 		ire2 = nhop_ire->ire_dep_parent;
3117 		if (ire2 != NULL)
3118 			ire_refhold(ire2);
3119 		mutex_exit(&nhop_ire->ire_lock);
3120 		ire_refrele(nhop_ire);
3121 		nhop_ire = ire2;
3122 	}
3123 	if (nhop_ire == NULL)
3124 		return;
3125 
3126 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3127 
3128 	src = ipha->ipha_src;
3129 
3130 	/*
3131 	 * We look at the interface ire for the nexthop,
3132 	 * to see if ipha_src is in the same subnet
3133 	 * as the nexthop.
3134 	 */
3135 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3136 		/*
3137 		 * The source is directly connected.
3138 		 */
3139 		mp1 = copymsg(mp);
3140 		if (mp1 != NULL) {
3141 			icmp_send_redirect(mp1, nhop, ira);
3142 		}
3143 	}
3144 	ire_refrele(nhop_ire);
3145 }
3146 
3147 /*
3148  * Generate an ICMP redirect message.
3149  */
3150 static void
3151 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3152 {
3153 	icmph_t	icmph;
3154 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3155 
3156 	mp = icmp_pkt_err_ok(mp, ira);
3157 	if (mp == NULL)
3158 		return;
3159 
3160 	bzero(&icmph, sizeof (icmph_t));
3161 	icmph.icmph_type = ICMP_REDIRECT;
3162 	icmph.icmph_code = 1;
3163 	icmph.icmph_rd_gateway = gateway;
3164 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3165 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3166 }
3167 
3168 /*
3169  * Generate an ICMP time exceeded message.
3170  */
3171 void
3172 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3173 {
3174 	icmph_t	icmph;
3175 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3176 
3177 	mp = icmp_pkt_err_ok(mp, ira);
3178 	if (mp == NULL)
3179 		return;
3180 
3181 	bzero(&icmph, sizeof (icmph_t));
3182 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3183 	icmph.icmph_code = code;
3184 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3185 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3186 }
3187 
3188 /*
3189  * Generate an ICMP unreachable message.
3190  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3191  * constructed by the caller.
3192  */
3193 void
3194 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3195 {
3196 	icmph_t	icmph;
3197 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3198 
3199 	mp = icmp_pkt_err_ok(mp, ira);
3200 	if (mp == NULL)
3201 		return;
3202 
3203 	bzero(&icmph, sizeof (icmph_t));
3204 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3205 	icmph.icmph_code = code;
3206 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3207 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3208 }
3209 
3210 /*
3211  * Latch in the IPsec state for a stream based the policy in the listener
3212  * and the actions in the ip_recv_attr_t.
3213  * Called directly from TCP and SCTP.
3214  */
3215 boolean_t
3216 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3217 {
3218 	ASSERT(lconnp->conn_policy != NULL);
3219 	ASSERT(connp->conn_policy == NULL);
3220 
3221 	IPPH_REFHOLD(lconnp->conn_policy);
3222 	connp->conn_policy = lconnp->conn_policy;
3223 
3224 	if (ira->ira_ipsec_action != NULL) {
3225 		if (connp->conn_latch == NULL) {
3226 			connp->conn_latch = iplatch_create();
3227 			if (connp->conn_latch == NULL)
3228 				return (B_FALSE);
3229 		}
3230 		ipsec_latch_inbound(connp, ira);
3231 	}
3232 	return (B_TRUE);
3233 }
3234 
3235 /*
3236  * Verify whether or not the IP address is a valid local address.
3237  * Could be a unicast, including one for a down interface.
3238  * If allow_mcbc then a multicast or broadcast address is also
3239  * acceptable.
3240  *
3241  * In the case of a broadcast/multicast address, however, the
3242  * upper protocol is expected to reset the src address
3243  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3244  * no packets are emitted with broadcast/multicast address as
3245  * source address (that violates hosts requirements RFC 1122)
3246  * The addresses valid for bind are:
3247  *	(1) - INADDR_ANY (0)
3248  *	(2) - IP address of an UP interface
3249  *	(3) - IP address of a DOWN interface
3250  *	(4) - valid local IP broadcast addresses. In this case
3251  *	the conn will only receive packets destined to
3252  *	the specified broadcast address.
3253  *	(5) - a multicast address. In this case
3254  *	the conn will only receive packets destined to
3255  *	the specified multicast address. Note: the
3256  *	application still has to issue an
3257  *	IP_ADD_MEMBERSHIP socket option.
3258  *
3259  * In all the above cases, the bound address must be valid in the current zone.
3260  * When the address is loopback, multicast or broadcast, there might be many
3261  * matching IREs so bind has to look up based on the zone.
3262  */
3263 ip_laddr_t
3264 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3265     ip_stack_t *ipst, boolean_t allow_mcbc)
3266 {
3267 	ire_t *src_ire;
3268 
3269 	ASSERT(src_addr != INADDR_ANY);
3270 
3271 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3272 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3273 
3274 	/*
3275 	 * If an address other than in6addr_any is requested,
3276 	 * we verify that it is a valid address for bind
3277 	 * Note: Following code is in if-else-if form for
3278 	 * readability compared to a condition check.
3279 	 */
3280 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3281 		/*
3282 		 * (2) Bind to address of local UP interface
3283 		 */
3284 		ire_refrele(src_ire);
3285 		return (IPVL_UNICAST_UP);
3286 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3287 		/*
3288 		 * (4) Bind to broadcast address
3289 		 */
3290 		ire_refrele(src_ire);
3291 		if (allow_mcbc)
3292 			return (IPVL_BCAST);
3293 		else
3294 			return (IPVL_BAD);
3295 	} else if (CLASSD(src_addr)) {
3296 		/* (5) bind to multicast address. */
3297 		if (src_ire != NULL)
3298 			ire_refrele(src_ire);
3299 
3300 		if (allow_mcbc)
3301 			return (IPVL_MCAST);
3302 		else
3303 			return (IPVL_BAD);
3304 	} else {
3305 		ipif_t *ipif;
3306 
3307 		/*
3308 		 * (3) Bind to address of local DOWN interface?
3309 		 * (ipif_lookup_addr() looks up all interfaces
3310 		 * but we do not get here for UP interfaces
3311 		 * - case (2) above)
3312 		 */
3313 		if (src_ire != NULL)
3314 			ire_refrele(src_ire);
3315 
3316 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3317 		if (ipif == NULL)
3318 			return (IPVL_BAD);
3319 
3320 		/* Not a useful source? */
3321 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3322 			ipif_refrele(ipif);
3323 			return (IPVL_BAD);
3324 		}
3325 		ipif_refrele(ipif);
3326 		return (IPVL_UNICAST_DOWN);
3327 	}
3328 }
3329 
3330 /*
3331  * Insert in the bind fanout for IPv4 and IPv6.
3332  * The caller should already have used ip_laddr_verify_v*() before calling
3333  * this.
3334  */
3335 int
3336 ip_laddr_fanout_insert(conn_t *connp)
3337 {
3338 	int		error;
3339 
3340 	/*
3341 	 * Allow setting new policies. For example, disconnects result
3342 	 * in us being called. As we would have set conn_policy_cached
3343 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3344 	 * can change after the disconnect.
3345 	 */
3346 	connp->conn_policy_cached = B_FALSE;
3347 
3348 	error = ipcl_bind_insert(connp);
3349 	if (error != 0) {
3350 		if (connp->conn_anon_port) {
3351 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3352 			    connp->conn_mlp_type, connp->conn_proto,
3353 			    ntohs(connp->conn_lport), B_FALSE);
3354 		}
3355 		connp->conn_mlp_type = mlptSingle;
3356 	}
3357 	return (error);
3358 }
3359 
3360 /*
3361  * Verify that both the source and destination addresses are valid. If
3362  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3363  * i.e. have no route to it.  Protocols like TCP want to verify destination
3364  * reachability, while tunnels do not.
3365  *
3366  * Determine the route, the interface, and (optionally) the source address
3367  * to use to reach a given destination.
3368  * Note that we allow connect to broadcast and multicast addresses when
3369  * IPDF_ALLOW_MCBC is set.
3370  * first_hop and dst_addr are normally the same, but if source routing
3371  * they will differ; in that case the first_hop is what we'll use for the
3372  * routing lookup but the dce and label checks will be done on dst_addr,
3373  *
3374  * If uinfo is set, then we fill in the best available information
3375  * we have for the destination. This is based on (in priority order) any
3376  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3377  * ill_mtu/ill_mc_mtu.
3378  *
3379  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3380  * always do the label check on dst_addr.
3381  */
3382 int
3383 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3384     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3385 {
3386 	ire_t		*ire = NULL;
3387 	int		error = 0;
3388 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3389 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3390 	ip_stack_t	*ipst = ixa->ixa_ipst;
3391 	dce_t		*dce;
3392 	uint_t		pmtu;
3393 	uint_t		generation;
3394 	nce_t		*nce;
3395 	ill_t		*ill = NULL;
3396 	boolean_t	multirt = B_FALSE;
3397 
3398 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3399 
3400 	/*
3401 	 * We never send to zero; the ULPs map it to the loopback address.
3402 	 * We can't allow it since we use zero to mean unitialized in some
3403 	 * places.
3404 	 */
3405 	ASSERT(dst_addr != INADDR_ANY);
3406 
3407 	if (is_system_labeled()) {
3408 		ts_label_t *tsl = NULL;
3409 
3410 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3411 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3412 		if (error != 0)
3413 			return (error);
3414 		if (tsl != NULL) {
3415 			/* Update the label */
3416 			ip_xmit_attr_replace_tsl(ixa, tsl);
3417 		}
3418 	}
3419 
3420 	setsrc = INADDR_ANY;
3421 	/*
3422 	 * Select a route; For IPMP interfaces, we would only select
3423 	 * a "hidden" route (i.e., going through a specific under_ill)
3424 	 * if ixa_ifindex has been specified.
3425 	 */
3426 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3427 	    &generation, &setsrc, &error, &multirt);
3428 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3429 	if (error != 0)
3430 		goto bad_addr;
3431 
3432 	/*
3433 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3434 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3435 	 * Otherwise the destination needn't be reachable.
3436 	 *
3437 	 * If we match on a reject or black hole, then we've got a
3438 	 * local failure.  May as well fail out the connect() attempt,
3439 	 * since it's never going to succeed.
3440 	 */
3441 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3442 		/*
3443 		 * If we're verifying destination reachability, we always want
3444 		 * to complain here.
3445 		 *
3446 		 * If we're not verifying destination reachability but the
3447 		 * destination has a route, we still want to fail on the
3448 		 * temporary address and broadcast address tests.
3449 		 *
3450 		 * In both cases do we let the code continue so some reasonable
3451 		 * information is returned to the caller. That enables the
3452 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3453 		 * use the generation mismatch path to check for the unreachable
3454 		 * case thereby avoiding any specific check in the main path.
3455 		 */
3456 		ASSERT(generation == IRE_GENERATION_VERIFY);
3457 		if (flags & IPDF_VERIFY_DST) {
3458 			/*
3459 			 * Set errno but continue to set up ixa_ire to be
3460 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3461 			 * That allows callers to use ip_output to get an
3462 			 * ICMP error back.
3463 			 */
3464 			if (!(ire->ire_type & IRE_HOST))
3465 				error = ENETUNREACH;
3466 			else
3467 				error = EHOSTUNREACH;
3468 		}
3469 	}
3470 
3471 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3472 	    !(flags & IPDF_ALLOW_MCBC)) {
3473 		ire_refrele(ire);
3474 		ire = ire_reject(ipst, B_FALSE);
3475 		generation = IRE_GENERATION_VERIFY;
3476 		error = ENETUNREACH;
3477 	}
3478 
3479 	/* Cache things */
3480 	if (ixa->ixa_ire != NULL)
3481 		ire_refrele_notr(ixa->ixa_ire);
3482 #ifdef DEBUG
3483 	ire_refhold_notr(ire);
3484 	ire_refrele(ire);
3485 #endif
3486 	ixa->ixa_ire = ire;
3487 	ixa->ixa_ire_generation = generation;
3488 
3489 	/*
3490 	 * Ensure that ixa_dce is always set any time that ixa_ire is set,
3491 	 * since some callers will send a packet to conn_ip_output() even if
3492 	 * there's an error.
3493 	 */
3494 	if (flags & IPDF_UNIQUE_DCE) {
3495 		/* Fallback to the default dce if allocation fails */
3496 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3497 		if (dce != NULL)
3498 			generation = dce->dce_generation;
3499 		else
3500 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3501 	} else {
3502 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3503 	}
3504 	ASSERT(dce != NULL);
3505 	if (ixa->ixa_dce != NULL)
3506 		dce_refrele_notr(ixa->ixa_dce);
3507 #ifdef DEBUG
3508 	dce_refhold_notr(dce);
3509 	dce_refrele(dce);
3510 #endif
3511 	ixa->ixa_dce = dce;
3512 	ixa->ixa_dce_generation = generation;
3513 
3514 	/*
3515 	 * For multicast with multirt we have a flag passed back from
3516 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3517 	 * possible multicast address.
3518 	 * We also need a flag for multicast since we can't check
3519 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3520 	 */
3521 	if (multirt) {
3522 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3523 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3524 	} else {
3525 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3526 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3527 	}
3528 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3529 		/* Get an nce to cache. */
3530 		nce = ire_to_nce(ire, firsthop, NULL);
3531 		if (nce == NULL) {
3532 			/* Allocation failure? */
3533 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3534 		} else {
3535 			if (ixa->ixa_nce != NULL)
3536 				nce_refrele(ixa->ixa_nce);
3537 			ixa->ixa_nce = nce;
3538 		}
3539 	}
3540 
3541 	/*
3542 	 * If the source address is a loopback address, the
3543 	 * destination had best be local or multicast.
3544 	 * If we are sending to an IRE_LOCAL using a loopback source then
3545 	 * it had better be the same zoneid.
3546 	 */
3547 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3548 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3549 			ire = NULL;	/* Stored in ixa_ire */
3550 			error = EADDRNOTAVAIL;
3551 			goto bad_addr;
3552 		}
3553 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3554 			ire = NULL;	/* Stored in ixa_ire */
3555 			error = EADDRNOTAVAIL;
3556 			goto bad_addr;
3557 		}
3558 	}
3559 	if (ire->ire_type & IRE_BROADCAST) {
3560 		/*
3561 		 * If the ULP didn't have a specified source, then we
3562 		 * make sure we reselect the source when sending
3563 		 * broadcasts out different interfaces.
3564 		 */
3565 		if (flags & IPDF_SELECT_SRC)
3566 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3567 		else
3568 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3569 	}
3570 
3571 	/*
3572 	 * Does the caller want us to pick a source address?
3573 	 */
3574 	if (flags & IPDF_SELECT_SRC) {
3575 		ipaddr_t	src_addr;
3576 
3577 		/*
3578 		 * We use use ire_nexthop_ill to avoid the under ipmp
3579 		 * interface for source address selection. Note that for ipmp
3580 		 * probe packets, ixa_ifindex would have been specified, and
3581 		 * the ip_select_route() invocation would have picked an ire
3582 		 * will ire_ill pointing at an under interface.
3583 		 */
3584 		ill = ire_nexthop_ill(ire);
3585 
3586 		/* If unreachable we have no ill but need some source */
3587 		if (ill == NULL) {
3588 			src_addr = htonl(INADDR_LOOPBACK);
3589 			/* Make sure we look for a better source address */
3590 			generation = SRC_GENERATION_VERIFY;
3591 		} else {
3592 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3593 			    ixa->ixa_multicast_ifaddr, zoneid,
3594 			    ipst, &src_addr, &generation, NULL);
3595 			if (error != 0) {
3596 				ire = NULL;	/* Stored in ixa_ire */
3597 				goto bad_addr;
3598 			}
3599 		}
3600 
3601 		/*
3602 		 * We allow the source address to to down.
3603 		 * However, we check that we don't use the loopback address
3604 		 * as a source when sending out on the wire.
3605 		 */
3606 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3607 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3608 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3609 			ire = NULL;	/* Stored in ixa_ire */
3610 			error = EADDRNOTAVAIL;
3611 			goto bad_addr;
3612 		}
3613 
3614 		*src_addrp = src_addr;
3615 		ixa->ixa_src_generation = generation;
3616 	}
3617 
3618 	/*
3619 	 * Make sure we don't leave an unreachable ixa_nce in place
3620 	 * since ip_select_route is used when we unplumb i.e., remove
3621 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3622 	 */
3623 	nce = ixa->ixa_nce;
3624 	if (nce != NULL && nce->nce_is_condemned) {
3625 		nce_refrele(nce);
3626 		ixa->ixa_nce = NULL;
3627 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3628 	}
3629 
3630 	/*
3631 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3632 	 * However, we can't do it for IPv4 multicast or broadcast.
3633 	 */
3634 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3635 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3636 
3637 	/*
3638 	 * Set initial value for fragmentation limit. Either conn_ip_output
3639 	 * or ULP might updates it when there are routing changes.
3640 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3641 	 */
3642 	pmtu = ip_get_pmtu(ixa);
3643 	ixa->ixa_fragsize = pmtu;
3644 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3645 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3646 		ixa->ixa_pmtu = pmtu;
3647 
3648 	/*
3649 	 * Extract information useful for some transports.
3650 	 * First we look for DCE metrics. Then we take what we have in
3651 	 * the metrics in the route, where the offlink is used if we have
3652 	 * one.
3653 	 */
3654 	if (uinfo != NULL) {
3655 		bzero(uinfo, sizeof (*uinfo));
3656 
3657 		if (dce->dce_flags & DCEF_UINFO)
3658 			*uinfo = dce->dce_uinfo;
3659 
3660 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3661 
3662 		/* Allow ire_metrics to decrease the path MTU from above */
3663 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3664 			uinfo->iulp_mtu = pmtu;
3665 
3666 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3667 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3668 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3669 	}
3670 
3671 	if (ill != NULL)
3672 		ill_refrele(ill);
3673 
3674 	return (error);
3675 
3676 bad_addr:
3677 	if (ire != NULL)
3678 		ire_refrele(ire);
3679 
3680 	if (ill != NULL)
3681 		ill_refrele(ill);
3682 
3683 	/*
3684 	 * Make sure we don't leave an unreachable ixa_nce in place
3685 	 * since ip_select_route is used when we unplumb i.e., remove
3686 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3687 	 */
3688 	nce = ixa->ixa_nce;
3689 	if (nce != NULL && nce->nce_is_condemned) {
3690 		nce_refrele(nce);
3691 		ixa->ixa_nce = NULL;
3692 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3693 	}
3694 
3695 	return (error);
3696 }
3697 
3698 
3699 /*
3700  * Get the base MTU for the case when path MTU discovery is not used.
3701  * Takes the MTU of the IRE into account.
3702  */
3703 uint_t
3704 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3705 {
3706 	uint_t mtu;
3707 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3708 
3709 	if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST))
3710 		mtu = ill->ill_mc_mtu;
3711 	else
3712 		mtu = ill->ill_mtu;
3713 
3714 	if (iremtu != 0 && iremtu < mtu)
3715 		mtu = iremtu;
3716 
3717 	return (mtu);
3718 }
3719 
3720 /*
3721  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3722  * Assumes that ixa_ire, dce, and nce have already been set up.
3723  *
3724  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3725  * We avoid path MTU discovery if it is disabled with ndd.
3726  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3727  *
3728  * NOTE: We also used to turn it off for source routed packets. That
3729  * is no longer required since the dce is per final destination.
3730  */
3731 uint_t
3732 ip_get_pmtu(ip_xmit_attr_t *ixa)
3733 {
3734 	ip_stack_t	*ipst = ixa->ixa_ipst;
3735 	dce_t		*dce;
3736 	nce_t		*nce;
3737 	ire_t		*ire;
3738 	uint_t		pmtu;
3739 
3740 	ire = ixa->ixa_ire;
3741 	dce = ixa->ixa_dce;
3742 	nce = ixa->ixa_nce;
3743 
3744 	/*
3745 	 * If path MTU discovery has been turned off by ndd, then we ignore
3746 	 * any dce_pmtu and for IPv4 we will not set DF.
3747 	 */
3748 	if (!ipst->ips_ip_path_mtu_discovery)
3749 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3750 
3751 	pmtu = IP_MAXPACKET;
3752 	/*
3753 	 * Decide whether whether IPv4 sets DF
3754 	 * For IPv6 "no DF" means to use the 1280 mtu
3755 	 */
3756 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3757 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3758 	} else {
3759 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3760 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3761 			pmtu = IPV6_MIN_MTU;
3762 	}
3763 
3764 	/* Check if the PMTU is to old before we use it */
3765 	if ((dce->dce_flags & DCEF_PMTU) &&
3766 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3767 	    ipst->ips_ip_pathmtu_interval) {
3768 		/*
3769 		 * Older than 20 minutes. Drop the path MTU information.
3770 		 */
3771 		mutex_enter(&dce->dce_lock);
3772 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3773 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3774 		mutex_exit(&dce->dce_lock);
3775 		dce_increment_generation(dce);
3776 	}
3777 
3778 	/* The metrics on the route can lower the path MTU */
3779 	if (ire->ire_metrics.iulp_mtu != 0 &&
3780 	    ire->ire_metrics.iulp_mtu < pmtu)
3781 		pmtu = ire->ire_metrics.iulp_mtu;
3782 
3783 	/*
3784 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3785 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3786 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3787 	 */
3788 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3789 		if (dce->dce_flags & DCEF_PMTU) {
3790 			if (dce->dce_pmtu < pmtu)
3791 				pmtu = dce->dce_pmtu;
3792 
3793 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3794 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3795 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3796 			} else {
3797 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3798 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3799 			}
3800 		} else {
3801 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3802 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3803 		}
3804 	}
3805 
3806 	/*
3807 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3808 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3809 	 * mtu as IRE_LOOPBACK.
3810 	 */
3811 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3812 		uint_t loopback_mtu;
3813 
3814 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3815 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3816 
3817 		if (loopback_mtu < pmtu)
3818 			pmtu = loopback_mtu;
3819 	} else if (nce != NULL) {
3820 		/*
3821 		 * Make sure we don't exceed the interface MTU.
3822 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3823 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3824 		 * to tell the transport something larger than zero.
3825 		 */
3826 		if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST)) {
3827 			if (nce->nce_common->ncec_ill->ill_mc_mtu < pmtu)
3828 				pmtu = nce->nce_common->ncec_ill->ill_mc_mtu;
3829 			if (nce->nce_common->ncec_ill != nce->nce_ill &&
3830 			    nce->nce_ill->ill_mc_mtu < pmtu) {
3831 				/*
3832 				 * for interfaces in an IPMP group, the mtu of
3833 				 * the nce_ill (under_ill) could be different
3834 				 * from the mtu of the ncec_ill, so we take the
3835 				 * min of the two.
3836 				 */
3837 				pmtu = nce->nce_ill->ill_mc_mtu;
3838 			}
3839 		} else {
3840 			if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3841 				pmtu = nce->nce_common->ncec_ill->ill_mtu;
3842 			if (nce->nce_common->ncec_ill != nce->nce_ill &&
3843 			    nce->nce_ill->ill_mtu < pmtu) {
3844 				/*
3845 				 * for interfaces in an IPMP group, the mtu of
3846 				 * the nce_ill (under_ill) could be different
3847 				 * from the mtu of the ncec_ill, so we take the
3848 				 * min of the two.
3849 				 */
3850 				pmtu = nce->nce_ill->ill_mtu;
3851 			}
3852 		}
3853 	}
3854 
3855 	/*
3856 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3857 	 * Only applies to IPv6.
3858 	 */
3859 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3860 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3861 			switch (ixa->ixa_use_min_mtu) {
3862 			case IPV6_USE_MIN_MTU_MULTICAST:
3863 				if (ire->ire_type & IRE_MULTICAST)
3864 					pmtu = IPV6_MIN_MTU;
3865 				break;
3866 			case IPV6_USE_MIN_MTU_ALWAYS:
3867 				pmtu = IPV6_MIN_MTU;
3868 				break;
3869 			case IPV6_USE_MIN_MTU_NEVER:
3870 				break;
3871 			}
3872 		} else {
3873 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3874 			if (ire->ire_type & IRE_MULTICAST)
3875 				pmtu = IPV6_MIN_MTU;
3876 		}
3877 	}
3878 
3879 	/*
3880 	 * For multirouted IPv6 packets, the IP layer will insert a 8-byte
3881 	 * fragment header in every packet. We compensate for those cases by
3882 	 * returning a smaller path MTU to the ULP.
3883 	 *
3884 	 * In the case of CGTP then ip_output will add a fragment header.
3885 	 * Make sure there is room for it by telling a smaller number
3886 	 * to the transport.
3887 	 *
3888 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3889 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3890 	 * which is the size of the packets it can send.
3891 	 */
3892 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3893 		if ((ire->ire_flags & RTF_MULTIRT) ||
3894 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3895 			pmtu -= sizeof (ip6_frag_t);
3896 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3897 		}
3898 	}
3899 
3900 	return (pmtu);
3901 }
3902 
3903 /*
3904  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3905  * the final piece where we don't.  Return a pointer to the first mblk in the
3906  * result, and update the pointer to the next mblk to chew on.  If anything
3907  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3908  * NULL pointer.
3909  */
3910 mblk_t *
3911 ip_carve_mp(mblk_t **mpp, ssize_t len)
3912 {
3913 	mblk_t	*mp0;
3914 	mblk_t	*mp1;
3915 	mblk_t	*mp2;
3916 
3917 	if (!len || !mpp || !(mp0 = *mpp))
3918 		return (NULL);
3919 	/* If we aren't going to consume the first mblk, we need a dup. */
3920 	if (mp0->b_wptr - mp0->b_rptr > len) {
3921 		mp1 = dupb(mp0);
3922 		if (mp1) {
3923 			/* Partition the data between the two mblks. */
3924 			mp1->b_wptr = mp1->b_rptr + len;
3925 			mp0->b_rptr = mp1->b_wptr;
3926 			/*
3927 			 * after adjustments if mblk not consumed is now
3928 			 * unaligned, try to align it. If this fails free
3929 			 * all messages and let upper layer recover.
3930 			 */
3931 			if (!OK_32PTR(mp0->b_rptr)) {
3932 				if (!pullupmsg(mp0, -1)) {
3933 					freemsg(mp0);
3934 					freemsg(mp1);
3935 					*mpp = NULL;
3936 					return (NULL);
3937 				}
3938 			}
3939 		}
3940 		return (mp1);
3941 	}
3942 	/* Eat through as many mblks as we need to get len bytes. */
3943 	len -= mp0->b_wptr - mp0->b_rptr;
3944 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3945 		if (mp2->b_wptr - mp2->b_rptr > len) {
3946 			/*
3947 			 * We won't consume the entire last mblk.  Like
3948 			 * above, dup and partition it.
3949 			 */
3950 			mp1->b_cont = dupb(mp2);
3951 			mp1 = mp1->b_cont;
3952 			if (!mp1) {
3953 				/*
3954 				 * Trouble.  Rather than go to a lot of
3955 				 * trouble to clean up, we free the messages.
3956 				 * This won't be any worse than losing it on
3957 				 * the wire.
3958 				 */
3959 				freemsg(mp0);
3960 				freemsg(mp2);
3961 				*mpp = NULL;
3962 				return (NULL);
3963 			}
3964 			mp1->b_wptr = mp1->b_rptr + len;
3965 			mp2->b_rptr = mp1->b_wptr;
3966 			/*
3967 			 * after adjustments if mblk not consumed is now
3968 			 * unaligned, try to align it. If this fails free
3969 			 * all messages and let upper layer recover.
3970 			 */
3971 			if (!OK_32PTR(mp2->b_rptr)) {
3972 				if (!pullupmsg(mp2, -1)) {
3973 					freemsg(mp0);
3974 					freemsg(mp2);
3975 					*mpp = NULL;
3976 					return (NULL);
3977 				}
3978 			}
3979 			*mpp = mp2;
3980 			return (mp0);
3981 		}
3982 		/* Decrement len by the amount we just got. */
3983 		len -= mp2->b_wptr - mp2->b_rptr;
3984 	}
3985 	/*
3986 	 * len should be reduced to zero now.  If not our caller has
3987 	 * screwed up.
3988 	 */
3989 	if (len) {
3990 		/* Shouldn't happen! */
3991 		freemsg(mp0);
3992 		*mpp = NULL;
3993 		return (NULL);
3994 	}
3995 	/*
3996 	 * We consumed up to exactly the end of an mblk.  Detach the part
3997 	 * we are returning from the rest of the chain.
3998 	 */
3999 	mp1->b_cont = NULL;
4000 	*mpp = mp2;
4001 	return (mp0);
4002 }
4003 
4004 /* The ill stream is being unplumbed. Called from ip_close */
4005 int
4006 ip_modclose(ill_t *ill)
4007 {
4008 	boolean_t success;
4009 	ipsq_t	*ipsq;
4010 	ipif_t	*ipif;
4011 	queue_t	*q = ill->ill_rq;
4012 	ip_stack_t	*ipst = ill->ill_ipst;
4013 	int	i;
4014 	arl_ill_common_t *ai = ill->ill_common;
4015 
4016 	/*
4017 	 * The punlink prior to this may have initiated a capability
4018 	 * negotiation. But ipsq_enter will block until that finishes or
4019 	 * times out.
4020 	 */
4021 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
4022 
4023 	/*
4024 	 * Open/close/push/pop is guaranteed to be single threaded
4025 	 * per stream by STREAMS. FS guarantees that all references
4026 	 * from top are gone before close is called. So there can't
4027 	 * be another close thread that has set CONDEMNED on this ill.
4028 	 * and cause ipsq_enter to return failure.
4029 	 */
4030 	ASSERT(success);
4031 	ipsq = ill->ill_phyint->phyint_ipsq;
4032 
4033 	/*
4034 	 * Mark it condemned. No new reference will be made to this ill.
4035 	 * Lookup functions will return an error. Threads that try to
4036 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4037 	 * that the refcnt will drop down to zero.
4038 	 */
4039 	mutex_enter(&ill->ill_lock);
4040 	ill->ill_state_flags |= ILL_CONDEMNED;
4041 	for (ipif = ill->ill_ipif; ipif != NULL;
4042 	    ipif = ipif->ipif_next) {
4043 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4044 	}
4045 	/*
4046 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4047 	 * returns  error if ILL_CONDEMNED is set
4048 	 */
4049 	cv_broadcast(&ill->ill_cv);
4050 	mutex_exit(&ill->ill_lock);
4051 
4052 	/*
4053 	 * Send all the deferred DLPI messages downstream which came in
4054 	 * during the small window right before ipsq_enter(). We do this
4055 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4056 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4057 	 */
4058 	ill_dlpi_send_deferred(ill);
4059 
4060 	/*
4061 	 * Shut down fragmentation reassembly.
4062 	 * ill_frag_timer won't start a timer again.
4063 	 * Now cancel any existing timer
4064 	 */
4065 	(void) untimeout(ill->ill_frag_timer_id);
4066 	(void) ill_frag_timeout(ill, 0);
4067 
4068 	/*
4069 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4070 	 * this ill. Then wait for the refcnts to drop to zero.
4071 	 * ill_is_freeable checks whether the ill is really quiescent.
4072 	 * Then make sure that threads that are waiting to enter the
4073 	 * ipsq have seen the error returned by ipsq_enter and have
4074 	 * gone away. Then we call ill_delete_tail which does the
4075 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4076 	 */
4077 	ill_delete(ill);
4078 	mutex_enter(&ill->ill_lock);
4079 	while (!ill_is_freeable(ill))
4080 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4081 
4082 	while (ill->ill_waiters)
4083 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4084 
4085 	mutex_exit(&ill->ill_lock);
4086 
4087 	/*
4088 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4089 	 * it held until the end of the function since the cleanup
4090 	 * below needs to be able to use the ip_stack_t.
4091 	 */
4092 	netstack_hold(ipst->ips_netstack);
4093 
4094 	/* qprocsoff is done via ill_delete_tail */
4095 	ill_delete_tail(ill);
4096 	/*
4097 	 * synchronously wait for arp stream to unbind. After this, we
4098 	 * cannot get any data packets up from the driver.
4099 	 */
4100 	arp_unbind_complete(ill);
4101 	ASSERT(ill->ill_ipst == NULL);
4102 
4103 	/*
4104 	 * Walk through all conns and qenable those that have queued data.
4105 	 * Close synchronization needs this to
4106 	 * be done to ensure that all upper layers blocked
4107 	 * due to flow control to the closing device
4108 	 * get unblocked.
4109 	 */
4110 	ip1dbg(("ip_wsrv: walking\n"));
4111 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4112 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4113 	}
4114 
4115 	/*
4116 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4117 	 * stream is being torn down before ARP was plumbed (e.g.,
4118 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4119 	 * an error
4120 	 */
4121 	if (ai != NULL) {
4122 		ASSERT(!ill->ill_isv6);
4123 		mutex_enter(&ai->ai_lock);
4124 		ai->ai_ill = NULL;
4125 		if (ai->ai_arl == NULL) {
4126 			mutex_destroy(&ai->ai_lock);
4127 			kmem_free(ai, sizeof (*ai));
4128 		} else {
4129 			cv_signal(&ai->ai_ill_unplumb_done);
4130 			mutex_exit(&ai->ai_lock);
4131 		}
4132 	}
4133 
4134 	mutex_enter(&ipst->ips_ip_mi_lock);
4135 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4136 	mutex_exit(&ipst->ips_ip_mi_lock);
4137 
4138 	/*
4139 	 * credp could be null if the open didn't succeed and ip_modopen
4140 	 * itself calls ip_close.
4141 	 */
4142 	if (ill->ill_credp != NULL)
4143 		crfree(ill->ill_credp);
4144 
4145 	mutex_destroy(&ill->ill_saved_ire_lock);
4146 	mutex_destroy(&ill->ill_lock);
4147 	rw_destroy(&ill->ill_mcast_lock);
4148 	mutex_destroy(&ill->ill_mcast_serializer);
4149 	list_destroy(&ill->ill_nce);
4150 
4151 	/*
4152 	 * Now we are done with the module close pieces that
4153 	 * need the netstack_t.
4154 	 */
4155 	netstack_rele(ipst->ips_netstack);
4156 
4157 	mi_close_free((IDP)ill);
4158 	q->q_ptr = WR(q)->q_ptr = NULL;
4159 
4160 	ipsq_exit(ipsq);
4161 
4162 	return (0);
4163 }
4164 
4165 /*
4166  * This is called as part of close() for IP, UDP, ICMP, and RTS
4167  * in order to quiesce the conn.
4168  */
4169 void
4170 ip_quiesce_conn(conn_t *connp)
4171 {
4172 	boolean_t	drain_cleanup_reqd = B_FALSE;
4173 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4174 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4175 	ip_stack_t	*ipst;
4176 
4177 	ASSERT(!IPCL_IS_TCP(connp));
4178 	ipst = connp->conn_netstack->netstack_ip;
4179 
4180 	/*
4181 	 * Mark the conn as closing, and this conn must not be
4182 	 * inserted in future into any list. Eg. conn_drain_insert(),
4183 	 * won't insert this conn into the conn_drain_list.
4184 	 *
4185 	 * conn_idl, and conn_ilg cannot get set henceforth.
4186 	 */
4187 	mutex_enter(&connp->conn_lock);
4188 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4189 	connp->conn_state_flags |= CONN_CLOSING;
4190 	if (connp->conn_idl != NULL)
4191 		drain_cleanup_reqd = B_TRUE;
4192 	if (connp->conn_oper_pending_ill != NULL)
4193 		conn_ioctl_cleanup_reqd = B_TRUE;
4194 	if (connp->conn_dhcpinit_ill != NULL) {
4195 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4196 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4197 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4198 		connp->conn_dhcpinit_ill = NULL;
4199 	}
4200 	if (connp->conn_ilg != NULL)
4201 		ilg_cleanup_reqd = B_TRUE;
4202 	mutex_exit(&connp->conn_lock);
4203 
4204 	if (conn_ioctl_cleanup_reqd)
4205 		conn_ioctl_cleanup(connp);
4206 
4207 	if (is_system_labeled() && connp->conn_anon_port) {
4208 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4209 		    connp->conn_mlp_type, connp->conn_proto,
4210 		    ntohs(connp->conn_lport), B_FALSE);
4211 		connp->conn_anon_port = 0;
4212 	}
4213 	connp->conn_mlp_type = mlptSingle;
4214 
4215 	/*
4216 	 * Remove this conn from any fanout list it is on.
4217 	 * and then wait for any threads currently operating
4218 	 * on this endpoint to finish
4219 	 */
4220 	ipcl_hash_remove(connp);
4221 
4222 	/*
4223 	 * Remove this conn from the drain list, and do any other cleanup that
4224 	 * may be required.  (TCP conns are never flow controlled, and
4225 	 * conn_idl will be NULL.)
4226 	 */
4227 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4228 		idl_t *idl = connp->conn_idl;
4229 
4230 		mutex_enter(&idl->idl_lock);
4231 		conn_drain(connp, B_TRUE);
4232 		mutex_exit(&idl->idl_lock);
4233 	}
4234 
4235 	if (connp == ipst->ips_ip_g_mrouter)
4236 		(void) ip_mrouter_done(ipst);
4237 
4238 	if (ilg_cleanup_reqd)
4239 		ilg_delete_all(connp);
4240 
4241 	/*
4242 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4243 	 * callers from write side can't be there now because close
4244 	 * is in progress. The only other caller is ipcl_walk
4245 	 * which checks for the condemned flag.
4246 	 */
4247 	mutex_enter(&connp->conn_lock);
4248 	connp->conn_state_flags |= CONN_CONDEMNED;
4249 	while (connp->conn_ref != 1)
4250 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4251 	connp->conn_state_flags |= CONN_QUIESCED;
4252 	mutex_exit(&connp->conn_lock);
4253 }
4254 
4255 /* ARGSUSED */
4256 int
4257 ip_close(queue_t *q, int flags, cred_t *credp __unused)
4258 {
4259 	conn_t		*connp;
4260 
4261 	/*
4262 	 * Call the appropriate delete routine depending on whether this is
4263 	 * a module or device.
4264 	 */
4265 	if (WR(q)->q_next != NULL) {
4266 		/* This is a module close */
4267 		return (ip_modclose((ill_t *)q->q_ptr));
4268 	}
4269 
4270 	connp = q->q_ptr;
4271 	ip_quiesce_conn(connp);
4272 
4273 	qprocsoff(q);
4274 
4275 	/*
4276 	 * Now we are truly single threaded on this stream, and can
4277 	 * delete the things hanging off the connp, and finally the connp.
4278 	 * We removed this connp from the fanout list, it cannot be
4279 	 * accessed thru the fanouts, and we already waited for the
4280 	 * conn_ref to drop to 0. We are already in close, so
4281 	 * there cannot be any other thread from the top. qprocsoff
4282 	 * has completed, and service has completed or won't run in
4283 	 * future.
4284 	 */
4285 	ASSERT(connp->conn_ref == 1);
4286 
4287 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4288 
4289 	connp->conn_ref--;
4290 	ipcl_conn_destroy(connp);
4291 
4292 	q->q_ptr = WR(q)->q_ptr = NULL;
4293 	return (0);
4294 }
4295 
4296 /*
4297  * Wapper around putnext() so that ip_rts_request can merely use
4298  * conn_recv.
4299  */
4300 /*ARGSUSED2*/
4301 static void
4302 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4303 {
4304 	conn_t *connp = (conn_t *)arg1;
4305 
4306 	putnext(connp->conn_rq, mp);
4307 }
4308 
4309 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4310 /* ARGSUSED */
4311 static void
4312 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4313 {
4314 	freemsg(mp);
4315 }
4316 
4317 /*
4318  * Called when the module is about to be unloaded
4319  */
4320 void
4321 ip_ddi_destroy(void)
4322 {
4323 	/* This needs to be called before destroying any transports. */
4324 	mutex_enter(&cpu_lock);
4325 	unregister_cpu_setup_func(ip_tp_cpu_update, NULL);
4326 	mutex_exit(&cpu_lock);
4327 
4328 	tnet_fini();
4329 
4330 	icmp_ddi_g_destroy();
4331 	rts_ddi_g_destroy();
4332 	udp_ddi_g_destroy();
4333 	sctp_ddi_g_destroy();
4334 	tcp_ddi_g_destroy();
4335 	ilb_ddi_g_destroy();
4336 	dce_g_destroy();
4337 	ipsec_policy_g_destroy();
4338 	ipcl_g_destroy();
4339 	ip_net_g_destroy();
4340 	ip_ire_g_fini();
4341 	inet_minor_destroy(ip_minor_arena_sa);
4342 #if defined(_LP64)
4343 	inet_minor_destroy(ip_minor_arena_la);
4344 #endif
4345 
4346 #ifdef DEBUG
4347 	list_destroy(&ip_thread_list);
4348 	rw_destroy(&ip_thread_rwlock);
4349 	tsd_destroy(&ip_thread_data);
4350 #endif
4351 
4352 	netstack_unregister(NS_IP);
4353 }
4354 
4355 /*
4356  * First step in cleanup.
4357  */
4358 /* ARGSUSED */
4359 static void
4360 ip_stack_shutdown(netstackid_t stackid, void *arg)
4361 {
4362 	ip_stack_t *ipst = (ip_stack_t *)arg;
4363 	kt_did_t ktid;
4364 
4365 #ifdef NS_DEBUG
4366 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4367 #endif
4368 
4369 	/*
4370 	 * Perform cleanup for special interfaces (loopback and IPMP).
4371 	 */
4372 	ip_interface_cleanup(ipst);
4373 
4374 	/*
4375 	 * The *_hook_shutdown()s start the process of notifying any
4376 	 * consumers that things are going away.... nothing is destroyed.
4377 	 */
4378 	ipv4_hook_shutdown(ipst);
4379 	ipv6_hook_shutdown(ipst);
4380 	arp_hook_shutdown(ipst);
4381 
4382 	mutex_enter(&ipst->ips_capab_taskq_lock);
4383 	ktid = ipst->ips_capab_taskq_thread->t_did;
4384 	ipst->ips_capab_taskq_quit = B_TRUE;
4385 	cv_signal(&ipst->ips_capab_taskq_cv);
4386 	mutex_exit(&ipst->ips_capab_taskq_lock);
4387 
4388 	/*
4389 	 * In rare occurrences, particularly on virtual hardware where CPUs can
4390 	 * be de-scheduled, the thread that we just signaled will not run until
4391 	 * after we have gotten through parts of ip_stack_fini. If that happens
4392 	 * then we'll try to grab the ips_capab_taskq_lock as part of returning
4393 	 * from cv_wait which no longer exists.
4394 	 */
4395 	thread_join(ktid);
4396 }
4397 
4398 /*
4399  * Free the IP stack instance.
4400  */
4401 static void
4402 ip_stack_fini(netstackid_t stackid, void *arg)
4403 {
4404 	ip_stack_t *ipst = (ip_stack_t *)arg;
4405 	int ret;
4406 
4407 #ifdef NS_DEBUG
4408 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4409 #endif
4410 	/*
4411 	 * At this point, all of the notifications that the events and
4412 	 * protocols are going away have been run, meaning that we can
4413 	 * now set about starting to clean things up.
4414 	 */
4415 	ipobs_fini(ipst);
4416 	ipv4_hook_destroy(ipst);
4417 	ipv6_hook_destroy(ipst);
4418 	arp_hook_destroy(ipst);
4419 	ip_net_destroy(ipst);
4420 
4421 	ipmp_destroy(ipst);
4422 
4423 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4424 	ipst->ips_ip_mibkp = NULL;
4425 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4426 	ipst->ips_icmp_mibkp = NULL;
4427 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4428 	ipst->ips_ip_kstat = NULL;
4429 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4430 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4431 	ipst->ips_ip6_kstat = NULL;
4432 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4433 
4434 	kmem_free(ipst->ips_propinfo_tbl,
4435 	    ip_propinfo_count * sizeof (mod_prop_info_t));
4436 	ipst->ips_propinfo_tbl = NULL;
4437 
4438 	dce_stack_destroy(ipst);
4439 	ip_mrouter_stack_destroy(ipst);
4440 
4441 	/*
4442 	 * Quiesce all of our timers. Note we set the quiesce flags before we
4443 	 * call untimeout. The slowtimers may actually kick off another instance
4444 	 * of the non-slow timers.
4445 	 */
4446 	mutex_enter(&ipst->ips_igmp_timer_lock);
4447 	ipst->ips_igmp_timer_quiesce = B_TRUE;
4448 	mutex_exit(&ipst->ips_igmp_timer_lock);
4449 
4450 	mutex_enter(&ipst->ips_mld_timer_lock);
4451 	ipst->ips_mld_timer_quiesce = B_TRUE;
4452 	mutex_exit(&ipst->ips_mld_timer_lock);
4453 
4454 	mutex_enter(&ipst->ips_igmp_slowtimeout_lock);
4455 	ipst->ips_igmp_slowtimeout_quiesce = B_TRUE;
4456 	mutex_exit(&ipst->ips_igmp_slowtimeout_lock);
4457 
4458 	mutex_enter(&ipst->ips_mld_slowtimeout_lock);
4459 	ipst->ips_mld_slowtimeout_quiesce = B_TRUE;
4460 	mutex_exit(&ipst->ips_mld_slowtimeout_lock);
4461 
4462 	ret = untimeout(ipst->ips_igmp_timeout_id);
4463 	if (ret == -1) {
4464 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4465 	} else {
4466 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4467 		ipst->ips_igmp_timeout_id = 0;
4468 	}
4469 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4470 	if (ret == -1) {
4471 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4472 	} else {
4473 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4474 		ipst->ips_igmp_slowtimeout_id = 0;
4475 	}
4476 	ret = untimeout(ipst->ips_mld_timeout_id);
4477 	if (ret == -1) {
4478 		ASSERT(ipst->ips_mld_timeout_id == 0);
4479 	} else {
4480 		ASSERT(ipst->ips_mld_timeout_id != 0);
4481 		ipst->ips_mld_timeout_id = 0;
4482 	}
4483 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4484 	if (ret == -1) {
4485 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4486 	} else {
4487 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4488 		ipst->ips_mld_slowtimeout_id = 0;
4489 	}
4490 
4491 	ip_ire_fini(ipst);
4492 	ip6_asp_free(ipst);
4493 	conn_drain_fini(ipst);
4494 	ipcl_destroy(ipst);
4495 
4496 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4497 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4498 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4499 	ipst->ips_ndp4 = NULL;
4500 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4501 	ipst->ips_ndp6 = NULL;
4502 
4503 	if (ipst->ips_loopback_ksp != NULL) {
4504 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4505 		ipst->ips_loopback_ksp = NULL;
4506 	}
4507 
4508 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4509 	cv_destroy(&ipst->ips_capab_taskq_cv);
4510 
4511 	rw_destroy(&ipst->ips_srcid_lock);
4512 
4513 	mutex_destroy(&ipst->ips_ip_mi_lock);
4514 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4515 
4516 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4517 	mutex_destroy(&ipst->ips_mld_timer_lock);
4518 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4519 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4520 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4521 	rw_destroy(&ipst->ips_ill_g_lock);
4522 
4523 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4524 	ipst->ips_phyint_g_list = NULL;
4525 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4526 	ipst->ips_ill_g_heads = NULL;
4527 
4528 	ldi_ident_release(ipst->ips_ldi_ident);
4529 	kmem_free(ipst, sizeof (*ipst));
4530 }
4531 
4532 /*
4533  * This function is called from the TSD destructor, and is used to debug
4534  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4535  * details.
4536  */
4537 static void
4538 ip_thread_exit(void *phash)
4539 {
4540 	th_hash_t *thh = phash;
4541 
4542 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4543 	list_remove(&ip_thread_list, thh);
4544 	rw_exit(&ip_thread_rwlock);
4545 	mod_hash_destroy_hash(thh->thh_hash);
4546 	kmem_free(thh, sizeof (*thh));
4547 }
4548 
4549 /*
4550  * Called when the IP kernel module is loaded into the kernel
4551  */
4552 void
4553 ip_ddi_init(void)
4554 {
4555 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4556 
4557 	/*
4558 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4559 	 * initial devices: ip, ip6, tcp, tcp6.
4560 	 */
4561 	/*
4562 	 * If this is a 64-bit kernel, then create two separate arenas -
4563 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4564 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4565 	 */
4566 	ip_minor_arena_la = NULL;
4567 	ip_minor_arena_sa = NULL;
4568 #if defined(_LP64)
4569 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4570 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4571 		cmn_err(CE_PANIC,
4572 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4573 	}
4574 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4575 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4576 		cmn_err(CE_PANIC,
4577 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4578 	}
4579 #else
4580 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4581 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4582 		cmn_err(CE_PANIC,
4583 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4584 	}
4585 #endif
4586 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4587 
4588 	ipcl_g_init();
4589 	ip_ire_g_init();
4590 	ip_net_g_init();
4591 
4592 #ifdef DEBUG
4593 	tsd_create(&ip_thread_data, ip_thread_exit);
4594 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4595 	list_create(&ip_thread_list, sizeof (th_hash_t),
4596 	    offsetof(th_hash_t, thh_link));
4597 #endif
4598 	ipsec_policy_g_init();
4599 	tcp_ddi_g_init();
4600 	sctp_ddi_g_init();
4601 	dce_g_init();
4602 
4603 	/*
4604 	 * We want to be informed each time a stack is created or
4605 	 * destroyed in the kernel, so we can maintain the
4606 	 * set of udp_stack_t's.
4607 	 */
4608 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4609 	    ip_stack_fini);
4610 
4611 	tnet_init();
4612 
4613 	udp_ddi_g_init();
4614 	rts_ddi_g_init();
4615 	icmp_ddi_g_init();
4616 	ilb_ddi_g_init();
4617 
4618 	/* This needs to be called after all transports are initialized. */
4619 	mutex_enter(&cpu_lock);
4620 	register_cpu_setup_func(ip_tp_cpu_update, NULL);
4621 	mutex_exit(&cpu_lock);
4622 }
4623 
4624 /*
4625  * Initialize the IP stack instance.
4626  */
4627 static void *
4628 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4629 {
4630 	ip_stack_t	*ipst;
4631 	size_t		arrsz;
4632 	major_t		major;
4633 
4634 #ifdef NS_DEBUG
4635 	printf("ip_stack_init(stack %d)\n", stackid);
4636 #endif
4637 
4638 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4639 	ipst->ips_netstack = ns;
4640 
4641 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4642 	    KM_SLEEP);
4643 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4644 	    KM_SLEEP);
4645 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4646 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4647 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4648 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4649 
4650 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4651 	ipst->ips_igmp_deferred_next = INFINITY;
4652 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4653 	ipst->ips_mld_deferred_next = INFINITY;
4654 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4655 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4656 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4657 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4658 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4659 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4660 
4661 	ipcl_init(ipst);
4662 	ip_ire_init(ipst);
4663 	ip6_asp_init(ipst);
4664 	ipif_init(ipst);
4665 	conn_drain_init(ipst);
4666 	ip_mrouter_stack_init(ipst);
4667 	dce_stack_init(ipst);
4668 
4669 	ipst->ips_ip_multirt_log_interval = 1000;
4670 
4671 	ipst->ips_ill_index = 1;
4672 
4673 	ipst->ips_saved_ip_forwarding = -1;
4674 	ipst->ips_reg_vif_num = ALL_VIFS;	/* Index to Register vif */
4675 
4676 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4677 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4678 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4679 
4680 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4681 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4682 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4683 	ipst->ips_ip6_kstat =
4684 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4685 
4686 	ipst->ips_ip_src_id = 1;
4687 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4688 
4689 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4690 
4691 	ip_net_init(ipst, ns);
4692 	ipv4_hook_init(ipst);
4693 	ipv6_hook_init(ipst);
4694 	arp_hook_init(ipst);
4695 	ipmp_init(ipst);
4696 	ipobs_init(ipst);
4697 
4698 	/*
4699 	 * Create the taskq dispatcher thread and initialize related stuff.
4700 	 */
4701 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4702 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4703 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4704 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4705 
4706 	major = mod_name_to_major(INET_NAME);
4707 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4708 	return (ipst);
4709 }
4710 
4711 /*
4712  * Allocate and initialize a DLPI template of the specified length.  (May be
4713  * called as writer.)
4714  */
4715 mblk_t *
4716 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4717 {
4718 	mblk_t	*mp;
4719 
4720 	mp = allocb(len, BPRI_MED);
4721 	if (!mp)
4722 		return (NULL);
4723 
4724 	/*
4725 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4726 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4727 	 * that other DLPI are M_PROTO.
4728 	 */
4729 	if (prim == DL_INFO_REQ) {
4730 		mp->b_datap->db_type = M_PCPROTO;
4731 	} else {
4732 		mp->b_datap->db_type = M_PROTO;
4733 	}
4734 
4735 	mp->b_wptr = mp->b_rptr + len;
4736 	bzero(mp->b_rptr, len);
4737 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4738 	return (mp);
4739 }
4740 
4741 /*
4742  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4743  */
4744 mblk_t *
4745 ip_dlnotify_alloc(uint_t notification, uint_t data)
4746 {
4747 	dl_notify_ind_t	*notifyp;
4748 	mblk_t		*mp;
4749 
4750 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4751 		return (NULL);
4752 
4753 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4754 	notifyp->dl_notification = notification;
4755 	notifyp->dl_data = data;
4756 	return (mp);
4757 }
4758 
4759 mblk_t *
4760 ip_dlnotify_alloc2(uint_t notification, uint_t data1, uint_t data2)
4761 {
4762 	dl_notify_ind_t	*notifyp;
4763 	mblk_t		*mp;
4764 
4765 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4766 		return (NULL);
4767 
4768 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4769 	notifyp->dl_notification = notification;
4770 	notifyp->dl_data1 = data1;
4771 	notifyp->dl_data2 = data2;
4772 	return (mp);
4773 }
4774 
4775 /*
4776  * Debug formatting routine.  Returns a character string representation of the
4777  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4778  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4779  *
4780  * Once the ndd table-printing interfaces are removed, this can be changed to
4781  * standard dotted-decimal form.
4782  */
4783 char *
4784 ip_dot_addr(ipaddr_t addr, char *buf)
4785 {
4786 	uint8_t *ap = (uint8_t *)&addr;
4787 
4788 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4789 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4790 	return (buf);
4791 }
4792 
4793 /*
4794  * Write the given MAC address as a printable string in the usual colon-
4795  * separated format.
4796  */
4797 const char *
4798 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4799 {
4800 	char *bp;
4801 
4802 	if (alen == 0 || buflen < 4)
4803 		return ("?");
4804 	bp = buf;
4805 	for (;;) {
4806 		/*
4807 		 * If there are more MAC address bytes available, but we won't
4808 		 * have any room to print them, then add "..." to the string
4809 		 * instead.  See below for the 'magic number' explanation.
4810 		 */
4811 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4812 			(void) strcpy(bp, "...");
4813 			break;
4814 		}
4815 		(void) sprintf(bp, "%02x", *addr++);
4816 		bp += 2;
4817 		if (--alen == 0)
4818 			break;
4819 		*bp++ = ':';
4820 		buflen -= 3;
4821 		/*
4822 		 * At this point, based on the first 'if' statement above,
4823 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4824 		 * buflen >= 4.  The first case leaves room for the final "xx"
4825 		 * number and trailing NUL byte.  The second leaves room for at
4826 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4827 		 * that statement.
4828 		 */
4829 	}
4830 	return (buf);
4831 }
4832 
4833 /*
4834  * Called when it is conceptually a ULP that would sent the packet
4835  * e.g., port unreachable and protocol unreachable. Check that the packet
4836  * would have passed the IPsec global policy before sending the error.
4837  *
4838  * Send an ICMP error after patching up the packet appropriately.
4839  * Uses ip_drop_input and bumps the appropriate MIB.
4840  */
4841 void
4842 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4843     ip_recv_attr_t *ira)
4844 {
4845 	ipha_t		*ipha;
4846 	boolean_t	secure;
4847 	ill_t		*ill = ira->ira_ill;
4848 	ip_stack_t	*ipst = ill->ill_ipst;
4849 	netstack_t	*ns = ipst->ips_netstack;
4850 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4851 
4852 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4853 
4854 	/*
4855 	 * We are generating an icmp error for some inbound packet.
4856 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4857 	 * Before we generate an error, check with global policy
4858 	 * to see whether this is allowed to enter the system. As
4859 	 * there is no "conn", we are checking with global policy.
4860 	 */
4861 	ipha = (ipha_t *)mp->b_rptr;
4862 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4863 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4864 		if (mp == NULL)
4865 			return;
4866 	}
4867 
4868 	/* We never send errors for protocols that we do implement */
4869 	if (ira->ira_protocol == IPPROTO_ICMP ||
4870 	    ira->ira_protocol == IPPROTO_IGMP) {
4871 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4872 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4873 		freemsg(mp);
4874 		return;
4875 	}
4876 	/*
4877 	 * Have to correct checksum since
4878 	 * the packet might have been
4879 	 * fragmented and the reassembly code in ip_rput
4880 	 * does not restore the IP checksum.
4881 	 */
4882 	ipha->ipha_hdr_checksum = 0;
4883 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4884 
4885 	switch (icmp_type) {
4886 	case ICMP_DEST_UNREACHABLE:
4887 		switch (icmp_code) {
4888 		case ICMP_PROTOCOL_UNREACHABLE:
4889 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4890 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4891 			break;
4892 		case ICMP_PORT_UNREACHABLE:
4893 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4894 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4895 			break;
4896 		}
4897 
4898 		icmp_unreachable(mp, icmp_code, ira);
4899 		break;
4900 	default:
4901 #ifdef DEBUG
4902 		panic("ip_fanout_send_icmp_v4: wrong type");
4903 		/*NOTREACHED*/
4904 #else
4905 		freemsg(mp);
4906 		break;
4907 #endif
4908 	}
4909 }
4910 
4911 /*
4912  * Used to send an ICMP error message when a packet is received for
4913  * a protocol that is not supported. The mblk passed as argument
4914  * is consumed by this function.
4915  */
4916 void
4917 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4918 {
4919 	ipha_t		*ipha;
4920 
4921 	ipha = (ipha_t *)mp->b_rptr;
4922 	if (ira->ira_flags & IRAF_IS_IPV4) {
4923 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4924 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4925 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4926 	} else {
4927 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4928 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4929 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4930 	}
4931 }
4932 
4933 /*
4934  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4935  * Handles IPv4 and IPv6.
4936  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4937  * Caller is responsible for dropping references to the conn.
4938  */
4939 void
4940 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4941     ip_recv_attr_t *ira)
4942 {
4943 	ill_t		*ill = ira->ira_ill;
4944 	ip_stack_t	*ipst = ill->ill_ipst;
4945 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4946 	boolean_t	secure;
4947 	uint_t		protocol = ira->ira_protocol;
4948 	iaflags_t	iraflags = ira->ira_flags;
4949 	queue_t		*rq;
4950 
4951 	secure = iraflags & IRAF_IPSEC_SECURE;
4952 
4953 	rq = connp->conn_rq;
4954 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4955 		switch (protocol) {
4956 		case IPPROTO_ICMPV6:
4957 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4958 			break;
4959 		case IPPROTO_ICMP:
4960 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4961 			break;
4962 		default:
4963 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4964 			break;
4965 		}
4966 		freemsg(mp);
4967 		return;
4968 	}
4969 
4970 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4971 
4972 	if (((iraflags & IRAF_IS_IPV4) ?
4973 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4974 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4975 	    secure) {
4976 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4977 		    ip6h, ira);
4978 		if (mp == NULL) {
4979 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4980 			/* Note that mp is NULL */
4981 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4982 			return;
4983 		}
4984 	}
4985 
4986 	if (iraflags & IRAF_ICMP_ERROR) {
4987 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4988 	} else {
4989 		ill_t *rill = ira->ira_rill;
4990 
4991 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4992 		ira->ira_ill = ira->ira_rill = NULL;
4993 		/* Send it upstream */
4994 		(connp->conn_recv)(connp, mp, NULL, ira);
4995 		ira->ira_ill = ill;
4996 		ira->ira_rill = rill;
4997 	}
4998 }
4999 
5000 /*
5001  * Handle protocols with which IP is less intimate.  There
5002  * can be more than one stream bound to a particular
5003  * protocol.  When this is the case, normally each one gets a copy
5004  * of any incoming packets.
5005  *
5006  * IPsec NOTE :
5007  *
5008  * Don't allow a secure packet going up a non-secure connection.
5009  * We don't allow this because
5010  *
5011  * 1) Reply might go out in clear which will be dropped at
5012  *    the sending side.
5013  * 2) If the reply goes out in clear it will give the
5014  *    adversary enough information for getting the key in
5015  *    most of the cases.
5016  *
5017  * Moreover getting a secure packet when we expect clear
5018  * implies that SA's were added without checking for
5019  * policy on both ends. This should not happen once ISAKMP
5020  * is used to negotiate SAs as SAs will be added only after
5021  * verifying the policy.
5022  *
5023  * Zones notes:
5024  * Earlier in ip_input on a system with multiple shared-IP zones we
5025  * duplicate the multicast and broadcast packets and send them up
5026  * with each explicit zoneid that exists on that ill.
5027  * This means that here we can match the zoneid with SO_ALLZONES being special.
5028  */
5029 void
5030 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
5031 {
5032 	mblk_t		*mp1;
5033 	ipaddr_t	laddr;
5034 	conn_t		*connp, *first_connp, *next_connp;
5035 	connf_t		*connfp;
5036 	ill_t		*ill = ira->ira_ill;
5037 	ip_stack_t	*ipst = ill->ill_ipst;
5038 
5039 	laddr = ipha->ipha_dst;
5040 
5041 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
5042 	mutex_enter(&connfp->connf_lock);
5043 	connp = connfp->connf_head;
5044 	for (connp = connfp->connf_head; connp != NULL;
5045 	    connp = connp->conn_next) {
5046 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5047 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5048 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5049 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
5050 			break;
5051 		}
5052 	}
5053 
5054 	if (connp == NULL) {
5055 		/*
5056 		 * No one bound to these addresses.  Is
5057 		 * there a client that wants all
5058 		 * unclaimed datagrams?
5059 		 */
5060 		mutex_exit(&connfp->connf_lock);
5061 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5062 		    ICMP_PROTOCOL_UNREACHABLE, ira);
5063 		return;
5064 	}
5065 
5066 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5067 
5068 	CONN_INC_REF(connp);
5069 	first_connp = connp;
5070 	connp = connp->conn_next;
5071 
5072 	for (;;) {
5073 		while (connp != NULL) {
5074 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5075 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5076 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5077 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5078 			    ira, connp)))
5079 				break;
5080 			connp = connp->conn_next;
5081 		}
5082 
5083 		if (connp == NULL) {
5084 			/* No more interested clients */
5085 			connp = first_connp;
5086 			break;
5087 		}
5088 		if (((mp1 = dupmsg(mp)) == NULL) &&
5089 		    ((mp1 = copymsg(mp)) == NULL)) {
5090 			/* Memory allocation failed */
5091 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5092 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5093 			connp = first_connp;
5094 			break;
5095 		}
5096 
5097 		CONN_INC_REF(connp);
5098 		mutex_exit(&connfp->connf_lock);
5099 
5100 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5101 		    ira);
5102 
5103 		mutex_enter(&connfp->connf_lock);
5104 		/* Follow the next pointer before releasing the conn. */
5105 		next_connp = connp->conn_next;
5106 		CONN_DEC_REF(connp);
5107 		connp = next_connp;
5108 	}
5109 
5110 	/* Last one.  Send it upstream. */
5111 	mutex_exit(&connfp->connf_lock);
5112 
5113 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5114 
5115 	CONN_DEC_REF(connp);
5116 }
5117 
5118 /*
5119  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5120  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5121  * is not consumed.
5122  *
5123  * One of three things can happen, all of which affect the passed-in mblk:
5124  *
5125  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5126  *
5127  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5128  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5129  *
5130  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5131  */
5132 mblk_t *
5133 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5134 {
5135 	int shift, plen, iph_len;
5136 	ipha_t *ipha;
5137 	udpha_t *udpha;
5138 	uint32_t *spi;
5139 	uint32_t esp_ports;
5140 	uint8_t *orptr;
5141 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5142 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5143 
5144 	ipha = (ipha_t *)mp->b_rptr;
5145 	iph_len = ira->ira_ip_hdr_length;
5146 	plen = ira->ira_pktlen;
5147 
5148 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5149 		/*
5150 		 * Most likely a keepalive for the benefit of an intervening
5151 		 * NAT.  These aren't for us, per se, so drop it.
5152 		 *
5153 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5154 		 * byte packets (keepalives are 1-byte), but we'll drop them
5155 		 * also.
5156 		 */
5157 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5158 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5159 		return (NULL);
5160 	}
5161 
5162 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5163 		/* might as well pull it all up - it might be ESP. */
5164 		if (!pullupmsg(mp, -1)) {
5165 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5166 			    DROPPER(ipss, ipds_esp_nomem),
5167 			    &ipss->ipsec_dropper);
5168 			return (NULL);
5169 		}
5170 
5171 		ipha = (ipha_t *)mp->b_rptr;
5172 	}
5173 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5174 	if (*spi == 0) {
5175 		/* UDP packet - remove 0-spi. */
5176 		shift = sizeof (uint32_t);
5177 	} else {
5178 		/* ESP-in-UDP packet - reduce to ESP. */
5179 		ipha->ipha_protocol = IPPROTO_ESP;
5180 		shift = sizeof (udpha_t);
5181 	}
5182 
5183 	/* Fix IP header */
5184 	ira->ira_pktlen = (plen - shift);
5185 	ipha->ipha_length = htons(ira->ira_pktlen);
5186 	ipha->ipha_hdr_checksum = 0;
5187 
5188 	orptr = mp->b_rptr;
5189 	mp->b_rptr += shift;
5190 
5191 	udpha = (udpha_t *)(orptr + iph_len);
5192 	if (*spi == 0) {
5193 		ASSERT((uint8_t *)ipha == orptr);
5194 		udpha->uha_length = htons(plen - shift - iph_len);
5195 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5196 		esp_ports = 0;
5197 	} else {
5198 		esp_ports = *((uint32_t *)udpha);
5199 		ASSERT(esp_ports != 0);
5200 	}
5201 	ovbcopy(orptr, orptr + shift, iph_len);
5202 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5203 		ipha = (ipha_t *)(orptr + shift);
5204 
5205 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5206 		ira->ira_esp_udp_ports = esp_ports;
5207 		ip_fanout_v4(mp, ipha, ira);
5208 		return (NULL);
5209 	}
5210 	return (mp);
5211 }
5212 
5213 /*
5214  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5215  * Handles IPv4 and IPv6.
5216  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5217  * Caller is responsible for dropping references to the conn.
5218  */
5219 void
5220 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5221     ip_recv_attr_t *ira)
5222 {
5223 	ill_t		*ill = ira->ira_ill;
5224 	ip_stack_t	*ipst = ill->ill_ipst;
5225 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5226 	boolean_t	secure;
5227 	iaflags_t	iraflags = ira->ira_flags;
5228 
5229 	secure = iraflags & IRAF_IPSEC_SECURE;
5230 
5231 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5232 	    !canputnext(connp->conn_rq)) {
5233 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5234 		freemsg(mp);
5235 		return;
5236 	}
5237 
5238 	if (((iraflags & IRAF_IS_IPV4) ?
5239 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5240 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5241 	    secure) {
5242 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5243 		    ip6h, ira);
5244 		if (mp == NULL) {
5245 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5246 			/* Note that mp is NULL */
5247 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5248 			return;
5249 		}
5250 	}
5251 
5252 	/*
5253 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5254 	 * check. Only ip_fanout_v4 has that check.
5255 	 */
5256 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5257 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5258 	} else {
5259 		ill_t *rill = ira->ira_rill;
5260 
5261 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5262 		ira->ira_ill = ira->ira_rill = NULL;
5263 		/* Send it upstream */
5264 		(connp->conn_recv)(connp, mp, NULL, ira);
5265 		ira->ira_ill = ill;
5266 		ira->ira_rill = rill;
5267 	}
5268 }
5269 
5270 /*
5271  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5272  * (Unicast fanout is handled in ip_input_v4.)
5273  *
5274  * If SO_REUSEADDR is set all multicast and broadcast packets
5275  * will be delivered to all conns bound to the same port.
5276  *
5277  * If there is at least one matching AF_INET receiver, then we will
5278  * ignore any AF_INET6 receivers.
5279  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5280  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5281  * packets.
5282  *
5283  * Zones notes:
5284  * Earlier in ip_input on a system with multiple shared-IP zones we
5285  * duplicate the multicast and broadcast packets and send them up
5286  * with each explicit zoneid that exists on that ill.
5287  * This means that here we can match the zoneid with SO_ALLZONES being special.
5288  */
5289 void
5290 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5291     ip_recv_attr_t *ira)
5292 {
5293 	ipaddr_t	laddr;
5294 	in6_addr_t	v6faddr;
5295 	conn_t		*connp;
5296 	connf_t		*connfp;
5297 	ipaddr_t	faddr;
5298 	ill_t		*ill = ira->ira_ill;
5299 	ip_stack_t	*ipst = ill->ill_ipst;
5300 
5301 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5302 
5303 	laddr = ipha->ipha_dst;
5304 	faddr = ipha->ipha_src;
5305 
5306 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5307 	mutex_enter(&connfp->connf_lock);
5308 	connp = connfp->connf_head;
5309 
5310 	/*
5311 	 * If SO_REUSEADDR has been set on the first we send the
5312 	 * packet to all clients that have joined the group and
5313 	 * match the port.
5314 	 */
5315 	while (connp != NULL) {
5316 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5317 		    conn_wantpacket(connp, ira, ipha) &&
5318 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5319 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5320 			break;
5321 		connp = connp->conn_next;
5322 	}
5323 
5324 	if (connp == NULL)
5325 		goto notfound;
5326 
5327 	CONN_INC_REF(connp);
5328 
5329 	if (connp->conn_reuseaddr) {
5330 		conn_t		*first_connp = connp;
5331 		conn_t		*next_connp;
5332 		mblk_t		*mp1;
5333 
5334 		connp = connp->conn_next;
5335 		for (;;) {
5336 			while (connp != NULL) {
5337 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5338 				    fport, faddr) &&
5339 				    conn_wantpacket(connp, ira, ipha) &&
5340 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5341 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5342 				    ira, connp)))
5343 					break;
5344 				connp = connp->conn_next;
5345 			}
5346 			if (connp == NULL) {
5347 				/* No more interested clients */
5348 				connp = first_connp;
5349 				break;
5350 			}
5351 			if (((mp1 = dupmsg(mp)) == NULL) &&
5352 			    ((mp1 = copymsg(mp)) == NULL)) {
5353 				/* Memory allocation failed */
5354 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5355 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5356 				connp = first_connp;
5357 				break;
5358 			}
5359 			CONN_INC_REF(connp);
5360 			mutex_exit(&connfp->connf_lock);
5361 
5362 			IP_STAT(ipst, ip_udp_fanmb);
5363 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5364 			    NULL, ira);
5365 			mutex_enter(&connfp->connf_lock);
5366 			/* Follow the next pointer before releasing the conn */
5367 			next_connp = connp->conn_next;
5368 			CONN_DEC_REF(connp);
5369 			connp = next_connp;
5370 		}
5371 	}
5372 
5373 	/* Last one.  Send it upstream. */
5374 	mutex_exit(&connfp->connf_lock);
5375 	IP_STAT(ipst, ip_udp_fanmb);
5376 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5377 	CONN_DEC_REF(connp);
5378 	return;
5379 
5380 notfound:
5381 	mutex_exit(&connfp->connf_lock);
5382 	/*
5383 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5384 	 * have already been matched above, since they live in the IPv4
5385 	 * fanout tables. This implies we only need to
5386 	 * check for IPv6 in6addr_any endpoints here.
5387 	 * Thus we compare using ipv6_all_zeros instead of the destination
5388 	 * address, except for the multicast group membership lookup which
5389 	 * uses the IPv4 destination.
5390 	 */
5391 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5392 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5393 	mutex_enter(&connfp->connf_lock);
5394 	connp = connfp->connf_head;
5395 	/*
5396 	 * IPv4 multicast packet being delivered to an AF_INET6
5397 	 * in6addr_any endpoint.
5398 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5399 	 * and not conn_wantpacket_v6() since any multicast membership is
5400 	 * for an IPv4-mapped multicast address.
5401 	 */
5402 	while (connp != NULL) {
5403 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5404 		    fport, v6faddr) &&
5405 		    conn_wantpacket(connp, ira, ipha) &&
5406 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5407 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5408 			break;
5409 		connp = connp->conn_next;
5410 	}
5411 
5412 	if (connp == NULL) {
5413 		/*
5414 		 * No one bound to this port.  Is
5415 		 * there a client that wants all
5416 		 * unclaimed datagrams?
5417 		 */
5418 		mutex_exit(&connfp->connf_lock);
5419 
5420 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5421 		    NULL) {
5422 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5423 			ip_fanout_proto_v4(mp, ipha, ira);
5424 		} else {
5425 			/*
5426 			 * We used to attempt to send an icmp error here, but
5427 			 * since this is known to be a multicast packet
5428 			 * and we don't send icmp errors in response to
5429 			 * multicast, just drop the packet and give up sooner.
5430 			 */
5431 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5432 			freemsg(mp);
5433 		}
5434 		return;
5435 	}
5436 	CONN_INC_REF(connp);
5437 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5438 
5439 	/*
5440 	 * If SO_REUSEADDR has been set on the first we send the
5441 	 * packet to all clients that have joined the group and
5442 	 * match the port.
5443 	 */
5444 	if (connp->conn_reuseaddr) {
5445 		conn_t		*first_connp = connp;
5446 		conn_t		*next_connp;
5447 		mblk_t		*mp1;
5448 
5449 		connp = connp->conn_next;
5450 		for (;;) {
5451 			while (connp != NULL) {
5452 				if (IPCL_UDP_MATCH_V6(connp, lport,
5453 				    ipv6_all_zeros, fport, v6faddr) &&
5454 				    conn_wantpacket(connp, ira, ipha) &&
5455 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5456 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5457 				    ira, connp)))
5458 					break;
5459 				connp = connp->conn_next;
5460 			}
5461 			if (connp == NULL) {
5462 				/* No more interested clients */
5463 				connp = first_connp;
5464 				break;
5465 			}
5466 			if (((mp1 = dupmsg(mp)) == NULL) &&
5467 			    ((mp1 = copymsg(mp)) == NULL)) {
5468 				/* Memory allocation failed */
5469 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5470 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5471 				connp = first_connp;
5472 				break;
5473 			}
5474 			CONN_INC_REF(connp);
5475 			mutex_exit(&connfp->connf_lock);
5476 
5477 			IP_STAT(ipst, ip_udp_fanmb);
5478 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5479 			    NULL, ira);
5480 			mutex_enter(&connfp->connf_lock);
5481 			/* Follow the next pointer before releasing the conn */
5482 			next_connp = connp->conn_next;
5483 			CONN_DEC_REF(connp);
5484 			connp = next_connp;
5485 		}
5486 	}
5487 
5488 	/* Last one.  Send it upstream. */
5489 	mutex_exit(&connfp->connf_lock);
5490 	IP_STAT(ipst, ip_udp_fanmb);
5491 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5492 	CONN_DEC_REF(connp);
5493 }
5494 
5495 /*
5496  * Split an incoming packet's IPv4 options into the label and the other options.
5497  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5498  * clearing out any leftover label or options.
5499  * Otherwise it just makes ipp point into the packet.
5500  *
5501  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5502  */
5503 int
5504 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5505 {
5506 	uchar_t		*opt;
5507 	uint32_t	totallen;
5508 	uint32_t	optval;
5509 	uint32_t	optlen;
5510 
5511 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5512 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5513 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5514 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5515 
5516 	/*
5517 	 * Get length (in 4 byte octets) of IP header options.
5518 	 */
5519 	totallen = ipha->ipha_version_and_hdr_length -
5520 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5521 
5522 	if (totallen == 0) {
5523 		if (!allocate)
5524 			return (0);
5525 
5526 		/* Clear out anything from a previous packet */
5527 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5528 			kmem_free(ipp->ipp_ipv4_options,
5529 			    ipp->ipp_ipv4_options_len);
5530 			ipp->ipp_ipv4_options = NULL;
5531 			ipp->ipp_ipv4_options_len = 0;
5532 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5533 		}
5534 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5535 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5536 			ipp->ipp_label_v4 = NULL;
5537 			ipp->ipp_label_len_v4 = 0;
5538 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5539 		}
5540 		return (0);
5541 	}
5542 
5543 	totallen <<= 2;
5544 	opt = (uchar_t *)&ipha[1];
5545 	if (!is_system_labeled()) {
5546 
5547 	copyall:
5548 		if (!allocate) {
5549 			if (totallen != 0) {
5550 				ipp->ipp_ipv4_options = opt;
5551 				ipp->ipp_ipv4_options_len = totallen;
5552 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5553 			}
5554 			return (0);
5555 		}
5556 		/* Just copy all of options */
5557 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5558 			if (totallen == ipp->ipp_ipv4_options_len) {
5559 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5560 				return (0);
5561 			}
5562 			kmem_free(ipp->ipp_ipv4_options,
5563 			    ipp->ipp_ipv4_options_len);
5564 			ipp->ipp_ipv4_options = NULL;
5565 			ipp->ipp_ipv4_options_len = 0;
5566 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5567 		}
5568 		if (totallen == 0)
5569 			return (0);
5570 
5571 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5572 		if (ipp->ipp_ipv4_options == NULL)
5573 			return (ENOMEM);
5574 		ipp->ipp_ipv4_options_len = totallen;
5575 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5576 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5577 		return (0);
5578 	}
5579 
5580 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5581 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5582 		ipp->ipp_label_v4 = NULL;
5583 		ipp->ipp_label_len_v4 = 0;
5584 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5585 	}
5586 
5587 	/*
5588 	 * Search for CIPSO option.
5589 	 * We assume CIPSO is first in options if it is present.
5590 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5591 	 * prior to the CIPSO option.
5592 	 */
5593 	while (totallen != 0) {
5594 		switch (optval = opt[IPOPT_OPTVAL]) {
5595 		case IPOPT_EOL:
5596 			return (0);
5597 		case IPOPT_NOP:
5598 			optlen = 1;
5599 			break;
5600 		default:
5601 			if (totallen <= IPOPT_OLEN)
5602 				return (EINVAL);
5603 			optlen = opt[IPOPT_OLEN];
5604 			if (optlen < 2)
5605 				return (EINVAL);
5606 		}
5607 		if (optlen > totallen)
5608 			return (EINVAL);
5609 
5610 		switch (optval) {
5611 		case IPOPT_COMSEC:
5612 			if (!allocate) {
5613 				ipp->ipp_label_v4 = opt;
5614 				ipp->ipp_label_len_v4 = optlen;
5615 				ipp->ipp_fields |= IPPF_LABEL_V4;
5616 			} else {
5617 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5618 				    KM_NOSLEEP);
5619 				if (ipp->ipp_label_v4 == NULL)
5620 					return (ENOMEM);
5621 				ipp->ipp_label_len_v4 = optlen;
5622 				ipp->ipp_fields |= IPPF_LABEL_V4;
5623 				bcopy(opt, ipp->ipp_label_v4, optlen);
5624 			}
5625 			totallen -= optlen;
5626 			opt += optlen;
5627 
5628 			/* Skip padding bytes until we get to a multiple of 4 */
5629 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5630 				totallen--;
5631 				opt++;
5632 			}
5633 			/* Remaining as ipp_ipv4_options */
5634 			goto copyall;
5635 		}
5636 		totallen -= optlen;
5637 		opt += optlen;
5638 	}
5639 	/* No CIPSO found; return everything as ipp_ipv4_options */
5640 	totallen = ipha->ipha_version_and_hdr_length -
5641 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5642 	totallen <<= 2;
5643 	opt = (uchar_t *)&ipha[1];
5644 	goto copyall;
5645 }
5646 
5647 /*
5648  * Efficient versions of lookup for an IRE when we only
5649  * match the address.
5650  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5651  * Does not handle multicast addresses.
5652  */
5653 uint_t
5654 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5655 {
5656 	ire_t *ire;
5657 	uint_t result;
5658 
5659 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5660 	ASSERT(ire != NULL);
5661 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5662 		result = IRE_NOROUTE;
5663 	else
5664 		result = ire->ire_type;
5665 	ire_refrele(ire);
5666 	return (result);
5667 }
5668 
5669 /*
5670  * Efficient versions of lookup for an IRE when we only
5671  * match the address.
5672  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5673  * Does not handle multicast addresses.
5674  */
5675 uint_t
5676 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5677 {
5678 	ire_t *ire;
5679 	uint_t result;
5680 
5681 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5682 	ASSERT(ire != NULL);
5683 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5684 		result = IRE_NOROUTE;
5685 	else
5686 		result = ire->ire_type;
5687 	ire_refrele(ire);
5688 	return (result);
5689 }
5690 
5691 /*
5692  * Nobody should be sending
5693  * packets up this stream
5694  */
5695 static int
5696 ip_lrput(queue_t *q, mblk_t *mp)
5697 {
5698 	switch (mp->b_datap->db_type) {
5699 	case M_FLUSH:
5700 		/* Turn around */
5701 		if (*mp->b_rptr & FLUSHW) {
5702 			*mp->b_rptr &= ~FLUSHR;
5703 			qreply(q, mp);
5704 			return (0);
5705 		}
5706 		break;
5707 	}
5708 	freemsg(mp);
5709 	return (0);
5710 }
5711 
5712 /* Nobody should be sending packets down this stream */
5713 /* ARGSUSED */
5714 int
5715 ip_lwput(queue_t *q, mblk_t *mp)
5716 {
5717 	freemsg(mp);
5718 	return (0);
5719 }
5720 
5721 /*
5722  * Move the first hop in any source route to ipha_dst and remove that part of
5723  * the source route.  Called by other protocols.  Errors in option formatting
5724  * are ignored - will be handled by ip_output_options. Return the final
5725  * destination (either ipha_dst or the last entry in a source route.)
5726  */
5727 ipaddr_t
5728 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5729 {
5730 	ipoptp_t	opts;
5731 	uchar_t		*opt;
5732 	uint8_t		optval;
5733 	uint8_t		optlen;
5734 	ipaddr_t	dst;
5735 	int		i;
5736 	ip_stack_t	*ipst = ns->netstack_ip;
5737 
5738 	ip2dbg(("ip_massage_options\n"));
5739 	dst = ipha->ipha_dst;
5740 	for (optval = ipoptp_first(&opts, ipha);
5741 	    optval != IPOPT_EOL;
5742 	    optval = ipoptp_next(&opts)) {
5743 		opt = opts.ipoptp_cur;
5744 		switch (optval) {
5745 			uint8_t off;
5746 		case IPOPT_SSRR:
5747 		case IPOPT_LSRR:
5748 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5749 				ip1dbg(("ip_massage_options: bad src route\n"));
5750 				break;
5751 			}
5752 			optlen = opts.ipoptp_len;
5753 			off = opt[IPOPT_OFFSET];
5754 			off--;
5755 		redo_srr:
5756 			if (optlen < IP_ADDR_LEN ||
5757 			    off > optlen - IP_ADDR_LEN) {
5758 				/* End of source route */
5759 				ip1dbg(("ip_massage_options: end of SR\n"));
5760 				break;
5761 			}
5762 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5763 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5764 			    ntohl(dst)));
5765 			/*
5766 			 * Check if our address is present more than
5767 			 * once as consecutive hops in source route.
5768 			 * XXX verify per-interface ip_forwarding
5769 			 * for source route?
5770 			 */
5771 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5772 				off += IP_ADDR_LEN;
5773 				goto redo_srr;
5774 			}
5775 			if (dst == htonl(INADDR_LOOPBACK)) {
5776 				ip1dbg(("ip_massage_options: loopback addr in "
5777 				    "source route!\n"));
5778 				break;
5779 			}
5780 			/*
5781 			 * Update ipha_dst to be the first hop and remove the
5782 			 * first hop from the source route (by overwriting
5783 			 * part of the option with NOP options).
5784 			 */
5785 			ipha->ipha_dst = dst;
5786 			/* Put the last entry in dst */
5787 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5788 			    3;
5789 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5790 
5791 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5792 			    ntohl(dst)));
5793 			/* Move down and overwrite */
5794 			opt[IP_ADDR_LEN] = opt[0];
5795 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5796 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5797 			for (i = 0; i < IP_ADDR_LEN; i++)
5798 				opt[i] = IPOPT_NOP;
5799 			break;
5800 		}
5801 	}
5802 	return (dst);
5803 }
5804 
5805 /*
5806  * Return the network mask
5807  * associated with the specified address.
5808  */
5809 ipaddr_t
5810 ip_net_mask(ipaddr_t addr)
5811 {
5812 	uchar_t	*up = (uchar_t *)&addr;
5813 	ipaddr_t mask = 0;
5814 	uchar_t	*maskp = (uchar_t *)&mask;
5815 
5816 #if defined(__x86)
5817 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5818 #endif
5819 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5820 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5821 #endif
5822 	if (CLASSD(addr)) {
5823 		maskp[0] = 0xF0;
5824 		return (mask);
5825 	}
5826 
5827 	/* We assume Class E default netmask to be 32 */
5828 	if (CLASSE(addr))
5829 		return (0xffffffffU);
5830 
5831 	if (addr == 0)
5832 		return (0);
5833 	maskp[0] = 0xFF;
5834 	if ((up[0] & 0x80) == 0)
5835 		return (mask);
5836 
5837 	maskp[1] = 0xFF;
5838 	if ((up[0] & 0xC0) == 0x80)
5839 		return (mask);
5840 
5841 	maskp[2] = 0xFF;
5842 	if ((up[0] & 0xE0) == 0xC0)
5843 		return (mask);
5844 
5845 	/* Otherwise return no mask */
5846 	return ((ipaddr_t)0);
5847 }
5848 
5849 /* Name/Value Table Lookup Routine */
5850 char *
5851 ip_nv_lookup(nv_t *nv, int value)
5852 {
5853 	if (!nv)
5854 		return (NULL);
5855 	for (; nv->nv_name; nv++) {
5856 		if (nv->nv_value == value)
5857 			return (nv->nv_name);
5858 	}
5859 	return ("unknown");
5860 }
5861 
5862 static int
5863 ip_wait_for_info_ack(ill_t *ill)
5864 {
5865 	int err;
5866 
5867 	mutex_enter(&ill->ill_lock);
5868 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5869 		/*
5870 		 * Return value of 0 indicates a pending signal.
5871 		 */
5872 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5873 		if (err == 0) {
5874 			mutex_exit(&ill->ill_lock);
5875 			return (EINTR);
5876 		}
5877 	}
5878 	mutex_exit(&ill->ill_lock);
5879 	/*
5880 	 * ip_rput_other could have set an error  in ill_error on
5881 	 * receipt of M_ERROR.
5882 	 */
5883 	return (ill->ill_error);
5884 }
5885 
5886 /*
5887  * This is a module open, i.e. this is a control stream for access
5888  * to a DLPI device.  We allocate an ill_t as the instance data in
5889  * this case.
5890  */
5891 static int
5892 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5893 {
5894 	ill_t	*ill;
5895 	int	err;
5896 	zoneid_t zoneid;
5897 	netstack_t *ns;
5898 	ip_stack_t *ipst;
5899 
5900 	/*
5901 	 * Prevent unprivileged processes from pushing IP so that
5902 	 * they can't send raw IP.
5903 	 */
5904 	if (secpolicy_net_rawaccess(credp) != 0)
5905 		return (EPERM);
5906 
5907 	ns = netstack_find_by_cred(credp);
5908 	ASSERT(ns != NULL);
5909 	ipst = ns->netstack_ip;
5910 	ASSERT(ipst != NULL);
5911 
5912 	/*
5913 	 * For exclusive stacks we set the zoneid to zero
5914 	 * to make IP operate as if in the global zone.
5915 	 */
5916 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5917 		zoneid = GLOBAL_ZONEID;
5918 	else
5919 		zoneid = crgetzoneid(credp);
5920 
5921 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5922 	q->q_ptr = WR(q)->q_ptr = ill;
5923 	ill->ill_ipst = ipst;
5924 	ill->ill_zoneid = zoneid;
5925 
5926 	/*
5927 	 * ill_init initializes the ill fields and then sends down
5928 	 * down a DL_INFO_REQ after calling qprocson.
5929 	 */
5930 	err = ill_init(q, ill);
5931 
5932 	if (err != 0) {
5933 		mi_free(ill);
5934 		netstack_rele(ipst->ips_netstack);
5935 		q->q_ptr = NULL;
5936 		WR(q)->q_ptr = NULL;
5937 		return (err);
5938 	}
5939 
5940 	/*
5941 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5942 	 *
5943 	 * ill_init initializes the ipsq marking this thread as
5944 	 * writer
5945 	 */
5946 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5947 	err = ip_wait_for_info_ack(ill);
5948 	if (err == 0)
5949 		ill->ill_credp = credp;
5950 	else
5951 		goto fail;
5952 
5953 	crhold(credp);
5954 
5955 	mutex_enter(&ipst->ips_ip_mi_lock);
5956 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5957 	    sflag, credp);
5958 	mutex_exit(&ipst->ips_ip_mi_lock);
5959 fail:
5960 	if (err) {
5961 		(void) ip_close(q, 0, credp);
5962 		return (err);
5963 	}
5964 	return (0);
5965 }
5966 
5967 /* For /dev/ip aka AF_INET open */
5968 int
5969 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5970 {
5971 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5972 }
5973 
5974 /* For /dev/ip6 aka AF_INET6 open */
5975 int
5976 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5977 {
5978 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5979 }
5980 
5981 /* IP open routine. */
5982 int
5983 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5984     boolean_t isv6)
5985 {
5986 	conn_t		*connp;
5987 	major_t		maj;
5988 	zoneid_t	zoneid;
5989 	netstack_t	*ns;
5990 	ip_stack_t	*ipst;
5991 
5992 	/* Allow reopen. */
5993 	if (q->q_ptr != NULL)
5994 		return (0);
5995 
5996 	if (sflag & MODOPEN) {
5997 		/* This is a module open */
5998 		return (ip_modopen(q, devp, flag, sflag, credp));
5999 	}
6000 
6001 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
6002 		/*
6003 		 * Non streams based socket looking for a stream
6004 		 * to access IP
6005 		 */
6006 		return (ip_helper_stream_setup(q, devp, flag, sflag,
6007 		    credp, isv6));
6008 	}
6009 
6010 	ns = netstack_find_by_cred(credp);
6011 	ASSERT(ns != NULL);
6012 	ipst = ns->netstack_ip;
6013 	ASSERT(ipst != NULL);
6014 
6015 	/*
6016 	 * For exclusive stacks we set the zoneid to zero
6017 	 * to make IP operate as if in the global zone.
6018 	 */
6019 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
6020 		zoneid = GLOBAL_ZONEID;
6021 	else
6022 		zoneid = crgetzoneid(credp);
6023 
6024 	/*
6025 	 * We are opening as a device. This is an IP client stream, and we
6026 	 * allocate an conn_t as the instance data.
6027 	 */
6028 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
6029 
6030 	/*
6031 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
6032 	 * done by netstack_find_by_cred()
6033 	 */
6034 	netstack_rele(ipst->ips_netstack);
6035 
6036 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
6037 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
6038 	connp->conn_ixa->ixa_zoneid = zoneid;
6039 	connp->conn_zoneid = zoneid;
6040 
6041 	connp->conn_rq = q;
6042 	q->q_ptr = WR(q)->q_ptr = connp;
6043 
6044 	/* Minor tells us which /dev entry was opened */
6045 	if (isv6) {
6046 		connp->conn_family = AF_INET6;
6047 		connp->conn_ipversion = IPV6_VERSION;
6048 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
6049 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
6050 	} else {
6051 		connp->conn_family = AF_INET;
6052 		connp->conn_ipversion = IPV4_VERSION;
6053 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
6054 	}
6055 
6056 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
6057 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
6058 		connp->conn_minor_arena = ip_minor_arena_la;
6059 	} else {
6060 		/*
6061 		 * Either minor numbers in the large arena were exhausted
6062 		 * or a non socket application is doing the open.
6063 		 * Try to allocate from the small arena.
6064 		 */
6065 		if ((connp->conn_dev =
6066 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
6067 			/* CONN_DEC_REF takes care of netstack_rele() */
6068 			q->q_ptr = WR(q)->q_ptr = NULL;
6069 			CONN_DEC_REF(connp);
6070 			return (EBUSY);
6071 		}
6072 		connp->conn_minor_arena = ip_minor_arena_sa;
6073 	}
6074 
6075 	maj = getemajor(*devp);
6076 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
6077 
6078 	/*
6079 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
6080 	 */
6081 	connp->conn_cred = credp;
6082 	connp->conn_cpid = curproc->p_pid;
6083 	/* Cache things in ixa without an extra refhold */
6084 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
6085 	connp->conn_ixa->ixa_cred = connp->conn_cred;
6086 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6087 	if (is_system_labeled())
6088 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6089 
6090 	/*
6091 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6092 	 */
6093 	connp->conn_recv = ip_conn_input;
6094 	connp->conn_recvicmp = ip_conn_input_icmp;
6095 
6096 	crhold(connp->conn_cred);
6097 
6098 	/*
6099 	 * If the caller has the process-wide flag set, then default to MAC
6100 	 * exempt mode.  This allows read-down to unlabeled hosts.
6101 	 */
6102 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6103 		connp->conn_mac_mode = CONN_MAC_AWARE;
6104 
6105 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6106 
6107 	connp->conn_rq = q;
6108 	connp->conn_wq = WR(q);
6109 
6110 	/* Non-zero default values */
6111 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6112 
6113 	/*
6114 	 * Make the conn globally visible to walkers
6115 	 */
6116 	ASSERT(connp->conn_ref == 1);
6117 	mutex_enter(&connp->conn_lock);
6118 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6119 	mutex_exit(&connp->conn_lock);
6120 
6121 	qprocson(q);
6122 
6123 	return (0);
6124 }
6125 
6126 /*
6127  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6128  * all of them are copied to the conn_t. If the req is "zero", the policy is
6129  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6130  * fields.
6131  * We keep only the latest setting of the policy and thus policy setting
6132  * is not incremental/cumulative.
6133  *
6134  * Requests to set policies with multiple alternative actions will
6135  * go through a different API.
6136  */
6137 int
6138 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6139 {
6140 	uint_t ah_req = 0;
6141 	uint_t esp_req = 0;
6142 	uint_t se_req = 0;
6143 	ipsec_act_t *actp = NULL;
6144 	uint_t nact;
6145 	ipsec_policy_head_t *ph;
6146 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6147 	int error = 0;
6148 	netstack_t	*ns = connp->conn_netstack;
6149 	ip_stack_t	*ipst = ns->netstack_ip;
6150 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6151 
6152 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6153 
6154 	/*
6155 	 * The IP_SEC_OPT option does not allow variable length parameters,
6156 	 * hence a request cannot be NULL.
6157 	 */
6158 	if (req == NULL)
6159 		return (EINVAL);
6160 
6161 	ah_req = req->ipsr_ah_req;
6162 	esp_req = req->ipsr_esp_req;
6163 	se_req = req->ipsr_self_encap_req;
6164 
6165 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6166 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6167 		return (EINVAL);
6168 
6169 	/*
6170 	 * Are we dealing with a request to reset the policy (i.e.
6171 	 * zero requests).
6172 	 */
6173 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6174 	    (esp_req & REQ_MASK) == 0 &&
6175 	    (se_req & REQ_MASK) == 0);
6176 
6177 	if (!is_pol_reset) {
6178 		/*
6179 		 * If we couldn't load IPsec, fail with "protocol
6180 		 * not supported".
6181 		 * IPsec may not have been loaded for a request with zero
6182 		 * policies, so we don't fail in this case.
6183 		 */
6184 		mutex_enter(&ipss->ipsec_loader_lock);
6185 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6186 			mutex_exit(&ipss->ipsec_loader_lock);
6187 			return (EPROTONOSUPPORT);
6188 		}
6189 		mutex_exit(&ipss->ipsec_loader_lock);
6190 
6191 		/*
6192 		 * Test for valid requests. Invalid algorithms
6193 		 * need to be tested by IPsec code because new
6194 		 * algorithms can be added dynamically.
6195 		 */
6196 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6197 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6198 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6199 			return (EINVAL);
6200 		}
6201 
6202 		/*
6203 		 * Only privileged users can issue these
6204 		 * requests.
6205 		 */
6206 		if (((ah_req & IPSEC_PREF_NEVER) ||
6207 		    (esp_req & IPSEC_PREF_NEVER) ||
6208 		    (se_req & IPSEC_PREF_NEVER)) &&
6209 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6210 			return (EPERM);
6211 		}
6212 
6213 		/*
6214 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6215 		 * are mutually exclusive.
6216 		 */
6217 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6218 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6219 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6220 			/* Both of them are set */
6221 			return (EINVAL);
6222 		}
6223 	}
6224 
6225 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6226 
6227 	/*
6228 	 * If we have already cached policies in conn_connect(), don't
6229 	 * let them change now. We cache policies for connections
6230 	 * whose src,dst [addr, port] is known.
6231 	 */
6232 	if (connp->conn_policy_cached) {
6233 		return (EINVAL);
6234 	}
6235 
6236 	/*
6237 	 * We have a zero policies, reset the connection policy if already
6238 	 * set. This will cause the connection to inherit the
6239 	 * global policy, if any.
6240 	 */
6241 	if (is_pol_reset) {
6242 		if (connp->conn_policy != NULL) {
6243 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6244 			connp->conn_policy = NULL;
6245 		}
6246 		connp->conn_in_enforce_policy = B_FALSE;
6247 		connp->conn_out_enforce_policy = B_FALSE;
6248 		return (0);
6249 	}
6250 
6251 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6252 	    ipst->ips_netstack);
6253 	if (ph == NULL)
6254 		goto enomem;
6255 
6256 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6257 	if (actp == NULL)
6258 		goto enomem;
6259 
6260 	/*
6261 	 * Always insert IPv4 policy entries, since they can also apply to
6262 	 * ipv6 sockets being used in ipv4-compat mode.
6263 	 */
6264 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6265 	    IPSEC_TYPE_INBOUND, ns))
6266 		goto enomem;
6267 	is_pol_inserted = B_TRUE;
6268 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6269 	    IPSEC_TYPE_OUTBOUND, ns))
6270 		goto enomem;
6271 
6272 	/*
6273 	 * We're looking at a v6 socket, also insert the v6-specific
6274 	 * entries.
6275 	 */
6276 	if (connp->conn_family == AF_INET6) {
6277 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6278 		    IPSEC_TYPE_INBOUND, ns))
6279 			goto enomem;
6280 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6281 		    IPSEC_TYPE_OUTBOUND, ns))
6282 			goto enomem;
6283 	}
6284 
6285 	ipsec_actvec_free(actp, nact);
6286 
6287 	/*
6288 	 * If the requests need security, set enforce_policy.
6289 	 * If the requests are IPSEC_PREF_NEVER, one should
6290 	 * still set conn_out_enforce_policy so that ip_set_destination
6291 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6292 	 * for connections that we don't cache policy in at connect time,
6293 	 * if global policy matches in ip_output_attach_policy, we
6294 	 * don't wrongly inherit global policy. Similarly, we need
6295 	 * to set conn_in_enforce_policy also so that we don't verify
6296 	 * policy wrongly.
6297 	 */
6298 	if ((ah_req & REQ_MASK) != 0 ||
6299 	    (esp_req & REQ_MASK) != 0 ||
6300 	    (se_req & REQ_MASK) != 0) {
6301 		connp->conn_in_enforce_policy = B_TRUE;
6302 		connp->conn_out_enforce_policy = B_TRUE;
6303 	}
6304 
6305 	return (error);
6306 #undef REQ_MASK
6307 
6308 	/*
6309 	 * Common memory-allocation-failure exit path.
6310 	 */
6311 enomem:
6312 	if (actp != NULL)
6313 		ipsec_actvec_free(actp, nact);
6314 	if (is_pol_inserted)
6315 		ipsec_polhead_flush(ph, ns);
6316 	return (ENOMEM);
6317 }
6318 
6319 /*
6320  * Set socket options for joining and leaving multicast groups.
6321  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6322  * The caller has already check that the option name is consistent with
6323  * the address family of the socket.
6324  */
6325 int
6326 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6327     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6328 {
6329 	int		*i1 = (int *)invalp;
6330 	int		error = 0;
6331 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6332 	struct ip_mreq	*v4_mreqp;
6333 	struct ipv6_mreq *v6_mreqp;
6334 	struct group_req *greqp;
6335 	ire_t *ire;
6336 	boolean_t done = B_FALSE;
6337 	ipaddr_t ifaddr;
6338 	in6_addr_t v6group;
6339 	uint_t ifindex;
6340 	boolean_t mcast_opt = B_TRUE;
6341 	mcast_record_t fmode;
6342 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6343 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6344 
6345 	switch (name) {
6346 	case IP_ADD_MEMBERSHIP:
6347 	case IPV6_JOIN_GROUP:
6348 		mcast_opt = B_FALSE;
6349 		/* FALLTHROUGH */
6350 	case MCAST_JOIN_GROUP:
6351 		fmode = MODE_IS_EXCLUDE;
6352 		optfn = ip_opt_add_group;
6353 		break;
6354 
6355 	case IP_DROP_MEMBERSHIP:
6356 	case IPV6_LEAVE_GROUP:
6357 		mcast_opt = B_FALSE;
6358 		/* FALLTHROUGH */
6359 	case MCAST_LEAVE_GROUP:
6360 		fmode = MODE_IS_INCLUDE;
6361 		optfn = ip_opt_delete_group;
6362 		break;
6363 	default:
6364 		/* Should not be reached. */
6365 		fmode = MODE_IS_INCLUDE;
6366 		optfn = NULL;
6367 		ASSERT(0);
6368 	}
6369 
6370 	if (mcast_opt) {
6371 		struct sockaddr_in *sin;
6372 		struct sockaddr_in6 *sin6;
6373 
6374 		greqp = (struct group_req *)i1;
6375 		if (greqp->gr_group.ss_family == AF_INET) {
6376 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6377 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6378 		} else {
6379 			if (!inet6)
6380 				return (EINVAL);	/* Not on INET socket */
6381 
6382 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6383 			v6group = sin6->sin6_addr;
6384 		}
6385 		ifaddr = INADDR_ANY;
6386 		ifindex = greqp->gr_interface;
6387 	} else if (inet6) {
6388 		v6_mreqp = (struct ipv6_mreq *)i1;
6389 		v6group = v6_mreqp->ipv6mr_multiaddr;
6390 		ifaddr = INADDR_ANY;
6391 		ifindex = v6_mreqp->ipv6mr_interface;
6392 	} else {
6393 		v4_mreqp = (struct ip_mreq *)i1;
6394 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6395 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6396 		ifindex = 0;
6397 	}
6398 
6399 	/*
6400 	 * In the multirouting case, we need to replicate
6401 	 * the request on all interfaces that will take part
6402 	 * in replication.  We do so because multirouting is
6403 	 * reflective, thus we will probably receive multi-
6404 	 * casts on those interfaces.
6405 	 * The ip_multirt_apply_membership() succeeds if
6406 	 * the operation succeeds on at least one interface.
6407 	 */
6408 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6409 		ipaddr_t group;
6410 
6411 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6412 
6413 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6414 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6415 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6416 	} else {
6417 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6418 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6419 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6420 	}
6421 	if (ire != NULL) {
6422 		if (ire->ire_flags & RTF_MULTIRT) {
6423 			error = ip_multirt_apply_membership(optfn, ire, connp,
6424 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6425 			done = B_TRUE;
6426 		}
6427 		ire_refrele(ire);
6428 	}
6429 
6430 	if (!done) {
6431 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6432 		    fmode, &ipv6_all_zeros);
6433 	}
6434 	return (error);
6435 }
6436 
6437 /*
6438  * Set socket options for joining and leaving multicast groups
6439  * for specific sources.
6440  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6441  * The caller has already check that the option name is consistent with
6442  * the address family of the socket.
6443  */
6444 int
6445 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6446     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6447 {
6448 	int		*i1 = (int *)invalp;
6449 	int		error = 0;
6450 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6451 	struct ip_mreq_source *imreqp;
6452 	struct group_source_req *gsreqp;
6453 	in6_addr_t v6group, v6src;
6454 	uint32_t ifindex;
6455 	ipaddr_t ifaddr;
6456 	boolean_t mcast_opt = B_TRUE;
6457 	mcast_record_t fmode;
6458 	ire_t *ire;
6459 	boolean_t done = B_FALSE;
6460 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6461 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6462 
6463 	switch (name) {
6464 	case IP_BLOCK_SOURCE:
6465 		mcast_opt = B_FALSE;
6466 		/* FALLTHROUGH */
6467 	case MCAST_BLOCK_SOURCE:
6468 		fmode = MODE_IS_EXCLUDE;
6469 		optfn = ip_opt_add_group;
6470 		break;
6471 
6472 	case IP_UNBLOCK_SOURCE:
6473 		mcast_opt = B_FALSE;
6474 		/* FALLTHROUGH */
6475 	case MCAST_UNBLOCK_SOURCE:
6476 		fmode = MODE_IS_EXCLUDE;
6477 		optfn = ip_opt_delete_group;
6478 		break;
6479 
6480 	case IP_ADD_SOURCE_MEMBERSHIP:
6481 		mcast_opt = B_FALSE;
6482 		/* FALLTHROUGH */
6483 	case MCAST_JOIN_SOURCE_GROUP:
6484 		fmode = MODE_IS_INCLUDE;
6485 		optfn = ip_opt_add_group;
6486 		break;
6487 
6488 	case IP_DROP_SOURCE_MEMBERSHIP:
6489 		mcast_opt = B_FALSE;
6490 		/* FALLTHROUGH */
6491 	case MCAST_LEAVE_SOURCE_GROUP:
6492 		fmode = MODE_IS_INCLUDE;
6493 		optfn = ip_opt_delete_group;
6494 		break;
6495 	default:
6496 		/* Should not be reached. */
6497 		optfn = NULL;
6498 		fmode = 0;
6499 		ASSERT(0);
6500 	}
6501 
6502 	if (mcast_opt) {
6503 		gsreqp = (struct group_source_req *)i1;
6504 		ifindex = gsreqp->gsr_interface;
6505 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6506 			struct sockaddr_in *s;
6507 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6508 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6509 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6510 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6511 		} else {
6512 			struct sockaddr_in6 *s6;
6513 
6514 			if (!inet6)
6515 				return (EINVAL);	/* Not on INET socket */
6516 
6517 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6518 			v6group = s6->sin6_addr;
6519 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6520 			v6src = s6->sin6_addr;
6521 		}
6522 		ifaddr = INADDR_ANY;
6523 	} else {
6524 		imreqp = (struct ip_mreq_source *)i1;
6525 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6526 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6527 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6528 		ifindex = 0;
6529 	}
6530 
6531 	/*
6532 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6533 	 */
6534 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6535 		v6src = ipv6_all_zeros;
6536 
6537 	/*
6538 	 * In the multirouting case, we need to replicate
6539 	 * the request as noted in the mcast cases above.
6540 	 */
6541 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6542 		ipaddr_t group;
6543 
6544 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6545 
6546 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6547 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6548 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6549 	} else {
6550 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6551 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6552 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6553 	}
6554 	if (ire != NULL) {
6555 		if (ire->ire_flags & RTF_MULTIRT) {
6556 			error = ip_multirt_apply_membership(optfn, ire, connp,
6557 			    checkonly, &v6group, fmode, &v6src);
6558 			done = B_TRUE;
6559 		}
6560 		ire_refrele(ire);
6561 	}
6562 	if (!done) {
6563 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6564 		    fmode, &v6src);
6565 	}
6566 	return (error);
6567 }
6568 
6569 /*
6570  * Given a destination address and a pointer to where to put the information
6571  * this routine fills in the mtuinfo.
6572  * The socket must be connected.
6573  * For sctp conn_faddr is the primary address.
6574  */
6575 int
6576 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6577 {
6578 	uint32_t	pmtu = IP_MAXPACKET;
6579 	uint_t		scopeid;
6580 
6581 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6582 		return (-1);
6583 
6584 	/* In case we never sent or called ip_set_destination_v4/v6 */
6585 	if (ixa->ixa_ire != NULL)
6586 		pmtu = ip_get_pmtu(ixa);
6587 
6588 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6589 		scopeid = ixa->ixa_scopeid;
6590 	else
6591 		scopeid = 0;
6592 
6593 	bzero(mtuinfo, sizeof (*mtuinfo));
6594 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6595 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6596 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6597 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6598 	mtuinfo->ip6m_mtu = pmtu;
6599 
6600 	return (sizeof (struct ip6_mtuinfo));
6601 }
6602 
6603 /*
6604  * When the src multihoming is changed from weak to [strong, preferred]
6605  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6606  * and identify routes that were created by user-applications in the
6607  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6608  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6609  * is selected by finding an interface route for the gateway.
6610  */
6611 /* ARGSUSED */
6612 void
6613 ip_ire_rebind_walker(ire_t *ire, void *notused)
6614 {
6615 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6616 		return;
6617 	ire_rebind(ire);
6618 	ire_delete(ire);
6619 }
6620 
6621 /*
6622  * When the src multihoming is changed from  [strong, preferred] to weak,
6623  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6624  * set any entries that were created by user-applications in the unbound state
6625  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6626  */
6627 /* ARGSUSED */
6628 void
6629 ip_ire_unbind_walker(ire_t *ire, void *notused)
6630 {
6631 	ire_t *new_ire;
6632 
6633 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6634 		return;
6635 	if (ire->ire_ipversion == IPV6_VERSION) {
6636 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6637 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6638 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6639 	} else {
6640 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6641 		    (uchar_t *)&ire->ire_mask,
6642 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6643 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6644 	}
6645 	if (new_ire == NULL)
6646 		return;
6647 	new_ire->ire_unbound = B_TRUE;
6648 	/*
6649 	 * The bound ire must first be deleted so that we don't return
6650 	 * the existing one on the attempt to add the unbound new_ire.
6651 	 */
6652 	ire_delete(ire);
6653 	new_ire = ire_add(new_ire);
6654 	if (new_ire != NULL)
6655 		ire_refrele(new_ire);
6656 }
6657 
6658 /*
6659  * When the settings of ip*_strict_src_multihoming tunables are changed,
6660  * all cached routes need to be recomputed. This recomputation needs to be
6661  * done when going from weaker to stronger modes so that the cached ire
6662  * for the connection does not violate the current ip*_strict_src_multihoming
6663  * setting. It also needs to be done when going from stronger to weaker modes,
6664  * so that we fall back to matching on the longest-matching-route (as opposed
6665  * to a shorter match that may have been selected in the strong mode
6666  * to satisfy src_multihoming settings).
6667  *
6668  * The cached ixa_ire entires for all conn_t entries are marked as
6669  * "verify" so that they will be recomputed for the next packet.
6670  */
6671 void
6672 conn_ire_revalidate(conn_t *connp, void *arg)
6673 {
6674 	boolean_t isv6 = (boolean_t)arg;
6675 
6676 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6677 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6678 		return;
6679 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6680 }
6681 
6682 /*
6683  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6684  * When an ipf is passed here for the first time, if
6685  * we already have in-order fragments on the queue, we convert from the fast-
6686  * path reassembly scheme to the hard-case scheme.  From then on, additional
6687  * fragments are reassembled here.  We keep track of the start and end offsets
6688  * of each piece, and the number of holes in the chain.  When the hole count
6689  * goes to zero, we are done!
6690  *
6691  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6692  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6693  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6694  * after the call to ip_reassemble().
6695  */
6696 int
6697 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6698     size_t msg_len)
6699 {
6700 	uint_t	end;
6701 	mblk_t	*next_mp;
6702 	mblk_t	*mp1;
6703 	uint_t	offset;
6704 	boolean_t incr_dups = B_TRUE;
6705 	boolean_t offset_zero_seen = B_FALSE;
6706 	boolean_t pkt_boundary_checked = B_FALSE;
6707 
6708 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6709 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6710 
6711 	/* Add in byte count */
6712 	ipf->ipf_count += msg_len;
6713 	if (ipf->ipf_end) {
6714 		/*
6715 		 * We were part way through in-order reassembly, but now there
6716 		 * is a hole.  We walk through messages already queued, and
6717 		 * mark them for hard case reassembly.  We know that up till
6718 		 * now they were in order starting from offset zero.
6719 		 */
6720 		offset = 0;
6721 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6722 			IP_REASS_SET_START(mp1, offset);
6723 			if (offset == 0) {
6724 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6725 				offset = -ipf->ipf_nf_hdr_len;
6726 			}
6727 			offset += mp1->b_wptr - mp1->b_rptr;
6728 			IP_REASS_SET_END(mp1, offset);
6729 		}
6730 		/* One hole at the end. */
6731 		ipf->ipf_hole_cnt = 1;
6732 		/* Brand it as a hard case, forever. */
6733 		ipf->ipf_end = 0;
6734 	}
6735 	/* Walk through all the new pieces. */
6736 	do {
6737 		end = start + (mp->b_wptr - mp->b_rptr);
6738 		/*
6739 		 * If start is 0, decrease 'end' only for the first mblk of
6740 		 * the fragment. Otherwise 'end' can get wrong value in the
6741 		 * second pass of the loop if first mblk is exactly the
6742 		 * size of ipf_nf_hdr_len.
6743 		 */
6744 		if (start == 0 && !offset_zero_seen) {
6745 			/* First segment */
6746 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6747 			end -= ipf->ipf_nf_hdr_len;
6748 			offset_zero_seen = B_TRUE;
6749 		}
6750 		next_mp = mp->b_cont;
6751 		/*
6752 		 * We are checking to see if there is any interesing data
6753 		 * to process.  If there isn't and the mblk isn't the
6754 		 * one which carries the unfragmentable header then we
6755 		 * drop it.  It's possible to have just the unfragmentable
6756 		 * header come through without any data.  That needs to be
6757 		 * saved.
6758 		 *
6759 		 * If the assert at the top of this function holds then the
6760 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6761 		 * is infrequently traveled enough that the test is left in
6762 		 * to protect against future code changes which break that
6763 		 * invariant.
6764 		 */
6765 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6766 			/* Empty.  Blast it. */
6767 			IP_REASS_SET_START(mp, 0);
6768 			IP_REASS_SET_END(mp, 0);
6769 			/*
6770 			 * If the ipf points to the mblk we are about to free,
6771 			 * update ipf to point to the next mblk (or NULL
6772 			 * if none).
6773 			 */
6774 			if (ipf->ipf_mp->b_cont == mp)
6775 				ipf->ipf_mp->b_cont = next_mp;
6776 			freeb(mp);
6777 			continue;
6778 		}
6779 		mp->b_cont = NULL;
6780 		IP_REASS_SET_START(mp, start);
6781 		IP_REASS_SET_END(mp, end);
6782 		if (!ipf->ipf_tail_mp) {
6783 			ipf->ipf_tail_mp = mp;
6784 			ipf->ipf_mp->b_cont = mp;
6785 			if (start == 0 || !more) {
6786 				ipf->ipf_hole_cnt = 1;
6787 				/*
6788 				 * if the first fragment comes in more than one
6789 				 * mblk, this loop will be executed for each
6790 				 * mblk. Need to adjust hole count so exiting
6791 				 * this routine will leave hole count at 1.
6792 				 */
6793 				if (next_mp)
6794 					ipf->ipf_hole_cnt++;
6795 			} else
6796 				ipf->ipf_hole_cnt = 2;
6797 			continue;
6798 		} else if (ipf->ipf_last_frag_seen && !more &&
6799 		    !pkt_boundary_checked) {
6800 			/*
6801 			 * We check datagram boundary only if this fragment
6802 			 * claims to be the last fragment and we have seen a
6803 			 * last fragment in the past too. We do this only
6804 			 * once for a given fragment.
6805 			 *
6806 			 * start cannot be 0 here as fragments with start=0
6807 			 * and MF=0 gets handled as a complete packet. These
6808 			 * fragments should not reach here.
6809 			 */
6810 
6811 			if (start + msgdsize(mp) !=
6812 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6813 				/*
6814 				 * We have two fragments both of which claim
6815 				 * to be the last fragment but gives conflicting
6816 				 * information about the whole datagram size.
6817 				 * Something fishy is going on. Drop the
6818 				 * fragment and free up the reassembly list.
6819 				 */
6820 				return (IP_REASS_FAILED);
6821 			}
6822 
6823 			/*
6824 			 * We shouldn't come to this code block again for this
6825 			 * particular fragment.
6826 			 */
6827 			pkt_boundary_checked = B_TRUE;
6828 		}
6829 
6830 		/* New stuff at or beyond tail? */
6831 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6832 		if (start >= offset) {
6833 			if (ipf->ipf_last_frag_seen) {
6834 				/* current fragment is beyond last fragment */
6835 				return (IP_REASS_FAILED);
6836 			}
6837 			/* Link it on end. */
6838 			ipf->ipf_tail_mp->b_cont = mp;
6839 			ipf->ipf_tail_mp = mp;
6840 			if (more) {
6841 				if (start != offset)
6842 					ipf->ipf_hole_cnt++;
6843 			} else if (start == offset && next_mp == NULL)
6844 					ipf->ipf_hole_cnt--;
6845 			continue;
6846 		}
6847 		mp1 = ipf->ipf_mp->b_cont;
6848 		offset = IP_REASS_START(mp1);
6849 		/* New stuff at the front? */
6850 		if (start < offset) {
6851 			if (start == 0) {
6852 				if (end >= offset) {
6853 					/* Nailed the hole at the begining. */
6854 					ipf->ipf_hole_cnt--;
6855 				}
6856 			} else if (end < offset) {
6857 				/*
6858 				 * A hole, stuff, and a hole where there used
6859 				 * to be just a hole.
6860 				 */
6861 				ipf->ipf_hole_cnt++;
6862 			}
6863 			mp->b_cont = mp1;
6864 			/* Check for overlap. */
6865 			while (end > offset) {
6866 				if (end < IP_REASS_END(mp1)) {
6867 					mp->b_wptr -= end - offset;
6868 					IP_REASS_SET_END(mp, offset);
6869 					BUMP_MIB(ill->ill_ip_mib,
6870 					    ipIfStatsReasmPartDups);
6871 					break;
6872 				}
6873 				/* Did we cover another hole? */
6874 				if ((mp1->b_cont &&
6875 				    IP_REASS_END(mp1) !=
6876 				    IP_REASS_START(mp1->b_cont) &&
6877 				    end >= IP_REASS_START(mp1->b_cont)) ||
6878 				    (!ipf->ipf_last_frag_seen && !more)) {
6879 					ipf->ipf_hole_cnt--;
6880 				}
6881 				/* Clip out mp1. */
6882 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6883 					/*
6884 					 * After clipping out mp1, this guy
6885 					 * is now hanging off the end.
6886 					 */
6887 					ipf->ipf_tail_mp = mp;
6888 				}
6889 				IP_REASS_SET_START(mp1, 0);
6890 				IP_REASS_SET_END(mp1, 0);
6891 				/* Subtract byte count */
6892 				ipf->ipf_count -= mp1->b_datap->db_lim -
6893 				    mp1->b_datap->db_base;
6894 				freeb(mp1);
6895 				BUMP_MIB(ill->ill_ip_mib,
6896 				    ipIfStatsReasmPartDups);
6897 				mp1 = mp->b_cont;
6898 				if (!mp1)
6899 					break;
6900 				offset = IP_REASS_START(mp1);
6901 			}
6902 			ipf->ipf_mp->b_cont = mp;
6903 			continue;
6904 		}
6905 		/*
6906 		 * The new piece starts somewhere between the start of the head
6907 		 * and before the end of the tail.
6908 		 */
6909 		for (; mp1; mp1 = mp1->b_cont) {
6910 			offset = IP_REASS_END(mp1);
6911 			if (start < offset) {
6912 				if (end <= offset) {
6913 					/* Nothing new. */
6914 					IP_REASS_SET_START(mp, 0);
6915 					IP_REASS_SET_END(mp, 0);
6916 					/* Subtract byte count */
6917 					ipf->ipf_count -= mp->b_datap->db_lim -
6918 					    mp->b_datap->db_base;
6919 					if (incr_dups) {
6920 						ipf->ipf_num_dups++;
6921 						incr_dups = B_FALSE;
6922 					}
6923 					freeb(mp);
6924 					BUMP_MIB(ill->ill_ip_mib,
6925 					    ipIfStatsReasmDuplicates);
6926 					break;
6927 				}
6928 				/*
6929 				 * Trim redundant stuff off beginning of new
6930 				 * piece.
6931 				 */
6932 				IP_REASS_SET_START(mp, offset);
6933 				mp->b_rptr += offset - start;
6934 				BUMP_MIB(ill->ill_ip_mib,
6935 				    ipIfStatsReasmPartDups);
6936 				start = offset;
6937 				if (!mp1->b_cont) {
6938 					/*
6939 					 * After trimming, this guy is now
6940 					 * hanging off the end.
6941 					 */
6942 					mp1->b_cont = mp;
6943 					ipf->ipf_tail_mp = mp;
6944 					if (!more) {
6945 						ipf->ipf_hole_cnt--;
6946 					}
6947 					break;
6948 				}
6949 			}
6950 			if (start >= IP_REASS_START(mp1->b_cont))
6951 				continue;
6952 			/* Fill a hole */
6953 			if (start > offset)
6954 				ipf->ipf_hole_cnt++;
6955 			mp->b_cont = mp1->b_cont;
6956 			mp1->b_cont = mp;
6957 			mp1 = mp->b_cont;
6958 			offset = IP_REASS_START(mp1);
6959 			if (end >= offset) {
6960 				ipf->ipf_hole_cnt--;
6961 				/* Check for overlap. */
6962 				while (end > offset) {
6963 					if (end < IP_REASS_END(mp1)) {
6964 						mp->b_wptr -= end - offset;
6965 						IP_REASS_SET_END(mp, offset);
6966 						/*
6967 						 * TODO we might bump
6968 						 * this up twice if there is
6969 						 * overlap at both ends.
6970 						 */
6971 						BUMP_MIB(ill->ill_ip_mib,
6972 						    ipIfStatsReasmPartDups);
6973 						break;
6974 					}
6975 					/* Did we cover another hole? */
6976 					if ((mp1->b_cont &&
6977 					    IP_REASS_END(mp1)
6978 					    != IP_REASS_START(mp1->b_cont) &&
6979 					    end >=
6980 					    IP_REASS_START(mp1->b_cont)) ||
6981 					    (!ipf->ipf_last_frag_seen &&
6982 					    !more)) {
6983 						ipf->ipf_hole_cnt--;
6984 					}
6985 					/* Clip out mp1. */
6986 					if ((mp->b_cont = mp1->b_cont) ==
6987 					    NULL) {
6988 						/*
6989 						 * After clipping out mp1,
6990 						 * this guy is now hanging
6991 						 * off the end.
6992 						 */
6993 						ipf->ipf_tail_mp = mp;
6994 					}
6995 					IP_REASS_SET_START(mp1, 0);
6996 					IP_REASS_SET_END(mp1, 0);
6997 					/* Subtract byte count */
6998 					ipf->ipf_count -=
6999 					    mp1->b_datap->db_lim -
7000 					    mp1->b_datap->db_base;
7001 					freeb(mp1);
7002 					BUMP_MIB(ill->ill_ip_mib,
7003 					    ipIfStatsReasmPartDups);
7004 					mp1 = mp->b_cont;
7005 					if (!mp1)
7006 						break;
7007 					offset = IP_REASS_START(mp1);
7008 				}
7009 			}
7010 			break;
7011 		}
7012 	} while (start = end, mp = next_mp);
7013 
7014 	/* Fragment just processed could be the last one. Remember this fact */
7015 	if (!more)
7016 		ipf->ipf_last_frag_seen = B_TRUE;
7017 
7018 	/* Still got holes? */
7019 	if (ipf->ipf_hole_cnt)
7020 		return (IP_REASS_PARTIAL);
7021 	/* Clean up overloaded fields to avoid upstream disasters. */
7022 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
7023 		IP_REASS_SET_START(mp1, 0);
7024 		IP_REASS_SET_END(mp1, 0);
7025 	}
7026 	return (IP_REASS_COMPLETE);
7027 }
7028 
7029 /*
7030  * Fragmentation reassembly.  Each ILL has a hash table for
7031  * queuing packets undergoing reassembly for all IPIFs
7032  * associated with the ILL.  The hash is based on the packet
7033  * IP ident field.  The ILL frag hash table was allocated
7034  * as a timer block at the time the ILL was created.  Whenever
7035  * there is anything on the reassembly queue, the timer will
7036  * be running.  Returns the reassembled packet if reassembly completes.
7037  */
7038 mblk_t *
7039 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
7040 {
7041 	uint32_t	frag_offset_flags;
7042 	mblk_t		*t_mp;
7043 	ipaddr_t	dst;
7044 	uint8_t		proto = ipha->ipha_protocol;
7045 	uint32_t	sum_val;
7046 	uint16_t	sum_flags;
7047 	ipf_t		*ipf;
7048 	ipf_t		**ipfp;
7049 	ipfb_t		*ipfb;
7050 	uint16_t	ident;
7051 	uint32_t	offset;
7052 	ipaddr_t	src;
7053 	uint_t		hdr_length;
7054 	uint32_t	end;
7055 	mblk_t		*mp1;
7056 	mblk_t		*tail_mp;
7057 	size_t		count;
7058 	size_t		msg_len;
7059 	uint8_t		ecn_info = 0;
7060 	uint32_t	packet_size;
7061 	boolean_t	pruned = B_FALSE;
7062 	ill_t		*ill = ira->ira_ill;
7063 	ip_stack_t	*ipst = ill->ill_ipst;
7064 
7065 	/*
7066 	 * Drop the fragmented as early as possible, if
7067 	 * we don't have resource(s) to re-assemble.
7068 	 */
7069 	if (ipst->ips_ip_reass_queue_bytes == 0) {
7070 		freemsg(mp);
7071 		return (NULL);
7072 	}
7073 
7074 	/* Check for fragmentation offset; return if there's none */
7075 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7076 	    (IPH_MF | IPH_OFFSET)) == 0)
7077 		return (mp);
7078 
7079 	/*
7080 	 * We utilize hardware computed checksum info only for UDP since
7081 	 * IP fragmentation is a normal occurrence for the protocol.  In
7082 	 * addition, checksum offload support for IP fragments carrying
7083 	 * UDP payload is commonly implemented across network adapters.
7084 	 */
7085 	ASSERT(ira->ira_rill != NULL);
7086 	if (proto == IPPROTO_UDP && dohwcksum &&
7087 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7088 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7089 		mblk_t *mp1 = mp->b_cont;
7090 		int32_t len;
7091 
7092 		/* Record checksum information from the packet */
7093 		sum_val = (uint32_t)DB_CKSUM16(mp);
7094 		sum_flags = DB_CKSUMFLAGS(mp);
7095 
7096 		/* IP payload offset from beginning of mblk */
7097 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7098 
7099 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7100 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7101 		    offset >= DB_CKSUMSTART(mp) &&
7102 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7103 			uint32_t adj;
7104 			/*
7105 			 * Partial checksum has been calculated by hardware
7106 			 * and attached to the packet; in addition, any
7107 			 * prepended extraneous data is even byte aligned.
7108 			 * If any such data exists, we adjust the checksum;
7109 			 * this would also handle any postpended data.
7110 			 */
7111 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7112 			    mp, mp1, len, adj);
7113 
7114 			/* One's complement subtract extraneous checksum */
7115 			if (adj >= sum_val)
7116 				sum_val = ~(adj - sum_val) & 0xFFFF;
7117 			else
7118 				sum_val -= adj;
7119 		}
7120 	} else {
7121 		sum_val = 0;
7122 		sum_flags = 0;
7123 	}
7124 
7125 	/* Clear hardware checksumming flag */
7126 	DB_CKSUMFLAGS(mp) = 0;
7127 
7128 	ident = ipha->ipha_ident;
7129 	offset = (frag_offset_flags << 3) & 0xFFFF;
7130 	src = ipha->ipha_src;
7131 	dst = ipha->ipha_dst;
7132 	hdr_length = IPH_HDR_LENGTH(ipha);
7133 	end = ntohs(ipha->ipha_length) - hdr_length;
7134 
7135 	/* If end == 0 then we have a packet with no data, so just free it */
7136 	if (end == 0) {
7137 		freemsg(mp);
7138 		return (NULL);
7139 	}
7140 
7141 	/* Record the ECN field info. */
7142 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7143 	if (offset != 0) {
7144 		/*
7145 		 * If this isn't the first piece, strip the header, and
7146 		 * add the offset to the end value.
7147 		 */
7148 		mp->b_rptr += hdr_length;
7149 		end += offset;
7150 	}
7151 
7152 	/* Handle vnic loopback of fragments */
7153 	if (mp->b_datap->db_ref > 2)
7154 		msg_len = 0;
7155 	else
7156 		msg_len = MBLKSIZE(mp);
7157 
7158 	tail_mp = mp;
7159 	while (tail_mp->b_cont != NULL) {
7160 		tail_mp = tail_mp->b_cont;
7161 		if (tail_mp->b_datap->db_ref <= 2)
7162 			msg_len += MBLKSIZE(tail_mp);
7163 	}
7164 
7165 	/* If the reassembly list for this ILL will get too big, prune it */
7166 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7167 	    ipst->ips_ip_reass_queue_bytes) {
7168 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7169 		    uint_t, ill->ill_frag_count,
7170 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7171 		ill_frag_prune(ill,
7172 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7173 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7174 		pruned = B_TRUE;
7175 	}
7176 
7177 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7178 	mutex_enter(&ipfb->ipfb_lock);
7179 
7180 	ipfp = &ipfb->ipfb_ipf;
7181 	/* Try to find an existing fragment queue for this packet. */
7182 	for (;;) {
7183 		ipf = ipfp[0];
7184 		if (ipf != NULL) {
7185 			/*
7186 			 * It has to match on ident and src/dst address.
7187 			 */
7188 			if (ipf->ipf_ident == ident &&
7189 			    ipf->ipf_src == src &&
7190 			    ipf->ipf_dst == dst &&
7191 			    ipf->ipf_protocol == proto) {
7192 				/*
7193 				 * If we have received too many
7194 				 * duplicate fragments for this packet
7195 				 * free it.
7196 				 */
7197 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7198 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7199 					freemsg(mp);
7200 					mutex_exit(&ipfb->ipfb_lock);
7201 					return (NULL);
7202 				}
7203 				/* Found it. */
7204 				break;
7205 			}
7206 			ipfp = &ipf->ipf_hash_next;
7207 			continue;
7208 		}
7209 
7210 		/*
7211 		 * If we pruned the list, do we want to store this new
7212 		 * fragment?. We apply an optimization here based on the
7213 		 * fact that most fragments will be received in order.
7214 		 * So if the offset of this incoming fragment is zero,
7215 		 * it is the first fragment of a new packet. We will
7216 		 * keep it.  Otherwise drop the fragment, as we have
7217 		 * probably pruned the packet already (since the
7218 		 * packet cannot be found).
7219 		 */
7220 		if (pruned && offset != 0) {
7221 			mutex_exit(&ipfb->ipfb_lock);
7222 			freemsg(mp);
7223 			return (NULL);
7224 		}
7225 
7226 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7227 			/*
7228 			 * Too many fragmented packets in this hash
7229 			 * bucket. Free the oldest.
7230 			 */
7231 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7232 		}
7233 
7234 		/* New guy.  Allocate a frag message. */
7235 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7236 		if (mp1 == NULL) {
7237 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7238 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7239 			freemsg(mp);
7240 reass_done:
7241 			mutex_exit(&ipfb->ipfb_lock);
7242 			return (NULL);
7243 		}
7244 
7245 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7246 		mp1->b_cont = mp;
7247 
7248 		/* Initialize the fragment header. */
7249 		ipf = (ipf_t *)mp1->b_rptr;
7250 		ipf->ipf_mp = mp1;
7251 		ipf->ipf_ptphn = ipfp;
7252 		ipfp[0] = ipf;
7253 		ipf->ipf_hash_next = NULL;
7254 		ipf->ipf_ident = ident;
7255 		ipf->ipf_protocol = proto;
7256 		ipf->ipf_src = src;
7257 		ipf->ipf_dst = dst;
7258 		ipf->ipf_nf_hdr_len = 0;
7259 		/* Record reassembly start time. */
7260 		ipf->ipf_timestamp = gethrestime_sec();
7261 		/* Record ipf generation and account for frag header */
7262 		ipf->ipf_gen = ill->ill_ipf_gen++;
7263 		ipf->ipf_count = MBLKSIZE(mp1);
7264 		ipf->ipf_last_frag_seen = B_FALSE;
7265 		ipf->ipf_ecn = ecn_info;
7266 		ipf->ipf_num_dups = 0;
7267 		ipfb->ipfb_frag_pkts++;
7268 		ipf->ipf_checksum = 0;
7269 		ipf->ipf_checksum_flags = 0;
7270 
7271 		/* Store checksum value in fragment header */
7272 		if (sum_flags != 0) {
7273 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7274 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7275 			ipf->ipf_checksum = sum_val;
7276 			ipf->ipf_checksum_flags = sum_flags;
7277 		}
7278 
7279 		/*
7280 		 * We handle reassembly two ways.  In the easy case,
7281 		 * where all the fragments show up in order, we do
7282 		 * minimal bookkeeping, and just clip new pieces on
7283 		 * the end.  If we ever see a hole, then we go off
7284 		 * to ip_reassemble which has to mark the pieces and
7285 		 * keep track of the number of holes, etc.  Obviously,
7286 		 * the point of having both mechanisms is so we can
7287 		 * handle the easy case as efficiently as possible.
7288 		 */
7289 		if (offset == 0) {
7290 			/* Easy case, in-order reassembly so far. */
7291 			ipf->ipf_count += msg_len;
7292 			ipf->ipf_tail_mp = tail_mp;
7293 			/*
7294 			 * Keep track of next expected offset in
7295 			 * ipf_end.
7296 			 */
7297 			ipf->ipf_end = end;
7298 			ipf->ipf_nf_hdr_len = hdr_length;
7299 		} else {
7300 			/* Hard case, hole at the beginning. */
7301 			ipf->ipf_tail_mp = NULL;
7302 			/*
7303 			 * ipf_end == 0 means that we have given up
7304 			 * on easy reassembly.
7305 			 */
7306 			ipf->ipf_end = 0;
7307 
7308 			/* Forget checksum offload from now on */
7309 			ipf->ipf_checksum_flags = 0;
7310 
7311 			/*
7312 			 * ipf_hole_cnt is set by ip_reassemble.
7313 			 * ipf_count is updated by ip_reassemble.
7314 			 * No need to check for return value here
7315 			 * as we don't expect reassembly to complete
7316 			 * or fail for the first fragment itself.
7317 			 */
7318 			(void) ip_reassemble(mp, ipf,
7319 			    (frag_offset_flags & IPH_OFFSET) << 3,
7320 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7321 		}
7322 		/* Update per ipfb and ill byte counts */
7323 		ipfb->ipfb_count += ipf->ipf_count;
7324 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7325 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7326 		/* If the frag timer wasn't already going, start it. */
7327 		mutex_enter(&ill->ill_lock);
7328 		ill_frag_timer_start(ill);
7329 		mutex_exit(&ill->ill_lock);
7330 		goto reass_done;
7331 	}
7332 
7333 	/*
7334 	 * If the packet's flag has changed (it could be coming up
7335 	 * from an interface different than the previous, therefore
7336 	 * possibly different checksum capability), then forget about
7337 	 * any stored checksum states.  Otherwise add the value to
7338 	 * the existing one stored in the fragment header.
7339 	 */
7340 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7341 		sum_val += ipf->ipf_checksum;
7342 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7343 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7344 		ipf->ipf_checksum = sum_val;
7345 	} else if (ipf->ipf_checksum_flags != 0) {
7346 		/* Forget checksum offload from now on */
7347 		ipf->ipf_checksum_flags = 0;
7348 	}
7349 
7350 	/*
7351 	 * We have a new piece of a datagram which is already being
7352 	 * reassembled.  Update the ECN info if all IP fragments
7353 	 * are ECN capable.  If there is one which is not, clear
7354 	 * all the info.  If there is at least one which has CE
7355 	 * code point, IP needs to report that up to transport.
7356 	 */
7357 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7358 		if (ecn_info == IPH_ECN_CE)
7359 			ipf->ipf_ecn = IPH_ECN_CE;
7360 	} else {
7361 		ipf->ipf_ecn = IPH_ECN_NECT;
7362 	}
7363 	if (offset && ipf->ipf_end == offset) {
7364 		/* The new fragment fits at the end */
7365 		ipf->ipf_tail_mp->b_cont = mp;
7366 		/* Update the byte count */
7367 		ipf->ipf_count += msg_len;
7368 		/* Update per ipfb and ill byte counts */
7369 		ipfb->ipfb_count += msg_len;
7370 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7371 		atomic_add_32(&ill->ill_frag_count, msg_len);
7372 		if (frag_offset_flags & IPH_MF) {
7373 			/* More to come. */
7374 			ipf->ipf_end = end;
7375 			ipf->ipf_tail_mp = tail_mp;
7376 			goto reass_done;
7377 		}
7378 	} else {
7379 		/* Go do the hard cases. */
7380 		int ret;
7381 
7382 		if (offset == 0)
7383 			ipf->ipf_nf_hdr_len = hdr_length;
7384 
7385 		/* Save current byte count */
7386 		count = ipf->ipf_count;
7387 		ret = ip_reassemble(mp, ipf,
7388 		    (frag_offset_flags & IPH_OFFSET) << 3,
7389 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7390 		/* Count of bytes added and subtracted (freeb()ed) */
7391 		count = ipf->ipf_count - count;
7392 		if (count) {
7393 			/* Update per ipfb and ill byte counts */
7394 			ipfb->ipfb_count += count;
7395 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7396 			atomic_add_32(&ill->ill_frag_count, count);
7397 		}
7398 		if (ret == IP_REASS_PARTIAL) {
7399 			goto reass_done;
7400 		} else if (ret == IP_REASS_FAILED) {
7401 			/* Reassembly failed. Free up all resources */
7402 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7403 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7404 				IP_REASS_SET_START(t_mp, 0);
7405 				IP_REASS_SET_END(t_mp, 0);
7406 			}
7407 			freemsg(mp);
7408 			goto reass_done;
7409 		}
7410 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7411 	}
7412 	/*
7413 	 * We have completed reassembly.  Unhook the frag header from
7414 	 * the reassembly list.
7415 	 *
7416 	 * Before we free the frag header, record the ECN info
7417 	 * to report back to the transport.
7418 	 */
7419 	ecn_info = ipf->ipf_ecn;
7420 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7421 	ipfp = ipf->ipf_ptphn;
7422 
7423 	/* We need to supply these to caller */
7424 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7425 		sum_val = ipf->ipf_checksum;
7426 	else
7427 		sum_val = 0;
7428 
7429 	mp1 = ipf->ipf_mp;
7430 	count = ipf->ipf_count;
7431 	ipf = ipf->ipf_hash_next;
7432 	if (ipf != NULL)
7433 		ipf->ipf_ptphn = ipfp;
7434 	ipfp[0] = ipf;
7435 	atomic_add_32(&ill->ill_frag_count, -count);
7436 	ASSERT(ipfb->ipfb_count >= count);
7437 	ipfb->ipfb_count -= count;
7438 	ipfb->ipfb_frag_pkts--;
7439 	mutex_exit(&ipfb->ipfb_lock);
7440 	/* Ditch the frag header. */
7441 	mp = mp1->b_cont;
7442 
7443 	freeb(mp1);
7444 
7445 	/* Restore original IP length in header. */
7446 	packet_size = (uint32_t)msgdsize(mp);
7447 	if (packet_size > IP_MAXPACKET) {
7448 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7449 		ip_drop_input("Reassembled packet too large", mp, ill);
7450 		freemsg(mp);
7451 		return (NULL);
7452 	}
7453 
7454 	if (DB_REF(mp) > 1) {
7455 		mblk_t *mp2 = copymsg(mp);
7456 
7457 		if (mp2 == NULL) {
7458 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7459 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7460 			freemsg(mp);
7461 			return (NULL);
7462 		}
7463 		freemsg(mp);
7464 		mp = mp2;
7465 	}
7466 	ipha = (ipha_t *)mp->b_rptr;
7467 
7468 	ipha->ipha_length = htons((uint16_t)packet_size);
7469 	/* We're now complete, zip the frag state */
7470 	ipha->ipha_fragment_offset_and_flags = 0;
7471 	/* Record the ECN info. */
7472 	ipha->ipha_type_of_service &= 0xFC;
7473 	ipha->ipha_type_of_service |= ecn_info;
7474 
7475 	/* Update the receive attributes */
7476 	ira->ira_pktlen = packet_size;
7477 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7478 
7479 	/* Reassembly is successful; set checksum information in packet */
7480 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7481 	DB_CKSUMFLAGS(mp) = sum_flags;
7482 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7483 
7484 	return (mp);
7485 }
7486 
7487 /*
7488  * Pullup function that should be used for IP input in order to
7489  * ensure we do not loose the L2 source address; we need the l2 source
7490  * address for IP_RECVSLLA and for ndp_input.
7491  *
7492  * We return either NULL or b_rptr.
7493  */
7494 void *
7495 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7496 {
7497 	ill_t		*ill = ira->ira_ill;
7498 
7499 	if (ip_rput_pullups++ == 0) {
7500 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7501 		    "ip_pullup: %s forced us to "
7502 		    " pullup pkt, hdr len %ld, hdr addr %p",
7503 		    ill->ill_name, len, (void *)mp->b_rptr);
7504 	}
7505 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7506 		ip_setl2src(mp, ira, ira->ira_rill);
7507 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7508 	if (!pullupmsg(mp, len))
7509 		return (NULL);
7510 	else
7511 		return (mp->b_rptr);
7512 }
7513 
7514 /*
7515  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7516  * When called from the ULP ira_rill will be NULL hence the caller has to
7517  * pass in the ill.
7518  */
7519 /* ARGSUSED */
7520 void
7521 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7522 {
7523 	const uchar_t *addr;
7524 	int alen;
7525 
7526 	if (ira->ira_flags & IRAF_L2SRC_SET)
7527 		return;
7528 
7529 	ASSERT(ill != NULL);
7530 	alen = ill->ill_phys_addr_length;
7531 	ASSERT(alen <= sizeof (ira->ira_l2src));
7532 	if (ira->ira_mhip != NULL &&
7533 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7534 		bcopy(addr, ira->ira_l2src, alen);
7535 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7536 	    (addr = ill->ill_phys_addr) != NULL) {
7537 		bcopy(addr, ira->ira_l2src, alen);
7538 	} else {
7539 		bzero(ira->ira_l2src, alen);
7540 	}
7541 	ira->ira_flags |= IRAF_L2SRC_SET;
7542 }
7543 
7544 /*
7545  * check ip header length and align it.
7546  */
7547 mblk_t *
7548 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7549 {
7550 	ill_t	*ill = ira->ira_ill;
7551 	ssize_t len;
7552 
7553 	len = MBLKL(mp);
7554 
7555 	if (!OK_32PTR(mp->b_rptr))
7556 		IP_STAT(ill->ill_ipst, ip_notaligned);
7557 	else
7558 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7559 
7560 	/* Guard against bogus device drivers */
7561 	if (len < 0) {
7562 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7563 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7564 		freemsg(mp);
7565 		return (NULL);
7566 	}
7567 
7568 	if (len == 0) {
7569 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7570 		mblk_t *mp1 = mp->b_cont;
7571 
7572 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7573 			ip_setl2src(mp, ira, ira->ira_rill);
7574 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7575 
7576 		freeb(mp);
7577 		mp = mp1;
7578 		if (mp == NULL)
7579 			return (NULL);
7580 
7581 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7582 			return (mp);
7583 	}
7584 	if (ip_pullup(mp, min_size, ira) == NULL) {
7585 		if (msgdsize(mp) < min_size) {
7586 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7587 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7588 		} else {
7589 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7590 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7591 		}
7592 		freemsg(mp);
7593 		return (NULL);
7594 	}
7595 	return (mp);
7596 }
7597 
7598 /*
7599  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7600  */
7601 mblk_t *
7602 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7603     uint_t min_size, ip_recv_attr_t *ira)
7604 {
7605 	ill_t	*ill = ira->ira_ill;
7606 
7607 	/*
7608 	 * Make sure we have data length consistent
7609 	 * with the IP header.
7610 	 */
7611 	if (mp->b_cont == NULL) {
7612 		/* pkt_len is based on ipha_len, not the mblk length */
7613 		if (pkt_len < min_size) {
7614 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7615 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7616 			freemsg(mp);
7617 			return (NULL);
7618 		}
7619 		if (len < 0) {
7620 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7621 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7622 			freemsg(mp);
7623 			return (NULL);
7624 		}
7625 		/* Drop any pad */
7626 		mp->b_wptr = rptr + pkt_len;
7627 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7628 		ASSERT(pkt_len >= min_size);
7629 		if (pkt_len < min_size) {
7630 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7631 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7632 			freemsg(mp);
7633 			return (NULL);
7634 		}
7635 		if (len < 0) {
7636 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7637 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7638 			freemsg(mp);
7639 			return (NULL);
7640 		}
7641 		/* Drop any pad */
7642 		(void) adjmsg(mp, -len);
7643 		/*
7644 		 * adjmsg may have freed an mblk from the chain, hence
7645 		 * invalidate any hw checksum here. This will force IP to
7646 		 * calculate the checksum in sw, but only for this packet.
7647 		 */
7648 		DB_CKSUMFLAGS(mp) = 0;
7649 		IP_STAT(ill->ill_ipst, ip_multimblk);
7650 	}
7651 	return (mp);
7652 }
7653 
7654 /*
7655  * Check that the IPv4 opt_len is consistent with the packet and pullup
7656  * the options.
7657  */
7658 mblk_t *
7659 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7660     ip_recv_attr_t *ira)
7661 {
7662 	ill_t	*ill = ira->ira_ill;
7663 	ssize_t len;
7664 
7665 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7666 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7667 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7668 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7669 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7670 		freemsg(mp);
7671 		return (NULL);
7672 	}
7673 
7674 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7675 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7676 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7677 		freemsg(mp);
7678 		return (NULL);
7679 	}
7680 	/*
7681 	 * Recompute complete header length and make sure we
7682 	 * have access to all of it.
7683 	 */
7684 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7685 	if (len > (mp->b_wptr - mp->b_rptr)) {
7686 		if (len > pkt_len) {
7687 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7688 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7689 			freemsg(mp);
7690 			return (NULL);
7691 		}
7692 		if (ip_pullup(mp, len, ira) == NULL) {
7693 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7694 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7695 			freemsg(mp);
7696 			return (NULL);
7697 		}
7698 	}
7699 	return (mp);
7700 }
7701 
7702 /*
7703  * Returns a new ire, or the same ire, or NULL.
7704  * If a different IRE is returned, then it is held; the caller
7705  * needs to release it.
7706  * In no case is there any hold/release on the ire argument.
7707  */
7708 ire_t *
7709 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7710 {
7711 	ire_t		*new_ire;
7712 	ill_t		*ire_ill;
7713 	uint_t		ifindex;
7714 	ip_stack_t	*ipst = ill->ill_ipst;
7715 	boolean_t	strict_check = B_FALSE;
7716 
7717 	/*
7718 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7719 	 * issue (e.g. packet received on an underlying interface matched an
7720 	 * IRE_LOCAL on its associated group interface).
7721 	 */
7722 	ASSERT(ire->ire_ill != NULL);
7723 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7724 		return (ire);
7725 
7726 	/*
7727 	 * Do another ire lookup here, using the ingress ill, to see if the
7728 	 * interface is in a usesrc group.
7729 	 * As long as the ills belong to the same group, we don't consider
7730 	 * them to be arriving on the wrong interface. Thus, if the switch
7731 	 * is doing inbound load spreading, we won't drop packets when the
7732 	 * ip*_strict_dst_multihoming switch is on.
7733 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7734 	 * where the local address may not be unique. In this case we were
7735 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7736 	 * actually returned. The new lookup, which is more specific, should
7737 	 * only find the IRE_LOCAL associated with the ingress ill if one
7738 	 * exists.
7739 	 */
7740 	if (ire->ire_ipversion == IPV4_VERSION) {
7741 		if (ipst->ips_ip_strict_dst_multihoming)
7742 			strict_check = B_TRUE;
7743 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7744 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7745 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7746 	} else {
7747 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7748 		if (ipst->ips_ipv6_strict_dst_multihoming)
7749 			strict_check = B_TRUE;
7750 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7751 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7752 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7753 	}
7754 	/*
7755 	 * If the same ire that was returned in ip_input() is found then this
7756 	 * is an indication that usesrc groups are in use. The packet
7757 	 * arrived on a different ill in the group than the one associated with
7758 	 * the destination address.  If a different ire was found then the same
7759 	 * IP address must be hosted on multiple ills. This is possible with
7760 	 * unnumbered point2point interfaces. We switch to use this new ire in
7761 	 * order to have accurate interface statistics.
7762 	 */
7763 	if (new_ire != NULL) {
7764 		/* Note: held in one case but not the other? Caller handles */
7765 		if (new_ire != ire)
7766 			return (new_ire);
7767 		/* Unchanged */
7768 		ire_refrele(new_ire);
7769 		return (ire);
7770 	}
7771 
7772 	/*
7773 	 * Chase pointers once and store locally.
7774 	 */
7775 	ASSERT(ire->ire_ill != NULL);
7776 	ire_ill = ire->ire_ill;
7777 	ifindex = ill->ill_usesrc_ifindex;
7778 
7779 	/*
7780 	 * Check if it's a legal address on the 'usesrc' interface.
7781 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7782 	 * can just check phyint_ifindex.
7783 	 */
7784 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7785 		return (ire);
7786 	}
7787 
7788 	/*
7789 	 * If the ip*_strict_dst_multihoming switch is on then we can
7790 	 * only accept this packet if the interface is marked as routing.
7791 	 */
7792 	if (!(strict_check))
7793 		return (ire);
7794 
7795 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7796 		return (ire);
7797 	}
7798 	return (NULL);
7799 }
7800 
7801 /*
7802  * This function is used to construct a mac_header_info_s from a
7803  * DL_UNITDATA_IND message.
7804  * The address fields in the mhi structure points into the message,
7805  * thus the caller can't use those fields after freeing the message.
7806  *
7807  * We determine whether the packet received is a non-unicast packet
7808  * and in doing so, determine whether or not it is broadcast vs multicast.
7809  * For it to be a broadcast packet, we must have the appropriate mblk_t
7810  * hanging off the ill_t.  If this is either not present or doesn't match
7811  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7812  * to be multicast.  Thus NICs that have no broadcast address (or no
7813  * capability for one, such as point to point links) cannot return as
7814  * the packet being broadcast.
7815  */
7816 void
7817 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7818 {
7819 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7820 	mblk_t *bmp;
7821 	uint_t extra_offset;
7822 
7823 	bzero(mhip, sizeof (struct mac_header_info_s));
7824 
7825 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7826 
7827 	if (ill->ill_sap_length < 0)
7828 		extra_offset = 0;
7829 	else
7830 		extra_offset = ill->ill_sap_length;
7831 
7832 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7833 	    extra_offset;
7834 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7835 	    extra_offset;
7836 
7837 	if (!ind->dl_group_address)
7838 		return;
7839 
7840 	/* Multicast or broadcast */
7841 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7842 
7843 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7844 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7845 	    (bmp = ill->ill_bcast_mp) != NULL) {
7846 		dl_unitdata_req_t *dlur;
7847 		uint8_t *bphys_addr;
7848 
7849 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7850 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7851 		    extra_offset;
7852 
7853 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7854 		    ind->dl_dest_addr_length) == 0)
7855 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7856 	}
7857 }
7858 
7859 /*
7860  * This function is used to construct a mac_header_info_s from a
7861  * M_DATA fastpath message from a DLPI driver.
7862  * The address fields in the mhi structure points into the message,
7863  * thus the caller can't use those fields after freeing the message.
7864  *
7865  * We determine whether the packet received is a non-unicast packet
7866  * and in doing so, determine whether or not it is broadcast vs multicast.
7867  * For it to be a broadcast packet, we must have the appropriate mblk_t
7868  * hanging off the ill_t.  If this is either not present or doesn't match
7869  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7870  * to be multicast.  Thus NICs that have no broadcast address (or no
7871  * capability for one, such as point to point links) cannot return as
7872  * the packet being broadcast.
7873  */
7874 void
7875 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7876 {
7877 	mblk_t *bmp;
7878 	struct ether_header *pether;
7879 
7880 	bzero(mhip, sizeof (struct mac_header_info_s));
7881 
7882 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7883 
7884 	pether = (struct ether_header *)((char *)mp->b_rptr
7885 	    - sizeof (struct ether_header));
7886 
7887 	/*
7888 	 * Make sure the interface is an ethernet type, since we don't
7889 	 * know the header format for anything but Ethernet. Also make
7890 	 * sure we are pointing correctly above db_base.
7891 	 */
7892 	if (ill->ill_type != IFT_ETHER)
7893 		return;
7894 
7895 retry:
7896 	if ((uchar_t *)pether < mp->b_datap->db_base)
7897 		return;
7898 
7899 	/* Is there a VLAN tag? */
7900 	if (ill->ill_isv6) {
7901 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7902 			pether = (struct ether_header *)((char *)pether - 4);
7903 			goto retry;
7904 		}
7905 	} else {
7906 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7907 			pether = (struct ether_header *)((char *)pether - 4);
7908 			goto retry;
7909 		}
7910 	}
7911 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7912 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7913 
7914 	if (!(mhip->mhi_daddr[0] & 0x01))
7915 		return;
7916 
7917 	/* Multicast or broadcast */
7918 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7919 
7920 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7921 		dl_unitdata_req_t *dlur;
7922 		uint8_t *bphys_addr;
7923 		uint_t	addrlen;
7924 
7925 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7926 		addrlen = dlur->dl_dest_addr_length;
7927 		if (ill->ill_sap_length < 0) {
7928 			bphys_addr = (uchar_t *)dlur +
7929 			    dlur->dl_dest_addr_offset;
7930 			addrlen += ill->ill_sap_length;
7931 		} else {
7932 			bphys_addr = (uchar_t *)dlur +
7933 			    dlur->dl_dest_addr_offset +
7934 			    ill->ill_sap_length;
7935 			addrlen -= ill->ill_sap_length;
7936 		}
7937 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7938 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7939 	}
7940 }
7941 
7942 /*
7943  * Handle anything but M_DATA messages
7944  * We see the DL_UNITDATA_IND which are part
7945  * of the data path, and also the other messages from the driver.
7946  */
7947 void
7948 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7949 {
7950 	mblk_t		*first_mp;
7951 	struct iocblk   *iocp;
7952 	struct mac_header_info_s mhi;
7953 
7954 	switch (DB_TYPE(mp)) {
7955 	case M_PROTO:
7956 	case M_PCPROTO: {
7957 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7958 		    DL_UNITDATA_IND) {
7959 			/* Go handle anything other than data elsewhere. */
7960 			ip_rput_dlpi(ill, mp);
7961 			return;
7962 		}
7963 
7964 		first_mp = mp;
7965 		mp = first_mp->b_cont;
7966 		first_mp->b_cont = NULL;
7967 
7968 		if (mp == NULL) {
7969 			freeb(first_mp);
7970 			return;
7971 		}
7972 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7973 		if (ill->ill_isv6)
7974 			ip_input_v6(ill, NULL, mp, &mhi);
7975 		else
7976 			ip_input(ill, NULL, mp, &mhi);
7977 
7978 		/* Ditch the DLPI header. */
7979 		freeb(first_mp);
7980 		return;
7981 	}
7982 	case M_IOCACK:
7983 		iocp = (struct iocblk *)mp->b_rptr;
7984 		switch (iocp->ioc_cmd) {
7985 		case DL_IOC_HDR_INFO:
7986 			ill_fastpath_ack(ill, mp);
7987 			return;
7988 		default:
7989 			putnext(ill->ill_rq, mp);
7990 			return;
7991 		}
7992 		/* FALLTHROUGH */
7993 	case M_ERROR:
7994 	case M_HANGUP:
7995 		mutex_enter(&ill->ill_lock);
7996 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7997 			mutex_exit(&ill->ill_lock);
7998 			freemsg(mp);
7999 			return;
8000 		}
8001 		ill_refhold_locked(ill);
8002 		mutex_exit(&ill->ill_lock);
8003 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
8004 		    B_FALSE);
8005 		return;
8006 	case M_CTL:
8007 		putnext(ill->ill_rq, mp);
8008 		return;
8009 	case M_IOCNAK:
8010 		ip1dbg(("got iocnak "));
8011 		iocp = (struct iocblk *)mp->b_rptr;
8012 		switch (iocp->ioc_cmd) {
8013 		case DL_IOC_HDR_INFO:
8014 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
8015 			return;
8016 		default:
8017 			break;
8018 		}
8019 		/* FALLTHROUGH */
8020 	default:
8021 		putnext(ill->ill_rq, mp);
8022 		return;
8023 	}
8024 }
8025 
8026 /* Read side put procedure.  Packets coming from the wire arrive here. */
8027 int
8028 ip_rput(queue_t *q, mblk_t *mp)
8029 {
8030 	ill_t	*ill;
8031 	union DL_primitives *dl;
8032 
8033 	ill = (ill_t *)q->q_ptr;
8034 
8035 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
8036 		/*
8037 		 * If things are opening or closing, only accept high-priority
8038 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
8039 		 * created; on close, things hanging off the ill may have been
8040 		 * freed already.)
8041 		 */
8042 		dl = (union DL_primitives *)mp->b_rptr;
8043 		if (DB_TYPE(mp) != M_PCPROTO ||
8044 		    dl->dl_primitive == DL_UNITDATA_IND) {
8045 			inet_freemsg(mp);
8046 			return (0);
8047 		}
8048 	}
8049 	if (DB_TYPE(mp) == M_DATA) {
8050 		struct mac_header_info_s mhi;
8051 
8052 		ip_mdata_to_mhi(ill, mp, &mhi);
8053 		ip_input(ill, NULL, mp, &mhi);
8054 	} else {
8055 		ip_rput_notdata(ill, mp);
8056 	}
8057 	return (0);
8058 }
8059 
8060 /*
8061  * Move the information to a copy.
8062  */
8063 mblk_t *
8064 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8065 {
8066 	mblk_t		*mp1;
8067 	ill_t		*ill = ira->ira_ill;
8068 	ip_stack_t	*ipst = ill->ill_ipst;
8069 
8070 	IP_STAT(ipst, ip_db_ref);
8071 
8072 	/* Make sure we have ira_l2src before we loose the original mblk */
8073 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
8074 		ip_setl2src(mp, ira, ira->ira_rill);
8075 
8076 	mp1 = copymsg(mp);
8077 	if (mp1 == NULL) {
8078 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8079 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
8080 		freemsg(mp);
8081 		return (NULL);
8082 	}
8083 	/* preserve the hardware checksum flags and data, if present */
8084 	if (DB_CKSUMFLAGS(mp) != 0) {
8085 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8086 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8087 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8088 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8089 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8090 	}
8091 	freemsg(mp);
8092 	return (mp1);
8093 }
8094 
8095 static void
8096 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8097     t_uscalar_t err)
8098 {
8099 	if (dl_err == DL_SYSERR) {
8100 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8101 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8102 		    ill->ill_name, dl_primstr(prim), err);
8103 		return;
8104 	}
8105 
8106 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8107 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8108 	    dl_errstr(dl_err));
8109 }
8110 
8111 /*
8112  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8113  * than DL_UNITDATA_IND messages. If we need to process this message
8114  * exclusively, we call qwriter_ip, in which case we also need to call
8115  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8116  */
8117 void
8118 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8119 {
8120 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8121 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8122 	queue_t		*q = ill->ill_rq;
8123 	t_uscalar_t	prim = dloa->dl_primitive;
8124 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8125 
8126 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8127 	    char *, dl_primstr(prim), ill_t *, ill);
8128 	ip1dbg(("ip_rput_dlpi"));
8129 
8130 	/*
8131 	 * If we received an ACK but didn't send a request for it, then it
8132 	 * can't be part of any pending operation; discard up-front.
8133 	 */
8134 	switch (prim) {
8135 	case DL_ERROR_ACK:
8136 		reqprim = dlea->dl_error_primitive;
8137 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8138 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8139 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8140 		    dlea->dl_unix_errno));
8141 		break;
8142 	case DL_OK_ACK:
8143 		reqprim = dloa->dl_correct_primitive;
8144 		break;
8145 	case DL_INFO_ACK:
8146 		reqprim = DL_INFO_REQ;
8147 		break;
8148 	case DL_BIND_ACK:
8149 		reqprim = DL_BIND_REQ;
8150 		break;
8151 	case DL_PHYS_ADDR_ACK:
8152 		reqprim = DL_PHYS_ADDR_REQ;
8153 		break;
8154 	case DL_NOTIFY_ACK:
8155 		reqprim = DL_NOTIFY_REQ;
8156 		break;
8157 	case DL_CAPABILITY_ACK:
8158 		reqprim = DL_CAPABILITY_REQ;
8159 		break;
8160 	}
8161 
8162 	if (prim != DL_NOTIFY_IND) {
8163 		if (reqprim == DL_PRIM_INVAL ||
8164 		    !ill_dlpi_pending(ill, reqprim)) {
8165 			/* Not a DLPI message we support or expected */
8166 			freemsg(mp);
8167 			return;
8168 		}
8169 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8170 		    dl_primstr(reqprim)));
8171 	}
8172 
8173 	switch (reqprim) {
8174 	case DL_UNBIND_REQ:
8175 		/*
8176 		 * NOTE: we mark the unbind as complete even if we got a
8177 		 * DL_ERROR_ACK, since there's not much else we can do.
8178 		 */
8179 		mutex_enter(&ill->ill_lock);
8180 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8181 		cv_signal(&ill->ill_cv);
8182 		mutex_exit(&ill->ill_lock);
8183 		break;
8184 
8185 	case DL_ENABMULTI_REQ:
8186 		if (prim == DL_OK_ACK) {
8187 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8188 				ill->ill_dlpi_multicast_state = IDS_OK;
8189 		}
8190 		break;
8191 	}
8192 
8193 	/*
8194 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8195 	 * need to become writer to continue to process it.  Because an
8196 	 * exclusive operation doesn't complete until replies to all queued
8197 	 * DLPI messages have been received, we know we're in the middle of an
8198 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8199 	 *
8200 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8201 	 * Since this is on the ill stream we unconditionally bump up the
8202 	 * refcount without doing ILL_CAN_LOOKUP().
8203 	 */
8204 	ill_refhold(ill);
8205 	if (prim == DL_NOTIFY_IND)
8206 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8207 	else
8208 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8209 }
8210 
8211 /*
8212  * Handling of DLPI messages that require exclusive access to the ipsq.
8213  *
8214  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8215  * happen here. (along with mi_copy_done)
8216  */
8217 /* ARGSUSED */
8218 static void
8219 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8220 {
8221 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8222 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8223 	int		err = 0;
8224 	ill_t		*ill = (ill_t *)q->q_ptr;
8225 	ipif_t		*ipif = NULL;
8226 	mblk_t		*mp1 = NULL;
8227 	conn_t		*connp = NULL;
8228 	t_uscalar_t	paddrreq;
8229 	mblk_t		*mp_hw;
8230 	boolean_t	success;
8231 	boolean_t	ioctl_aborted = B_FALSE;
8232 	boolean_t	log = B_TRUE;
8233 
8234 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8235 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8236 
8237 	ip1dbg(("ip_rput_dlpi_writer .."));
8238 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8239 	ASSERT(IAM_WRITER_ILL(ill));
8240 
8241 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8242 	/*
8243 	 * The current ioctl could have been aborted by the user and a new
8244 	 * ioctl to bring up another ill could have started. We could still
8245 	 * get a response from the driver later.
8246 	 */
8247 	if (ipif != NULL && ipif->ipif_ill != ill)
8248 		ioctl_aborted = B_TRUE;
8249 
8250 	switch (dloa->dl_primitive) {
8251 	case DL_ERROR_ACK:
8252 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8253 		    dl_primstr(dlea->dl_error_primitive)));
8254 
8255 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8256 		    char *, dl_primstr(dlea->dl_error_primitive),
8257 		    ill_t *, ill);
8258 
8259 		switch (dlea->dl_error_primitive) {
8260 		case DL_DISABMULTI_REQ:
8261 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8262 			break;
8263 		case DL_PROMISCON_REQ:
8264 		case DL_PROMISCOFF_REQ:
8265 		case DL_UNBIND_REQ:
8266 		case DL_ATTACH_REQ:
8267 		case DL_INFO_REQ:
8268 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8269 			break;
8270 		case DL_NOTIFY_REQ:
8271 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8272 			log = B_FALSE;
8273 			break;
8274 		case DL_PHYS_ADDR_REQ:
8275 			/*
8276 			 * For IPv6 only, there are two additional
8277 			 * phys_addr_req's sent to the driver to get the
8278 			 * IPv6 token and lla. This allows IP to acquire
8279 			 * the hardware address format for a given interface
8280 			 * without having built in knowledge of the hardware
8281 			 * address. ill_phys_addr_pend keeps track of the last
8282 			 * DL_PAR sent so we know which response we are
8283 			 * dealing with. ill_dlpi_done will update
8284 			 * ill_phys_addr_pend when it sends the next req.
8285 			 * We don't complete the IOCTL until all three DL_PARs
8286 			 * have been attempted, so set *_len to 0 and break.
8287 			 */
8288 			paddrreq = ill->ill_phys_addr_pend;
8289 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8290 			if (paddrreq == DL_IPV6_TOKEN) {
8291 				ill->ill_token_length = 0;
8292 				log = B_FALSE;
8293 				break;
8294 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8295 				ill->ill_nd_lla_len = 0;
8296 				log = B_FALSE;
8297 				break;
8298 			}
8299 			/*
8300 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8301 			 * We presumably have an IOCTL hanging out waiting
8302 			 * for completion. Find it and complete the IOCTL
8303 			 * with the error noted.
8304 			 * However, ill_dl_phys was called on an ill queue
8305 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8306 			 * set. But the ioctl is known to be pending on ill_wq.
8307 			 */
8308 			if (!ill->ill_ifname_pending)
8309 				break;
8310 			ill->ill_ifname_pending = 0;
8311 			if (!ioctl_aborted)
8312 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8313 			if (mp1 != NULL) {
8314 				/*
8315 				 * This operation (SIOCSLIFNAME) must have
8316 				 * happened on the ill. Assert there is no conn
8317 				 */
8318 				ASSERT(connp == NULL);
8319 				q = ill->ill_wq;
8320 			}
8321 			break;
8322 		case DL_BIND_REQ:
8323 			ill_dlpi_done(ill, DL_BIND_REQ);
8324 			if (ill->ill_ifname_pending)
8325 				break;
8326 			mutex_enter(&ill->ill_lock);
8327 			ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8328 			mutex_exit(&ill->ill_lock);
8329 			/*
8330 			 * Something went wrong with the bind.  We presumably
8331 			 * have an IOCTL hanging out waiting for completion.
8332 			 * Find it, take down the interface that was coming
8333 			 * up, and complete the IOCTL with the error noted.
8334 			 */
8335 			if (!ioctl_aborted)
8336 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8337 			if (mp1 != NULL) {
8338 				/*
8339 				 * This might be a result of a DL_NOTE_REPLUMB
8340 				 * notification. In that case, connp is NULL.
8341 				 */
8342 				if (connp != NULL)
8343 					q = CONNP_TO_WQ(connp);
8344 
8345 				(void) ipif_down(ipif, NULL, NULL);
8346 				/* error is set below the switch */
8347 			}
8348 			break;
8349 		case DL_ENABMULTI_REQ:
8350 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8351 
8352 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8353 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8354 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8355 
8356 				printf("ip: joining multicasts failed (%d)"
8357 				    " on %s - will use link layer "
8358 				    "broadcasts for multicast\n",
8359 				    dlea->dl_errno, ill->ill_name);
8360 
8361 				/*
8362 				 * Set up for multi_bcast; We are the
8363 				 * writer, so ok to access ill->ill_ipif
8364 				 * without any lock.
8365 				 */
8366 				mutex_enter(&ill->ill_phyint->phyint_lock);
8367 				ill->ill_phyint->phyint_flags |=
8368 				    PHYI_MULTI_BCAST;
8369 				mutex_exit(&ill->ill_phyint->phyint_lock);
8370 
8371 			}
8372 			freemsg(mp);	/* Don't want to pass this up */
8373 			return;
8374 		case DL_CAPABILITY_REQ:
8375 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8376 			    "DL_CAPABILITY REQ\n"));
8377 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8378 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8379 			ill_capability_done(ill);
8380 			freemsg(mp);
8381 			return;
8382 		}
8383 		/*
8384 		 * Note the error for IOCTL completion (mp1 is set when
8385 		 * ready to complete ioctl). If ill_ifname_pending_err is
8386 		 * set, an error occured during plumbing (ill_ifname_pending),
8387 		 * so we want to report that error.
8388 		 *
8389 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8390 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8391 		 * expected to get errack'd if the driver doesn't support
8392 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8393 		 * if these error conditions are encountered.
8394 		 */
8395 		if (mp1 != NULL) {
8396 			if (ill->ill_ifname_pending_err != 0)  {
8397 				err = ill->ill_ifname_pending_err;
8398 				ill->ill_ifname_pending_err = 0;
8399 			} else {
8400 				err = dlea->dl_unix_errno ?
8401 				    dlea->dl_unix_errno : ENXIO;
8402 			}
8403 		/*
8404 		 * If we're plumbing an interface and an error hasn't already
8405 		 * been saved, set ill_ifname_pending_err to the error passed
8406 		 * up. Ignore the error if log is B_FALSE (see comment above).
8407 		 */
8408 		} else if (log && ill->ill_ifname_pending &&
8409 		    ill->ill_ifname_pending_err == 0) {
8410 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8411 			    dlea->dl_unix_errno : ENXIO;
8412 		}
8413 
8414 		if (log)
8415 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8416 			    dlea->dl_errno, dlea->dl_unix_errno);
8417 		break;
8418 	case DL_CAPABILITY_ACK:
8419 		ill_capability_ack(ill, mp);
8420 		/*
8421 		 * The message has been handed off to ill_capability_ack
8422 		 * and must not be freed below
8423 		 */
8424 		mp = NULL;
8425 		break;
8426 
8427 	case DL_INFO_ACK:
8428 		/* Call a routine to handle this one. */
8429 		ill_dlpi_done(ill, DL_INFO_REQ);
8430 		ip_ll_subnet_defaults(ill, mp);
8431 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8432 		return;
8433 	case DL_BIND_ACK:
8434 		/*
8435 		 * We should have an IOCTL waiting on this unless
8436 		 * sent by ill_dl_phys, in which case just return
8437 		 */
8438 		ill_dlpi_done(ill, DL_BIND_REQ);
8439 
8440 		if (ill->ill_ifname_pending) {
8441 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8442 			    ill_t *, ill, mblk_t *, mp);
8443 			break;
8444 		}
8445 		mutex_enter(&ill->ill_lock);
8446 		ill->ill_dl_up = 1;
8447 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8448 		mutex_exit(&ill->ill_lock);
8449 
8450 		if (!ioctl_aborted)
8451 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8452 		if (mp1 == NULL) {
8453 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8454 			break;
8455 		}
8456 		/*
8457 		 * mp1 was added by ill_dl_up(). if that is a result of
8458 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8459 		 */
8460 		if (connp != NULL)
8461 			q = CONNP_TO_WQ(connp);
8462 		/*
8463 		 * We are exclusive. So nothing can change even after
8464 		 * we get the pending mp.
8465 		 */
8466 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8467 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8468 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8469 
8470 		/*
8471 		 * Now bring up the resolver; when that is complete, we'll
8472 		 * create IREs.  Note that we intentionally mirror what
8473 		 * ipif_up() would have done, because we got here by way of
8474 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8475 		 */
8476 		if (ill->ill_isv6) {
8477 			/*
8478 			 * v6 interfaces.
8479 			 * Unlike ARP which has to do another bind
8480 			 * and attach, once we get here we are
8481 			 * done with NDP
8482 			 */
8483 			(void) ipif_resolver_up(ipif, Res_act_initial);
8484 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8485 				err = ipif_up_done_v6(ipif);
8486 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8487 			/*
8488 			 * ARP and other v4 external resolvers.
8489 			 * Leave the pending mblk intact so that
8490 			 * the ioctl completes in ip_rput().
8491 			 */
8492 			if (connp != NULL)
8493 				mutex_enter(&connp->conn_lock);
8494 			mutex_enter(&ill->ill_lock);
8495 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8496 			mutex_exit(&ill->ill_lock);
8497 			if (connp != NULL)
8498 				mutex_exit(&connp->conn_lock);
8499 			if (success) {
8500 				err = ipif_resolver_up(ipif, Res_act_initial);
8501 				if (err == EINPROGRESS) {
8502 					freemsg(mp);
8503 					return;
8504 				}
8505 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8506 			} else {
8507 				/* The conn has started closing */
8508 				err = EINTR;
8509 			}
8510 		} else {
8511 			/*
8512 			 * This one is complete. Reply to pending ioctl.
8513 			 */
8514 			(void) ipif_resolver_up(ipif, Res_act_initial);
8515 			err = ipif_up_done(ipif);
8516 		}
8517 
8518 		if ((err == 0) && (ill->ill_up_ipifs)) {
8519 			err = ill_up_ipifs(ill, q, mp1);
8520 			if (err == EINPROGRESS) {
8521 				freemsg(mp);
8522 				return;
8523 			}
8524 		}
8525 
8526 		/*
8527 		 * If we have a moved ipif to bring up, and everything has
8528 		 * succeeded to this point, bring it up on the IPMP ill.
8529 		 * Otherwise, leave it down -- the admin can try to bring it
8530 		 * up by hand if need be.
8531 		 */
8532 		if (ill->ill_move_ipif != NULL) {
8533 			if (err != 0) {
8534 				ill->ill_move_ipif = NULL;
8535 			} else {
8536 				ipif = ill->ill_move_ipif;
8537 				ill->ill_move_ipif = NULL;
8538 				err = ipif_up(ipif, q, mp1);
8539 				if (err == EINPROGRESS) {
8540 					freemsg(mp);
8541 					return;
8542 				}
8543 			}
8544 		}
8545 		break;
8546 
8547 	case DL_NOTIFY_IND: {
8548 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8549 		uint_t orig_mtu, orig_mc_mtu;
8550 
8551 		switch (notify->dl_notification) {
8552 		case DL_NOTE_PHYS_ADDR:
8553 			err = ill_set_phys_addr(ill, mp);
8554 			break;
8555 
8556 		case DL_NOTE_REPLUMB:
8557 			/*
8558 			 * Directly return after calling ill_replumb().
8559 			 * Note that we should not free mp as it is reused
8560 			 * in the ill_replumb() function.
8561 			 */
8562 			err = ill_replumb(ill, mp);
8563 			return;
8564 
8565 		case DL_NOTE_FASTPATH_FLUSH:
8566 			nce_flush(ill, B_FALSE);
8567 			break;
8568 
8569 		case DL_NOTE_SDU_SIZE:
8570 		case DL_NOTE_SDU_SIZE2:
8571 			/*
8572 			 * The dce and fragmentation code can cope with
8573 			 * this changing while packets are being sent.
8574 			 * When packets are sent ip_output will discover
8575 			 * a change.
8576 			 *
8577 			 * Change the MTU size of the interface.
8578 			 */
8579 			mutex_enter(&ill->ill_lock);
8580 			orig_mtu = ill->ill_mtu;
8581 			orig_mc_mtu = ill->ill_mc_mtu;
8582 			switch (notify->dl_notification) {
8583 			case DL_NOTE_SDU_SIZE:
8584 				ill->ill_current_frag =
8585 				    (uint_t)notify->dl_data;
8586 				ill->ill_mc_mtu = (uint_t)notify->dl_data;
8587 				break;
8588 			case DL_NOTE_SDU_SIZE2:
8589 				ill->ill_current_frag =
8590 				    (uint_t)notify->dl_data1;
8591 				ill->ill_mc_mtu = (uint_t)notify->dl_data2;
8592 				break;
8593 			}
8594 			if (ill->ill_current_frag > ill->ill_max_frag)
8595 				ill->ill_max_frag = ill->ill_current_frag;
8596 
8597 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8598 				ill->ill_mtu = ill->ill_current_frag;
8599 
8600 				/*
8601 				 * If ill_user_mtu was set (via
8602 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8603 				 */
8604 				if (ill->ill_user_mtu != 0 &&
8605 				    ill->ill_user_mtu < ill->ill_mtu)
8606 					ill->ill_mtu = ill->ill_user_mtu;
8607 
8608 				if (ill->ill_user_mtu != 0 &&
8609 				    ill->ill_user_mtu < ill->ill_mc_mtu)
8610 					ill->ill_mc_mtu = ill->ill_user_mtu;
8611 
8612 				if (ill->ill_isv6) {
8613 					if (ill->ill_mtu < IPV6_MIN_MTU)
8614 						ill->ill_mtu = IPV6_MIN_MTU;
8615 					if (ill->ill_mc_mtu < IPV6_MIN_MTU)
8616 						ill->ill_mc_mtu = IPV6_MIN_MTU;
8617 				} else {
8618 					if (ill->ill_mtu < IP_MIN_MTU)
8619 						ill->ill_mtu = IP_MIN_MTU;
8620 					if (ill->ill_mc_mtu < IP_MIN_MTU)
8621 						ill->ill_mc_mtu = IP_MIN_MTU;
8622 				}
8623 			} else if (ill->ill_mc_mtu > ill->ill_mtu) {
8624 				ill->ill_mc_mtu = ill->ill_mtu;
8625 			}
8626 
8627 			mutex_exit(&ill->ill_lock);
8628 			/*
8629 			 * Make sure all dce_generation checks find out
8630 			 * that ill_mtu/ill_mc_mtu has changed.
8631 			 */
8632 			if (orig_mtu != ill->ill_mtu ||
8633 			    orig_mc_mtu != ill->ill_mc_mtu) {
8634 				dce_increment_all_generations(ill->ill_isv6,
8635 				    ill->ill_ipst);
8636 			}
8637 
8638 			/*
8639 			 * Refresh IPMP meta-interface MTU if necessary.
8640 			 */
8641 			if (IS_UNDER_IPMP(ill))
8642 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8643 			break;
8644 
8645 		case DL_NOTE_LINK_UP:
8646 		case DL_NOTE_LINK_DOWN: {
8647 			/*
8648 			 * We are writer. ill / phyint / ipsq assocs stable.
8649 			 * The RUNNING flag reflects the state of the link.
8650 			 */
8651 			phyint_t *phyint = ill->ill_phyint;
8652 			uint64_t new_phyint_flags;
8653 			boolean_t changed = B_FALSE;
8654 			boolean_t went_up;
8655 
8656 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8657 			mutex_enter(&phyint->phyint_lock);
8658 
8659 			new_phyint_flags = went_up ?
8660 			    phyint->phyint_flags | PHYI_RUNNING :
8661 			    phyint->phyint_flags & ~PHYI_RUNNING;
8662 
8663 			if (IS_IPMP(ill)) {
8664 				new_phyint_flags = went_up ?
8665 				    new_phyint_flags & ~PHYI_FAILED :
8666 				    new_phyint_flags | PHYI_FAILED;
8667 			}
8668 
8669 			if (new_phyint_flags != phyint->phyint_flags) {
8670 				phyint->phyint_flags = new_phyint_flags;
8671 				changed = B_TRUE;
8672 			}
8673 			mutex_exit(&phyint->phyint_lock);
8674 			/*
8675 			 * ill_restart_dad handles the DAD restart and routing
8676 			 * socket notification logic.
8677 			 */
8678 			if (changed) {
8679 				ill_restart_dad(phyint->phyint_illv4, went_up);
8680 				ill_restart_dad(phyint->phyint_illv6, went_up);
8681 			}
8682 			break;
8683 		}
8684 		case DL_NOTE_PROMISC_ON_PHYS: {
8685 			phyint_t *phyint = ill->ill_phyint;
8686 
8687 			mutex_enter(&phyint->phyint_lock);
8688 			phyint->phyint_flags |= PHYI_PROMISC;
8689 			mutex_exit(&phyint->phyint_lock);
8690 			break;
8691 		}
8692 		case DL_NOTE_PROMISC_OFF_PHYS: {
8693 			phyint_t *phyint = ill->ill_phyint;
8694 
8695 			mutex_enter(&phyint->phyint_lock);
8696 			phyint->phyint_flags &= ~PHYI_PROMISC;
8697 			mutex_exit(&phyint->phyint_lock);
8698 			break;
8699 		}
8700 		case DL_NOTE_CAPAB_RENEG:
8701 			/*
8702 			 * Something changed on the driver side.
8703 			 * It wants us to renegotiate the capabilities
8704 			 * on this ill. One possible cause is the aggregation
8705 			 * interface under us where a port got added or
8706 			 * went away.
8707 			 *
8708 			 * If the capability negotiation is already done
8709 			 * or is in progress, reset the capabilities and
8710 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8711 			 * so that when the ack comes back, we can start
8712 			 * the renegotiation process.
8713 			 *
8714 			 * Note that if ill_capab_reneg is already B_TRUE
8715 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8716 			 * the capability resetting request has been sent
8717 			 * and the renegotiation has not been started yet;
8718 			 * nothing needs to be done in this case.
8719 			 */
8720 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8721 			ill_capability_reset(ill, B_TRUE);
8722 			ipsq_current_finish(ipsq);
8723 			break;
8724 
8725 		case DL_NOTE_ALLOWED_IPS:
8726 			ill_set_allowed_ips(ill, mp);
8727 			break;
8728 		default:
8729 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8730 			    "type 0x%x for DL_NOTIFY_IND\n",
8731 			    notify->dl_notification));
8732 			break;
8733 		}
8734 
8735 		/*
8736 		 * As this is an asynchronous operation, we
8737 		 * should not call ill_dlpi_done
8738 		 */
8739 		break;
8740 	}
8741 	case DL_NOTIFY_ACK: {
8742 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8743 
8744 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8745 			ill->ill_note_link = 1;
8746 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8747 		break;
8748 	}
8749 	case DL_PHYS_ADDR_ACK: {
8750 		/*
8751 		 * As part of plumbing the interface via SIOCSLIFNAME,
8752 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8753 		 * whose answers we receive here.  As each answer is received,
8754 		 * we call ill_dlpi_done() to dispatch the next request as
8755 		 * we're processing the current one.  Once all answers have
8756 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8757 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8758 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8759 		 * available, but we know the ioctl is pending on ill_wq.)
8760 		 */
8761 		uint_t	paddrlen, paddroff;
8762 		uint8_t	*addr;
8763 
8764 		paddrreq = ill->ill_phys_addr_pend;
8765 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8766 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8767 		addr = mp->b_rptr + paddroff;
8768 
8769 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8770 		if (paddrreq == DL_IPV6_TOKEN) {
8771 			/*
8772 			 * bcopy to low-order bits of ill_token
8773 			 *
8774 			 * XXX Temporary hack - currently, all known tokens
8775 			 * are 64 bits, so I'll cheat for the moment.
8776 			 */
8777 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8778 			ill->ill_token_length = paddrlen;
8779 			break;
8780 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8781 			ASSERT(ill->ill_nd_lla_mp == NULL);
8782 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8783 			mp = NULL;
8784 			break;
8785 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8786 			ASSERT(ill->ill_dest_addr_mp == NULL);
8787 			ill->ill_dest_addr_mp = mp;
8788 			ill->ill_dest_addr = addr;
8789 			mp = NULL;
8790 			if (ill->ill_isv6) {
8791 				ill_setdesttoken(ill);
8792 				ipif_setdestlinklocal(ill->ill_ipif);
8793 			}
8794 			break;
8795 		}
8796 
8797 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8798 		ASSERT(ill->ill_phys_addr_mp == NULL);
8799 		if (!ill->ill_ifname_pending)
8800 			break;
8801 		ill->ill_ifname_pending = 0;
8802 		if (!ioctl_aborted)
8803 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8804 		if (mp1 != NULL) {
8805 			ASSERT(connp == NULL);
8806 			q = ill->ill_wq;
8807 		}
8808 		/*
8809 		 * If any error acks received during the plumbing sequence,
8810 		 * ill_ifname_pending_err will be set. Break out and send up
8811 		 * the error to the pending ioctl.
8812 		 */
8813 		if (ill->ill_ifname_pending_err != 0) {
8814 			err = ill->ill_ifname_pending_err;
8815 			ill->ill_ifname_pending_err = 0;
8816 			break;
8817 		}
8818 
8819 		ill->ill_phys_addr_mp = mp;
8820 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8821 		mp = NULL;
8822 
8823 		/*
8824 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8825 		 * provider doesn't support physical addresses.  We check both
8826 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8827 		 * not have physical addresses, but historically adversises a
8828 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8829 		 * its DL_PHYS_ADDR_ACK.
8830 		 */
8831 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8832 			ill->ill_phys_addr = NULL;
8833 		} else if (paddrlen != ill->ill_phys_addr_length) {
8834 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8835 			    paddrlen, ill->ill_phys_addr_length));
8836 			err = EINVAL;
8837 			break;
8838 		}
8839 
8840 		if (ill->ill_nd_lla_mp == NULL) {
8841 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8842 				err = ENOMEM;
8843 				break;
8844 			}
8845 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8846 		}
8847 
8848 		if (ill->ill_isv6) {
8849 			ill_setdefaulttoken(ill);
8850 			ipif_setlinklocal(ill->ill_ipif);
8851 		}
8852 		break;
8853 	}
8854 	case DL_OK_ACK:
8855 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8856 		    dl_primstr((int)dloa->dl_correct_primitive),
8857 		    dloa->dl_correct_primitive));
8858 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8859 		    char *, dl_primstr(dloa->dl_correct_primitive),
8860 		    ill_t *, ill);
8861 
8862 		switch (dloa->dl_correct_primitive) {
8863 		case DL_ENABMULTI_REQ:
8864 		case DL_DISABMULTI_REQ:
8865 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8866 			break;
8867 		case DL_PROMISCON_REQ:
8868 		case DL_PROMISCOFF_REQ:
8869 		case DL_UNBIND_REQ:
8870 		case DL_ATTACH_REQ:
8871 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8872 			break;
8873 		}
8874 		break;
8875 	default:
8876 		break;
8877 	}
8878 
8879 	freemsg(mp);
8880 	if (mp1 == NULL)
8881 		return;
8882 
8883 	/*
8884 	 * The operation must complete without EINPROGRESS since
8885 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8886 	 * the operation will be stuck forever inside the IPSQ.
8887 	 */
8888 	ASSERT(err != EINPROGRESS);
8889 
8890 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8891 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8892 	    ipif_t *, NULL);
8893 
8894 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8895 	case 0:
8896 		ipsq_current_finish(ipsq);
8897 		break;
8898 
8899 	case SIOCSLIFNAME:
8900 	case IF_UNITSEL: {
8901 		ill_t *ill_other = ILL_OTHER(ill);
8902 
8903 		/*
8904 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8905 		 * ill has a peer which is in an IPMP group, then place ill
8906 		 * into the same group.  One catch: although ifconfig plumbs
8907 		 * the appropriate IPMP meta-interface prior to plumbing this
8908 		 * ill, it is possible for multiple ifconfig applications to
8909 		 * race (or for another application to adjust plumbing), in
8910 		 * which case the IPMP meta-interface we need will be missing.
8911 		 * If so, kick the phyint out of the group.
8912 		 */
8913 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8914 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8915 			ipmp_illgrp_t	*illg;
8916 
8917 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8918 			if (illg == NULL)
8919 				ipmp_phyint_leave_grp(ill->ill_phyint);
8920 			else
8921 				ipmp_ill_join_illgrp(ill, illg);
8922 		}
8923 
8924 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8925 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8926 		else
8927 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8928 		break;
8929 	}
8930 	case SIOCLIFADDIF:
8931 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8932 		break;
8933 
8934 	default:
8935 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8936 		break;
8937 	}
8938 }
8939 
8940 /*
8941  * ip_rput_other is called by ip_rput to handle messages modifying the global
8942  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8943  */
8944 /* ARGSUSED */
8945 void
8946 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8947 {
8948 	ill_t		*ill = q->q_ptr;
8949 	struct iocblk	*iocp;
8950 
8951 	ip1dbg(("ip_rput_other "));
8952 	if (ipsq != NULL) {
8953 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8954 		ASSERT(ipsq->ipsq_xop ==
8955 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8956 	}
8957 
8958 	switch (mp->b_datap->db_type) {
8959 	case M_ERROR:
8960 	case M_HANGUP:
8961 		/*
8962 		 * The device has a problem.  We force the ILL down.  It can
8963 		 * be brought up again manually using SIOCSIFFLAGS (via
8964 		 * ifconfig or equivalent).
8965 		 */
8966 		ASSERT(ipsq != NULL);
8967 		if (mp->b_rptr < mp->b_wptr)
8968 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8969 		if (ill->ill_error == 0)
8970 			ill->ill_error = ENXIO;
8971 		if (!ill_down_start(q, mp))
8972 			return;
8973 		ipif_all_down_tail(ipsq, q, mp, NULL);
8974 		break;
8975 	case M_IOCNAK: {
8976 		iocp = (struct iocblk *)mp->b_rptr;
8977 
8978 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8979 		/*
8980 		 * If this was the first attempt, turn off the fastpath
8981 		 * probing.
8982 		 */
8983 		mutex_enter(&ill->ill_lock);
8984 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8985 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8986 			mutex_exit(&ill->ill_lock);
8987 			/*
8988 			 * don't flush the nce_t entries: we use them
8989 			 * as an index to the ncec itself.
8990 			 */
8991 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8992 			    ill->ill_name));
8993 		} else {
8994 			mutex_exit(&ill->ill_lock);
8995 		}
8996 		freemsg(mp);
8997 		break;
8998 	}
8999 	default:
9000 		ASSERT(0);
9001 		break;
9002 	}
9003 }
9004 
9005 /*
9006  * Update any source route, record route or timestamp options
9007  * When it fails it has consumed the message and BUMPed the MIB.
9008  */
9009 boolean_t
9010 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
9011     ip_recv_attr_t *ira)
9012 {
9013 	ipoptp_t	opts;
9014 	uchar_t		*opt;
9015 	uint8_t		optval;
9016 	uint8_t		optlen;
9017 	ipaddr_t	dst;
9018 	ipaddr_t	ifaddr;
9019 	uint32_t	ts;
9020 	timestruc_t	now;
9021 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9022 
9023 	ip2dbg(("ip_forward_options\n"));
9024 	dst = ipha->ipha_dst;
9025 	opt = NULL;
9026 
9027 	for (optval = ipoptp_first(&opts, ipha);
9028 	    optval != IPOPT_EOL;
9029 	    optval = ipoptp_next(&opts)) {
9030 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9031 		opt = opts.ipoptp_cur;
9032 		optlen = opts.ipoptp_len;
9033 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
9034 		    optval, opts.ipoptp_len));
9035 		switch (optval) {
9036 			uint32_t off;
9037 		case IPOPT_SSRR:
9038 		case IPOPT_LSRR:
9039 			/* Check if adminstratively disabled */
9040 			if (!ipst->ips_ip_forward_src_routed) {
9041 				BUMP_MIB(dst_ill->ill_ip_mib,
9042 				    ipIfStatsForwProhibits);
9043 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
9044 				    mp, dst_ill);
9045 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
9046 				    ira);
9047 				return (B_FALSE);
9048 			}
9049 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9050 				/*
9051 				 * Must be partial since ip_input_options
9052 				 * checked for strict.
9053 				 */
9054 				break;
9055 			}
9056 			off = opt[IPOPT_OFFSET];
9057 			off--;
9058 		redo_srr:
9059 			if (optlen < IP_ADDR_LEN ||
9060 			    off > optlen - IP_ADDR_LEN) {
9061 				/* End of source route */
9062 				ip1dbg((
9063 				    "ip_forward_options: end of SR\n"));
9064 				break;
9065 			}
9066 			/* Pick a reasonable address on the outbound if */
9067 			ASSERT(dst_ill != NULL);
9068 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9069 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9070 			    NULL) != 0) {
9071 				/* No source! Shouldn't happen */
9072 				ifaddr = INADDR_ANY;
9073 			}
9074 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9075 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9076 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
9077 			    ntohl(dst)));
9078 
9079 			/*
9080 			 * Check if our address is present more than
9081 			 * once as consecutive hops in source route.
9082 			 */
9083 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9084 				off += IP_ADDR_LEN;
9085 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9086 				goto redo_srr;
9087 			}
9088 			ipha->ipha_dst = dst;
9089 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9090 			break;
9091 		case IPOPT_RR:
9092 			off = opt[IPOPT_OFFSET];
9093 			off--;
9094 			if (optlen < IP_ADDR_LEN ||
9095 			    off > optlen - IP_ADDR_LEN) {
9096 				/* No more room - ignore */
9097 				ip1dbg((
9098 				    "ip_forward_options: end of RR\n"));
9099 				break;
9100 			}
9101 			/* Pick a reasonable address on the outbound if */
9102 			ASSERT(dst_ill != NULL);
9103 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9104 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9105 			    NULL) != 0) {
9106 				/* No source! Shouldn't happen */
9107 				ifaddr = INADDR_ANY;
9108 			}
9109 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9110 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9111 			break;
9112 		case IPOPT_TS:
9113 			off = 0;
9114 			/* Insert timestamp if there is room */
9115 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9116 			case IPOPT_TS_TSONLY:
9117 				off = IPOPT_TS_TIMELEN;
9118 				break;
9119 			case IPOPT_TS_PRESPEC:
9120 			case IPOPT_TS_PRESPEC_RFC791:
9121 				/* Verify that the address matched */
9122 				off = opt[IPOPT_OFFSET] - 1;
9123 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9124 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9125 					/* Not for us */
9126 					break;
9127 				}
9128 				/* FALLTHROUGH */
9129 			case IPOPT_TS_TSANDADDR:
9130 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9131 				break;
9132 			default:
9133 				/*
9134 				 * ip_*put_options should have already
9135 				 * dropped this packet.
9136 				 */
9137 				cmn_err(CE_PANIC, "ip_forward_options: "
9138 				    "unknown IT - bug in ip_input_options?\n");
9139 			}
9140 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9141 				/* Increase overflow counter */
9142 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9143 				opt[IPOPT_POS_OV_FLG] =
9144 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9145 				    (off << 4));
9146 				break;
9147 			}
9148 			off = opt[IPOPT_OFFSET] - 1;
9149 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9150 			case IPOPT_TS_PRESPEC:
9151 			case IPOPT_TS_PRESPEC_RFC791:
9152 			case IPOPT_TS_TSANDADDR:
9153 				/* Pick a reasonable addr on the outbound if */
9154 				ASSERT(dst_ill != NULL);
9155 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9156 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9157 				    NULL, NULL) != 0) {
9158 					/* No source! Shouldn't happen */
9159 					ifaddr = INADDR_ANY;
9160 				}
9161 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9162 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9163 				/* FALLTHROUGH */
9164 			case IPOPT_TS_TSONLY:
9165 				off = opt[IPOPT_OFFSET] - 1;
9166 				/* Compute # of milliseconds since midnight */
9167 				gethrestime(&now);
9168 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9169 				    NSEC2MSEC(now.tv_nsec);
9170 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9171 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9172 				break;
9173 			}
9174 			break;
9175 		}
9176 	}
9177 	return (B_TRUE);
9178 }
9179 
9180 /*
9181  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9182  * returns 'true' if there are still fragments left on the queue, in
9183  * which case we restart the timer.
9184  */
9185 void
9186 ill_frag_timer(void *arg)
9187 {
9188 	ill_t	*ill = (ill_t *)arg;
9189 	boolean_t frag_pending;
9190 	ip_stack_t *ipst = ill->ill_ipst;
9191 	time_t	timeout;
9192 
9193 	mutex_enter(&ill->ill_lock);
9194 	ASSERT(!ill->ill_fragtimer_executing);
9195 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9196 		ill->ill_frag_timer_id = 0;
9197 		mutex_exit(&ill->ill_lock);
9198 		return;
9199 	}
9200 	ill->ill_fragtimer_executing = 1;
9201 	mutex_exit(&ill->ill_lock);
9202 
9203 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9204 	    ipst->ips_ip_reassembly_timeout);
9205 
9206 	frag_pending = ill_frag_timeout(ill, timeout);
9207 
9208 	/*
9209 	 * Restart the timer, if we have fragments pending or if someone
9210 	 * wanted us to be scheduled again.
9211 	 */
9212 	mutex_enter(&ill->ill_lock);
9213 	ill->ill_fragtimer_executing = 0;
9214 	ill->ill_frag_timer_id = 0;
9215 	if (frag_pending || ill->ill_fragtimer_needrestart)
9216 		ill_frag_timer_start(ill);
9217 	mutex_exit(&ill->ill_lock);
9218 }
9219 
9220 void
9221 ill_frag_timer_start(ill_t *ill)
9222 {
9223 	ip_stack_t *ipst = ill->ill_ipst;
9224 	clock_t	timeo_ms;
9225 
9226 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9227 
9228 	/* If the ill is closing or opening don't proceed */
9229 	if (ill->ill_state_flags & ILL_CONDEMNED)
9230 		return;
9231 
9232 	if (ill->ill_fragtimer_executing) {
9233 		/*
9234 		 * ill_frag_timer is currently executing. Just record the
9235 		 * the fact that we want the timer to be restarted.
9236 		 * ill_frag_timer will post a timeout before it returns,
9237 		 * ensuring it will be called again.
9238 		 */
9239 		ill->ill_fragtimer_needrestart = 1;
9240 		return;
9241 	}
9242 
9243 	if (ill->ill_frag_timer_id == 0) {
9244 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9245 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9246 
9247 		/*
9248 		 * The timer is neither running nor is the timeout handler
9249 		 * executing. Post a timeout so that ill_frag_timer will be
9250 		 * called
9251 		 */
9252 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9253 		    MSEC_TO_TICK(timeo_ms >> 1));
9254 		ill->ill_fragtimer_needrestart = 0;
9255 	}
9256 }
9257 
9258 /*
9259  * Update any source route, record route or timestamp options.
9260  * Check that we are at end of strict source route.
9261  * The options have already been checked for sanity in ip_input_options().
9262  */
9263 boolean_t
9264 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9265 {
9266 	ipoptp_t	opts;
9267 	uchar_t		*opt;
9268 	uint8_t		optval;
9269 	uint8_t		optlen;
9270 	ipaddr_t	dst;
9271 	ipaddr_t	ifaddr;
9272 	uint32_t	ts;
9273 	timestruc_t	now;
9274 	ill_t		*ill = ira->ira_ill;
9275 	ip_stack_t	*ipst = ill->ill_ipst;
9276 
9277 	ip2dbg(("ip_input_local_options\n"));
9278 	opt = NULL;
9279 
9280 	for (optval = ipoptp_first(&opts, ipha);
9281 	    optval != IPOPT_EOL;
9282 	    optval = ipoptp_next(&opts)) {
9283 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9284 		opt = opts.ipoptp_cur;
9285 		optlen = opts.ipoptp_len;
9286 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9287 		    optval, optlen));
9288 		switch (optval) {
9289 			uint32_t off;
9290 		case IPOPT_SSRR:
9291 		case IPOPT_LSRR:
9292 			off = opt[IPOPT_OFFSET];
9293 			off--;
9294 			if (optlen < IP_ADDR_LEN ||
9295 			    off > optlen - IP_ADDR_LEN) {
9296 				/* End of source route */
9297 				ip1dbg(("ip_input_local_options: end of SR\n"));
9298 				break;
9299 			}
9300 			/*
9301 			 * This will only happen if two consecutive entries
9302 			 * in the source route contains our address or if
9303 			 * it is a packet with a loose source route which
9304 			 * reaches us before consuming the whole source route
9305 			 */
9306 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9307 			if (optval == IPOPT_SSRR) {
9308 				goto bad_src_route;
9309 			}
9310 			/*
9311 			 * Hack: instead of dropping the packet truncate the
9312 			 * source route to what has been used by filling the
9313 			 * rest with IPOPT_NOP.
9314 			 */
9315 			opt[IPOPT_OLEN] = (uint8_t)off;
9316 			while (off < optlen) {
9317 				opt[off++] = IPOPT_NOP;
9318 			}
9319 			break;
9320 		case IPOPT_RR:
9321 			off = opt[IPOPT_OFFSET];
9322 			off--;
9323 			if (optlen < IP_ADDR_LEN ||
9324 			    off > optlen - IP_ADDR_LEN) {
9325 				/* No more room - ignore */
9326 				ip1dbg((
9327 				    "ip_input_local_options: end of RR\n"));
9328 				break;
9329 			}
9330 			/* Pick a reasonable address on the outbound if */
9331 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9332 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9333 			    NULL) != 0) {
9334 				/* No source! Shouldn't happen */
9335 				ifaddr = INADDR_ANY;
9336 			}
9337 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9338 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9339 			break;
9340 		case IPOPT_TS:
9341 			off = 0;
9342 			/* Insert timestamp if there is romm */
9343 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9344 			case IPOPT_TS_TSONLY:
9345 				off = IPOPT_TS_TIMELEN;
9346 				break;
9347 			case IPOPT_TS_PRESPEC:
9348 			case IPOPT_TS_PRESPEC_RFC791:
9349 				/* Verify that the address matched */
9350 				off = opt[IPOPT_OFFSET] - 1;
9351 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9352 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9353 					/* Not for us */
9354 					break;
9355 				}
9356 				/* FALLTHROUGH */
9357 			case IPOPT_TS_TSANDADDR:
9358 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9359 				break;
9360 			default:
9361 				/*
9362 				 * ip_*put_options should have already
9363 				 * dropped this packet.
9364 				 */
9365 				cmn_err(CE_PANIC, "ip_input_local_options: "
9366 				    "unknown IT - bug in ip_input_options?\n");
9367 			}
9368 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9369 				/* Increase overflow counter */
9370 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9371 				opt[IPOPT_POS_OV_FLG] =
9372 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9373 				    (off << 4));
9374 				break;
9375 			}
9376 			off = opt[IPOPT_OFFSET] - 1;
9377 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9378 			case IPOPT_TS_PRESPEC:
9379 			case IPOPT_TS_PRESPEC_RFC791:
9380 			case IPOPT_TS_TSANDADDR:
9381 				/* Pick a reasonable addr on the outbound if */
9382 				if (ip_select_source_v4(ill, INADDR_ANY,
9383 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9384 				    &ifaddr, NULL, NULL) != 0) {
9385 					/* No source! Shouldn't happen */
9386 					ifaddr = INADDR_ANY;
9387 				}
9388 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9389 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9390 				/* FALLTHROUGH */
9391 			case IPOPT_TS_TSONLY:
9392 				off = opt[IPOPT_OFFSET] - 1;
9393 				/* Compute # of milliseconds since midnight */
9394 				gethrestime(&now);
9395 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9396 				    NSEC2MSEC(now.tv_nsec);
9397 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9398 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9399 				break;
9400 			}
9401 			break;
9402 		}
9403 	}
9404 	return (B_TRUE);
9405 
9406 bad_src_route:
9407 	/* make sure we clear any indication of a hardware checksum */
9408 	DB_CKSUMFLAGS(mp) = 0;
9409 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9410 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9411 	return (B_FALSE);
9412 
9413 }
9414 
9415 /*
9416  * Process IP options in an inbound packet.  Always returns the nexthop.
9417  * Normally this is the passed in nexthop, but if there is an option
9418  * that effects the nexthop (such as a source route) that will be returned.
9419  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9420  * and mp freed.
9421  */
9422 ipaddr_t
9423 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9424     ip_recv_attr_t *ira, int *errorp)
9425 {
9426 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9427 	ipoptp_t	opts;
9428 	uchar_t		*opt;
9429 	uint8_t		optval;
9430 	uint8_t		optlen;
9431 	intptr_t	code = 0;
9432 	ire_t		*ire;
9433 
9434 	ip2dbg(("ip_input_options\n"));
9435 	opt = NULL;
9436 	*errorp = 0;
9437 	for (optval = ipoptp_first(&opts, ipha);
9438 	    optval != IPOPT_EOL;
9439 	    optval = ipoptp_next(&opts)) {
9440 		opt = opts.ipoptp_cur;
9441 		optlen = opts.ipoptp_len;
9442 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9443 		    optval, optlen));
9444 		/*
9445 		 * Note: we need to verify the checksum before we
9446 		 * modify anything thus this routine only extracts the next
9447 		 * hop dst from any source route.
9448 		 */
9449 		switch (optval) {
9450 			uint32_t off;
9451 		case IPOPT_SSRR:
9452 		case IPOPT_LSRR:
9453 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9454 				if (optval == IPOPT_SSRR) {
9455 					ip1dbg(("ip_input_options: not next"
9456 					    " strict source route 0x%x\n",
9457 					    ntohl(dst)));
9458 					code = (char *)&ipha->ipha_dst -
9459 					    (char *)ipha;
9460 					goto param_prob; /* RouterReq's */
9461 				}
9462 				ip2dbg(("ip_input_options: "
9463 				    "not next source route 0x%x\n",
9464 				    ntohl(dst)));
9465 				break;
9466 			}
9467 
9468 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9469 				ip1dbg((
9470 				    "ip_input_options: bad option offset\n"));
9471 				code = (char *)&opt[IPOPT_OLEN] -
9472 				    (char *)ipha;
9473 				goto param_prob;
9474 			}
9475 			off = opt[IPOPT_OFFSET];
9476 			off--;
9477 		redo_srr:
9478 			if (optlen < IP_ADDR_LEN ||
9479 			    off > optlen - IP_ADDR_LEN) {
9480 				/* End of source route */
9481 				ip1dbg(("ip_input_options: end of SR\n"));
9482 				break;
9483 			}
9484 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9485 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9486 			    ntohl(dst)));
9487 
9488 			/*
9489 			 * Check if our address is present more than
9490 			 * once as consecutive hops in source route.
9491 			 * XXX verify per-interface ip_forwarding
9492 			 * for source route?
9493 			 */
9494 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9495 				off += IP_ADDR_LEN;
9496 				goto redo_srr;
9497 			}
9498 
9499 			if (dst == htonl(INADDR_LOOPBACK)) {
9500 				ip1dbg(("ip_input_options: loopback addr in "
9501 				    "source route!\n"));
9502 				goto bad_src_route;
9503 			}
9504 			/*
9505 			 * For strict: verify that dst is directly
9506 			 * reachable.
9507 			 */
9508 			if (optval == IPOPT_SSRR) {
9509 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9510 				    IRE_INTERFACE, NULL, ALL_ZONES,
9511 				    ira->ira_tsl,
9512 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9513 				    NULL);
9514 				if (ire == NULL) {
9515 					ip1dbg(("ip_input_options: SSRR not "
9516 					    "directly reachable: 0x%x\n",
9517 					    ntohl(dst)));
9518 					goto bad_src_route;
9519 				}
9520 				ire_refrele(ire);
9521 			}
9522 			/*
9523 			 * Defer update of the offset and the record route
9524 			 * until the packet is forwarded.
9525 			 */
9526 			break;
9527 		case IPOPT_RR:
9528 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9529 				ip1dbg((
9530 				    "ip_input_options: bad option offset\n"));
9531 				code = (char *)&opt[IPOPT_OLEN] -
9532 				    (char *)ipha;
9533 				goto param_prob;
9534 			}
9535 			break;
9536 		case IPOPT_TS:
9537 			/*
9538 			 * Verify that length >= 5 and that there is either
9539 			 * room for another timestamp or that the overflow
9540 			 * counter is not maxed out.
9541 			 */
9542 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9543 			if (optlen < IPOPT_MINLEN_IT) {
9544 				goto param_prob;
9545 			}
9546 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9547 				ip1dbg((
9548 				    "ip_input_options: bad option offset\n"));
9549 				code = (char *)&opt[IPOPT_OFFSET] -
9550 				    (char *)ipha;
9551 				goto param_prob;
9552 			}
9553 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9554 			case IPOPT_TS_TSONLY:
9555 				off = IPOPT_TS_TIMELEN;
9556 				break;
9557 			case IPOPT_TS_TSANDADDR:
9558 			case IPOPT_TS_PRESPEC:
9559 			case IPOPT_TS_PRESPEC_RFC791:
9560 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9561 				break;
9562 			default:
9563 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9564 				    (char *)ipha;
9565 				goto param_prob;
9566 			}
9567 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9568 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9569 				/*
9570 				 * No room and the overflow counter is 15
9571 				 * already.
9572 				 */
9573 				goto param_prob;
9574 			}
9575 			break;
9576 		}
9577 	}
9578 
9579 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9580 		return (dst);
9581 	}
9582 
9583 	ip1dbg(("ip_input_options: error processing IP options."));
9584 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9585 
9586 param_prob:
9587 	/* make sure we clear any indication of a hardware checksum */
9588 	DB_CKSUMFLAGS(mp) = 0;
9589 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9590 	icmp_param_problem(mp, (uint8_t)code, ira);
9591 	*errorp = -1;
9592 	return (dst);
9593 
9594 bad_src_route:
9595 	/* make sure we clear any indication of a hardware checksum */
9596 	DB_CKSUMFLAGS(mp) = 0;
9597 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9598 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9599 	*errorp = -1;
9600 	return (dst);
9601 }
9602 
9603 /*
9604  * IP & ICMP info in >=14 msg's ...
9605  *  - ip fixed part (mib2_ip_t)
9606  *  - icmp fixed part (mib2_icmp_t)
9607  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9608  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9609  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9610  *  - ipRouteAttributeTable (ip 102)	labeled routes
9611  *  - ip multicast membership (ip_member_t)
9612  *  - ip multicast source filtering (ip_grpsrc_t)
9613  *  - igmp fixed part (struct igmpstat)
9614  *  - multicast routing stats (struct mrtstat)
9615  *  - multicast routing vifs (array of struct vifctl)
9616  *  - multicast routing routes (array of struct mfcctl)
9617  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9618  *					One per ill plus one generic
9619  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9620  *					One per ill plus one generic
9621  *  - ipv6RouteEntry			all IPv6 IREs
9622  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9623  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9624  *  - ipv6AddrEntry			all IPv6 ipifs
9625  *  - ipv6 multicast membership (ipv6_member_t)
9626  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9627  *
9628  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9629  * already filled in by the caller.
9630  * If legacy_req is true then MIB structures needs to be truncated to their
9631  * legacy sizes before being returned.
9632  * Return value of 0 indicates that no messages were sent and caller
9633  * should free mpctl.
9634  */
9635 int
9636 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level, boolean_t legacy_req)
9637 {
9638 	ip_stack_t *ipst;
9639 	sctp_stack_t *sctps;
9640 
9641 	if (q->q_next != NULL) {
9642 		ipst = ILLQ_TO_IPST(q);
9643 	} else {
9644 		ipst = CONNQ_TO_IPST(q);
9645 	}
9646 	ASSERT(ipst != NULL);
9647 	sctps = ipst->ips_netstack->netstack_sctp;
9648 
9649 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9650 		return (0);
9651 	}
9652 
9653 	/*
9654 	 * For the purposes of the (broken) packet shell use
9655 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9656 	 * to make TCP and UDP appear first in the list of mib items.
9657 	 * TBD: We could expand this and use it in netstat so that
9658 	 * the kernel doesn't have to produce large tables (connections,
9659 	 * routes, etc) when netstat only wants the statistics or a particular
9660 	 * table.
9661 	 */
9662 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9663 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9664 			return (1);
9665 		}
9666 	}
9667 
9668 	if (level != MIB2_TCP) {
9669 		if ((mpctl = udp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9670 			return (1);
9671 		}
9672 		if (level == MIB2_UDP) {
9673 			goto done;
9674 		}
9675 	}
9676 
9677 	if (level != MIB2_UDP) {
9678 		if ((mpctl = tcp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9679 			return (1);
9680 		}
9681 		if (level == MIB2_TCP) {
9682 			goto done;
9683 		}
9684 	}
9685 
9686 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9687 	    ipst, legacy_req)) == NULL) {
9688 		return (1);
9689 	}
9690 
9691 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst,
9692 	    legacy_req)) == NULL) {
9693 		return (1);
9694 	}
9695 
9696 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9697 		return (1);
9698 	}
9699 
9700 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9701 		return (1);
9702 	}
9703 
9704 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9705 		return (1);
9706 	}
9707 
9708 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9709 		return (1);
9710 	}
9711 
9712 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst,
9713 	    legacy_req)) == NULL) {
9714 		return (1);
9715 	}
9716 
9717 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst,
9718 	    legacy_req)) == NULL) {
9719 		return (1);
9720 	}
9721 
9722 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9723 		return (1);
9724 	}
9725 
9726 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9727 		return (1);
9728 	}
9729 
9730 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9731 		return (1);
9732 	}
9733 
9734 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9735 		return (1);
9736 	}
9737 
9738 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9739 		return (1);
9740 	}
9741 
9742 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9743 		return (1);
9744 	}
9745 
9746 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9747 	if (mpctl == NULL)
9748 		return (1);
9749 
9750 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9751 	if (mpctl == NULL)
9752 		return (1);
9753 
9754 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9755 		return (1);
9756 	}
9757 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9758 		return (1);
9759 	}
9760 done:
9761 	freemsg(mpctl);
9762 	return (1);
9763 }
9764 
9765 /* Get global (legacy) IPv4 statistics */
9766 static mblk_t *
9767 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9768     ip_stack_t *ipst, boolean_t legacy_req)
9769 {
9770 	mib2_ip_t		old_ip_mib;
9771 	struct opthdr		*optp;
9772 	mblk_t			*mp2ctl;
9773 	mib2_ipAddrEntry_t	mae;
9774 
9775 	/*
9776 	 * make a copy of the original message
9777 	 */
9778 	mp2ctl = copymsg(mpctl);
9779 
9780 	/* fixed length IP structure... */
9781 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9782 	optp->level = MIB2_IP;
9783 	optp->name = 0;
9784 	SET_MIB(old_ip_mib.ipForwarding,
9785 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9786 	SET_MIB(old_ip_mib.ipDefaultTTL,
9787 	    (uint32_t)ipst->ips_ip_def_ttl);
9788 	SET_MIB(old_ip_mib.ipReasmTimeout,
9789 	    ipst->ips_ip_reassembly_timeout);
9790 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9791 	    (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9792 	    sizeof (mib2_ipAddrEntry_t));
9793 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9794 	    sizeof (mib2_ipRouteEntry_t));
9795 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9796 	    sizeof (mib2_ipNetToMediaEntry_t));
9797 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9798 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9799 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9800 	    sizeof (mib2_ipAttributeEntry_t));
9801 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9802 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9803 
9804 	/*
9805 	 * Grab the statistics from the new IP MIB
9806 	 */
9807 	SET_MIB(old_ip_mib.ipInReceives,
9808 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9809 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9810 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9811 	SET_MIB(old_ip_mib.ipForwDatagrams,
9812 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9813 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9814 	    ipmib->ipIfStatsInUnknownProtos);
9815 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9816 	SET_MIB(old_ip_mib.ipInDelivers,
9817 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9818 	SET_MIB(old_ip_mib.ipOutRequests,
9819 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9820 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9821 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9822 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9823 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9824 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9825 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9826 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9827 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9828 
9829 	/* ipRoutingDiscards is not being used */
9830 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9831 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9832 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9833 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9834 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9835 	    ipmib->ipIfStatsReasmDuplicates);
9836 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9837 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9838 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9839 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9840 	SET_MIB(old_ip_mib.rawipInOverflows,
9841 	    ipmib->rawipIfStatsInOverflows);
9842 
9843 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9844 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9845 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9846 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9847 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9848 	    ipmib->ipIfStatsOutSwitchIPVersion);
9849 
9850 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9851 	    (int)sizeof (old_ip_mib))) {
9852 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9853 		    (uint_t)sizeof (old_ip_mib)));
9854 	}
9855 
9856 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9857 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9858 	    (int)optp->level, (int)optp->name, (int)optp->len));
9859 	qreply(q, mpctl);
9860 	return (mp2ctl);
9861 }
9862 
9863 /* Per interface IPv4 statistics */
9864 static mblk_t *
9865 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9866     boolean_t legacy_req)
9867 {
9868 	struct opthdr		*optp;
9869 	mblk_t			*mp2ctl;
9870 	ill_t			*ill;
9871 	ill_walk_context_t	ctx;
9872 	mblk_t			*mp_tail = NULL;
9873 	mib2_ipIfStatsEntry_t	global_ip_mib;
9874 	mib2_ipAddrEntry_t	mae;
9875 
9876 	/*
9877 	 * Make a copy of the original message
9878 	 */
9879 	mp2ctl = copymsg(mpctl);
9880 
9881 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9882 	optp->level = MIB2_IP;
9883 	optp->name = MIB2_IP_TRAFFIC_STATS;
9884 	/* Include "unknown interface" ip_mib */
9885 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9886 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9887 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9888 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9889 	    (ipst->ips_ip_forwarding ? 1 : 2));
9890 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9891 	    (uint32_t)ipst->ips_ip_def_ttl);
9892 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9893 	    sizeof (mib2_ipIfStatsEntry_t));
9894 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9895 	    sizeof (mib2_ipAddrEntry_t));
9896 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9897 	    sizeof (mib2_ipRouteEntry_t));
9898 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9899 	    sizeof (mib2_ipNetToMediaEntry_t));
9900 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9901 	    sizeof (ip_member_t));
9902 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9903 	    sizeof (ip_grpsrc_t));
9904 
9905 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9906 
9907 	if (legacy_req) {
9908 		SET_MIB(global_ip_mib.ipIfStatsAddrEntrySize,
9909 		    LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t));
9910 	}
9911 
9912 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9913 	    (char *)&global_ip_mib, (int)sizeof (global_ip_mib))) {
9914 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9915 		    "failed to allocate %u bytes\n",
9916 		    (uint_t)sizeof (global_ip_mib)));
9917 	}
9918 
9919 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9920 	ill = ILL_START_WALK_V4(&ctx, ipst);
9921 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9922 		ill->ill_ip_mib->ipIfStatsIfIndex =
9923 		    ill->ill_phyint->phyint_ifindex;
9924 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9925 		    (ipst->ips_ip_forwarding ? 1 : 2));
9926 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9927 		    (uint32_t)ipst->ips_ip_def_ttl);
9928 
9929 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9930 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9931 		    (char *)ill->ill_ip_mib,
9932 		    (int)sizeof (*ill->ill_ip_mib))) {
9933 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9934 			    "failed to allocate %u bytes\n",
9935 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9936 		}
9937 	}
9938 	rw_exit(&ipst->ips_ill_g_lock);
9939 
9940 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9941 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9942 	    "level %d, name %d, len %d\n",
9943 	    (int)optp->level, (int)optp->name, (int)optp->len));
9944 	qreply(q, mpctl);
9945 
9946 	if (mp2ctl == NULL)
9947 		return (NULL);
9948 
9949 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst,
9950 	    legacy_req));
9951 }
9952 
9953 /* Global IPv4 ICMP statistics */
9954 static mblk_t *
9955 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9956 {
9957 	struct opthdr		*optp;
9958 	mblk_t			*mp2ctl;
9959 
9960 	/*
9961 	 * Make a copy of the original message
9962 	 */
9963 	mp2ctl = copymsg(mpctl);
9964 
9965 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9966 	optp->level = MIB2_ICMP;
9967 	optp->name = 0;
9968 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9969 	    (int)sizeof (ipst->ips_icmp_mib))) {
9970 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9971 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9972 	}
9973 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9974 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9975 	    (int)optp->level, (int)optp->name, (int)optp->len));
9976 	qreply(q, mpctl);
9977 	return (mp2ctl);
9978 }
9979 
9980 /* Global IPv4 IGMP statistics */
9981 static mblk_t *
9982 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9983 {
9984 	struct opthdr		*optp;
9985 	mblk_t			*mp2ctl;
9986 
9987 	/*
9988 	 * make a copy of the original message
9989 	 */
9990 	mp2ctl = copymsg(mpctl);
9991 
9992 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9993 	optp->level = EXPER_IGMP;
9994 	optp->name = 0;
9995 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9996 	    (int)sizeof (ipst->ips_igmpstat))) {
9997 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9998 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9999 	}
10000 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10001 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
10002 	    (int)optp->level, (int)optp->name, (int)optp->len));
10003 	qreply(q, mpctl);
10004 	return (mp2ctl);
10005 }
10006 
10007 /* Global IPv4 Multicast Routing statistics */
10008 static mblk_t *
10009 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10010 {
10011 	struct opthdr		*optp;
10012 	mblk_t			*mp2ctl;
10013 
10014 	/*
10015 	 * make a copy of the original message
10016 	 */
10017 	mp2ctl = copymsg(mpctl);
10018 
10019 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10020 	optp->level = EXPER_DVMRP;
10021 	optp->name = 0;
10022 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
10023 		ip0dbg(("ip_mroute_stats: failed\n"));
10024 	}
10025 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10026 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
10027 	    (int)optp->level, (int)optp->name, (int)optp->len));
10028 	qreply(q, mpctl);
10029 	return (mp2ctl);
10030 }
10031 
10032 /* IPv4 address information */
10033 static mblk_t *
10034 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10035     boolean_t legacy_req)
10036 {
10037 	struct opthdr		*optp;
10038 	mblk_t			*mp2ctl;
10039 	mblk_t			*mp_tail = NULL;
10040 	ill_t			*ill;
10041 	ipif_t			*ipif;
10042 	uint_t			bitval;
10043 	mib2_ipAddrEntry_t	mae;
10044 	size_t			mae_size;
10045 	zoneid_t		zoneid;
10046 	ill_walk_context_t	ctx;
10047 
10048 	/*
10049 	 * make a copy of the original message
10050 	 */
10051 	mp2ctl = copymsg(mpctl);
10052 
10053 	mae_size = (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
10054 	    sizeof (mib2_ipAddrEntry_t);
10055 
10056 	/* ipAddrEntryTable */
10057 
10058 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10059 	optp->level = MIB2_IP;
10060 	optp->name = MIB2_IP_ADDR;
10061 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10062 
10063 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10064 	ill = ILL_START_WALK_V4(&ctx, ipst);
10065 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10066 		for (ipif = ill->ill_ipif; ipif != NULL;
10067 		    ipif = ipif->ipif_next) {
10068 			if (ipif->ipif_zoneid != zoneid &&
10069 			    ipif->ipif_zoneid != ALL_ZONES)
10070 				continue;
10071 			/* Sum of count from dead IRE_LO* and our current */
10072 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10073 			if (ipif->ipif_ire_local != NULL) {
10074 				mae.ipAdEntInfo.ae_ibcnt +=
10075 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10076 			}
10077 			mae.ipAdEntInfo.ae_obcnt = 0;
10078 			mae.ipAdEntInfo.ae_focnt = 0;
10079 
10080 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
10081 			    OCTET_LENGTH);
10082 			mae.ipAdEntIfIndex.o_length =
10083 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
10084 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
10085 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
10086 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
10087 			mae.ipAdEntInfo.ae_subnet_len =
10088 			    ip_mask_to_plen(ipif->ipif_net_mask);
10089 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
10090 			for (bitval = 1;
10091 			    bitval &&
10092 			    !(bitval & ipif->ipif_brd_addr);
10093 			    bitval <<= 1)
10094 				noop;
10095 			mae.ipAdEntBcastAddr = bitval;
10096 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10097 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10098 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
10099 			mae.ipAdEntInfo.ae_broadcast_addr =
10100 			    ipif->ipif_brd_addr;
10101 			mae.ipAdEntInfo.ae_pp_dst_addr =
10102 			    ipif->ipif_pp_dst_addr;
10103 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10104 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10105 			mae.ipAdEntRetransmitTime =
10106 			    ill->ill_reachable_retrans_time;
10107 
10108 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10109 			    (char *)&mae, (int)mae_size)) {
10110 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10111 				    "allocate %u bytes\n", (uint_t)mae_size));
10112 			}
10113 		}
10114 	}
10115 	rw_exit(&ipst->ips_ill_g_lock);
10116 
10117 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10118 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10119 	    (int)optp->level, (int)optp->name, (int)optp->len));
10120 	qreply(q, mpctl);
10121 	return (mp2ctl);
10122 }
10123 
10124 /* IPv6 address information */
10125 static mblk_t *
10126 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10127     boolean_t legacy_req)
10128 {
10129 	struct opthdr		*optp;
10130 	mblk_t			*mp2ctl;
10131 	mblk_t			*mp_tail = NULL;
10132 	ill_t			*ill;
10133 	ipif_t			*ipif;
10134 	mib2_ipv6AddrEntry_t	mae6;
10135 	size_t			mae6_size;
10136 	zoneid_t		zoneid;
10137 	ill_walk_context_t	ctx;
10138 
10139 	/*
10140 	 * make a copy of the original message
10141 	 */
10142 	mp2ctl = copymsg(mpctl);
10143 
10144 	mae6_size = (legacy_req) ?
10145 	    LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t) :
10146 	    sizeof (mib2_ipv6AddrEntry_t);
10147 
10148 	/* ipv6AddrEntryTable */
10149 
10150 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10151 	optp->level = MIB2_IP6;
10152 	optp->name = MIB2_IP6_ADDR;
10153 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10154 
10155 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10156 	ill = ILL_START_WALK_V6(&ctx, ipst);
10157 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10158 		for (ipif = ill->ill_ipif; ipif != NULL;
10159 		    ipif = ipif->ipif_next) {
10160 			if (ipif->ipif_zoneid != zoneid &&
10161 			    ipif->ipif_zoneid != ALL_ZONES)
10162 				continue;
10163 			/* Sum of count from dead IRE_LO* and our current */
10164 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10165 			if (ipif->ipif_ire_local != NULL) {
10166 				mae6.ipv6AddrInfo.ae_ibcnt +=
10167 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10168 			}
10169 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10170 			mae6.ipv6AddrInfo.ae_focnt = 0;
10171 
10172 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10173 			    OCTET_LENGTH);
10174 			mae6.ipv6AddrIfIndex.o_length =
10175 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10176 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10177 			mae6.ipv6AddrPfxLength =
10178 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10179 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10180 			mae6.ipv6AddrInfo.ae_subnet_len =
10181 			    mae6.ipv6AddrPfxLength;
10182 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10183 
10184 			/* Type: stateless(1), stateful(2), unknown(3) */
10185 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10186 				mae6.ipv6AddrType = 1;
10187 			else
10188 				mae6.ipv6AddrType = 2;
10189 			/* Anycast: true(1), false(2) */
10190 			if (ipif->ipif_flags & IPIF_ANYCAST)
10191 				mae6.ipv6AddrAnycastFlag = 1;
10192 			else
10193 				mae6.ipv6AddrAnycastFlag = 2;
10194 
10195 			/*
10196 			 * Address status: preferred(1), deprecated(2),
10197 			 * invalid(3), inaccessible(4), unknown(5)
10198 			 */
10199 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10200 				mae6.ipv6AddrStatus = 3;
10201 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10202 				mae6.ipv6AddrStatus = 2;
10203 			else
10204 				mae6.ipv6AddrStatus = 1;
10205 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10206 			mae6.ipv6AddrInfo.ae_metric  =
10207 			    ipif->ipif_ill->ill_metric;
10208 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10209 			    ipif->ipif_v6pp_dst_addr;
10210 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10211 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10212 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10213 			mae6.ipv6AddrIdentifier = ill->ill_token;
10214 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10215 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10216 			mae6.ipv6AddrRetransmitTime =
10217 			    ill->ill_reachable_retrans_time;
10218 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10219 			    (char *)&mae6, (int)mae6_size)) {
10220 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10221 				    "allocate %u bytes\n",
10222 				    (uint_t)mae6_size));
10223 			}
10224 		}
10225 	}
10226 	rw_exit(&ipst->ips_ill_g_lock);
10227 
10228 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10229 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10230 	    (int)optp->level, (int)optp->name, (int)optp->len));
10231 	qreply(q, mpctl);
10232 	return (mp2ctl);
10233 }
10234 
10235 /* IPv4 multicast group membership. */
10236 static mblk_t *
10237 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10238 {
10239 	struct opthdr		*optp;
10240 	mblk_t			*mp2ctl;
10241 	ill_t			*ill;
10242 	ipif_t			*ipif;
10243 	ilm_t			*ilm;
10244 	ip_member_t		ipm;
10245 	mblk_t			*mp_tail = NULL;
10246 	ill_walk_context_t	ctx;
10247 	zoneid_t		zoneid;
10248 
10249 	/*
10250 	 * make a copy of the original message
10251 	 */
10252 	mp2ctl = copymsg(mpctl);
10253 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10254 
10255 	/* ipGroupMember table */
10256 	optp = (struct opthdr *)&mpctl->b_rptr[
10257 	    sizeof (struct T_optmgmt_ack)];
10258 	optp->level = MIB2_IP;
10259 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10260 
10261 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10262 	ill = ILL_START_WALK_V4(&ctx, ipst);
10263 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10264 		/* Make sure the ill isn't going away. */
10265 		if (!ill_check_and_refhold(ill))
10266 			continue;
10267 		rw_exit(&ipst->ips_ill_g_lock);
10268 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10269 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10270 			if (ilm->ilm_zoneid != zoneid &&
10271 			    ilm->ilm_zoneid != ALL_ZONES)
10272 				continue;
10273 
10274 			/* Is there an ipif for ilm_ifaddr? */
10275 			for (ipif = ill->ill_ipif; ipif != NULL;
10276 			    ipif = ipif->ipif_next) {
10277 				if (!IPIF_IS_CONDEMNED(ipif) &&
10278 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10279 				    ilm->ilm_ifaddr != INADDR_ANY)
10280 					break;
10281 			}
10282 			if (ipif != NULL) {
10283 				ipif_get_name(ipif,
10284 				    ipm.ipGroupMemberIfIndex.o_bytes,
10285 				    OCTET_LENGTH);
10286 			} else {
10287 				ill_get_name(ill,
10288 				    ipm.ipGroupMemberIfIndex.o_bytes,
10289 				    OCTET_LENGTH);
10290 			}
10291 			ipm.ipGroupMemberIfIndex.o_length =
10292 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10293 
10294 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10295 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10296 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10297 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10298 			    (char *)&ipm, (int)sizeof (ipm))) {
10299 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10300 				    "failed to allocate %u bytes\n",
10301 				    (uint_t)sizeof (ipm)));
10302 			}
10303 		}
10304 		rw_exit(&ill->ill_mcast_lock);
10305 		ill_refrele(ill);
10306 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10307 	}
10308 	rw_exit(&ipst->ips_ill_g_lock);
10309 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10310 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10311 	    (int)optp->level, (int)optp->name, (int)optp->len));
10312 	qreply(q, mpctl);
10313 	return (mp2ctl);
10314 }
10315 
10316 /* IPv6 multicast group membership. */
10317 static mblk_t *
10318 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10319 {
10320 	struct opthdr		*optp;
10321 	mblk_t			*mp2ctl;
10322 	ill_t			*ill;
10323 	ilm_t			*ilm;
10324 	ipv6_member_t		ipm6;
10325 	mblk_t			*mp_tail = NULL;
10326 	ill_walk_context_t	ctx;
10327 	zoneid_t		zoneid;
10328 
10329 	/*
10330 	 * make a copy of the original message
10331 	 */
10332 	mp2ctl = copymsg(mpctl);
10333 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10334 
10335 	/* ip6GroupMember table */
10336 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10337 	optp->level = MIB2_IP6;
10338 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10339 
10340 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10341 	ill = ILL_START_WALK_V6(&ctx, ipst);
10342 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10343 		/* Make sure the ill isn't going away. */
10344 		if (!ill_check_and_refhold(ill))
10345 			continue;
10346 		rw_exit(&ipst->ips_ill_g_lock);
10347 		/*
10348 		 * Normally we don't have any members on under IPMP interfaces.
10349 		 * We report them as a debugging aid.
10350 		 */
10351 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10352 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10353 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10354 			if (ilm->ilm_zoneid != zoneid &&
10355 			    ilm->ilm_zoneid != ALL_ZONES)
10356 				continue;	/* not this zone */
10357 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10358 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10359 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10360 			if (!snmp_append_data2(mpctl->b_cont,
10361 			    &mp_tail,
10362 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10363 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10364 				    "failed to allocate %u bytes\n",
10365 				    (uint_t)sizeof (ipm6)));
10366 			}
10367 		}
10368 		rw_exit(&ill->ill_mcast_lock);
10369 		ill_refrele(ill);
10370 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10371 	}
10372 	rw_exit(&ipst->ips_ill_g_lock);
10373 
10374 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10375 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10376 	    (int)optp->level, (int)optp->name, (int)optp->len));
10377 	qreply(q, mpctl);
10378 	return (mp2ctl);
10379 }
10380 
10381 /* IP multicast filtered sources */
10382 static mblk_t *
10383 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10384 {
10385 	struct opthdr		*optp;
10386 	mblk_t			*mp2ctl;
10387 	ill_t			*ill;
10388 	ipif_t			*ipif;
10389 	ilm_t			*ilm;
10390 	ip_grpsrc_t		ips;
10391 	mblk_t			*mp_tail = NULL;
10392 	ill_walk_context_t	ctx;
10393 	zoneid_t		zoneid;
10394 	int			i;
10395 	slist_t			*sl;
10396 
10397 	/*
10398 	 * make a copy of the original message
10399 	 */
10400 	mp2ctl = copymsg(mpctl);
10401 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10402 
10403 	/* ipGroupSource table */
10404 	optp = (struct opthdr *)&mpctl->b_rptr[
10405 	    sizeof (struct T_optmgmt_ack)];
10406 	optp->level = MIB2_IP;
10407 	optp->name = EXPER_IP_GROUP_SOURCES;
10408 
10409 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10410 	ill = ILL_START_WALK_V4(&ctx, ipst);
10411 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10412 		/* Make sure the ill isn't going away. */
10413 		if (!ill_check_and_refhold(ill))
10414 			continue;
10415 		rw_exit(&ipst->ips_ill_g_lock);
10416 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10417 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10418 			sl = ilm->ilm_filter;
10419 			if (ilm->ilm_zoneid != zoneid &&
10420 			    ilm->ilm_zoneid != ALL_ZONES)
10421 				continue;
10422 			if (SLIST_IS_EMPTY(sl))
10423 				continue;
10424 
10425 			/* Is there an ipif for ilm_ifaddr? */
10426 			for (ipif = ill->ill_ipif; ipif != NULL;
10427 			    ipif = ipif->ipif_next) {
10428 				if (!IPIF_IS_CONDEMNED(ipif) &&
10429 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10430 				    ilm->ilm_ifaddr != INADDR_ANY)
10431 					break;
10432 			}
10433 			if (ipif != NULL) {
10434 				ipif_get_name(ipif,
10435 				    ips.ipGroupSourceIfIndex.o_bytes,
10436 				    OCTET_LENGTH);
10437 			} else {
10438 				ill_get_name(ill,
10439 				    ips.ipGroupSourceIfIndex.o_bytes,
10440 				    OCTET_LENGTH);
10441 			}
10442 			ips.ipGroupSourceIfIndex.o_length =
10443 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10444 
10445 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10446 			for (i = 0; i < sl->sl_numsrc; i++) {
10447 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10448 					continue;
10449 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10450 				    ips.ipGroupSourceAddress);
10451 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10452 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10453 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10454 					    " failed to allocate %u bytes\n",
10455 					    (uint_t)sizeof (ips)));
10456 				}
10457 			}
10458 		}
10459 		rw_exit(&ill->ill_mcast_lock);
10460 		ill_refrele(ill);
10461 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10462 	}
10463 	rw_exit(&ipst->ips_ill_g_lock);
10464 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10465 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10466 	    (int)optp->level, (int)optp->name, (int)optp->len));
10467 	qreply(q, mpctl);
10468 	return (mp2ctl);
10469 }
10470 
10471 /* IPv6 multicast filtered sources. */
10472 static mblk_t *
10473 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10474 {
10475 	struct opthdr		*optp;
10476 	mblk_t			*mp2ctl;
10477 	ill_t			*ill;
10478 	ilm_t			*ilm;
10479 	ipv6_grpsrc_t		ips6;
10480 	mblk_t			*mp_tail = NULL;
10481 	ill_walk_context_t	ctx;
10482 	zoneid_t		zoneid;
10483 	int			i;
10484 	slist_t			*sl;
10485 
10486 	/*
10487 	 * make a copy of the original message
10488 	 */
10489 	mp2ctl = copymsg(mpctl);
10490 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10491 
10492 	/* ip6GroupMember table */
10493 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10494 	optp->level = MIB2_IP6;
10495 	optp->name = EXPER_IP6_GROUP_SOURCES;
10496 
10497 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10498 	ill = ILL_START_WALK_V6(&ctx, ipst);
10499 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10500 		/* Make sure the ill isn't going away. */
10501 		if (!ill_check_and_refhold(ill))
10502 			continue;
10503 		rw_exit(&ipst->ips_ill_g_lock);
10504 		/*
10505 		 * Normally we don't have any members on under IPMP interfaces.
10506 		 * We report them as a debugging aid.
10507 		 */
10508 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10509 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10510 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10511 			sl = ilm->ilm_filter;
10512 			if (ilm->ilm_zoneid != zoneid &&
10513 			    ilm->ilm_zoneid != ALL_ZONES)
10514 				continue;
10515 			if (SLIST_IS_EMPTY(sl))
10516 				continue;
10517 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10518 			for (i = 0; i < sl->sl_numsrc; i++) {
10519 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10520 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10521 				    (char *)&ips6, (int)sizeof (ips6))) {
10522 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10523 					    "group_src: failed to allocate "
10524 					    "%u bytes\n",
10525 					    (uint_t)sizeof (ips6)));
10526 				}
10527 			}
10528 		}
10529 		rw_exit(&ill->ill_mcast_lock);
10530 		ill_refrele(ill);
10531 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10532 	}
10533 	rw_exit(&ipst->ips_ill_g_lock);
10534 
10535 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10536 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10537 	    (int)optp->level, (int)optp->name, (int)optp->len));
10538 	qreply(q, mpctl);
10539 	return (mp2ctl);
10540 }
10541 
10542 /* Multicast routing virtual interface table. */
10543 static mblk_t *
10544 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10545 {
10546 	struct opthdr		*optp;
10547 	mblk_t			*mp2ctl;
10548 
10549 	/*
10550 	 * make a copy of the original message
10551 	 */
10552 	mp2ctl = copymsg(mpctl);
10553 
10554 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10555 	optp->level = EXPER_DVMRP;
10556 	optp->name = EXPER_DVMRP_VIF;
10557 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10558 		ip0dbg(("ip_mroute_vif: failed\n"));
10559 	}
10560 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10561 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10562 	    (int)optp->level, (int)optp->name, (int)optp->len));
10563 	qreply(q, mpctl);
10564 	return (mp2ctl);
10565 }
10566 
10567 /* Multicast routing table. */
10568 static mblk_t *
10569 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10570 {
10571 	struct opthdr		*optp;
10572 	mblk_t			*mp2ctl;
10573 
10574 	/*
10575 	 * make a copy of the original message
10576 	 */
10577 	mp2ctl = copymsg(mpctl);
10578 
10579 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10580 	optp->level = EXPER_DVMRP;
10581 	optp->name = EXPER_DVMRP_MRT;
10582 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10583 		ip0dbg(("ip_mroute_mrt: failed\n"));
10584 	}
10585 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10586 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10587 	    (int)optp->level, (int)optp->name, (int)optp->len));
10588 	qreply(q, mpctl);
10589 	return (mp2ctl);
10590 }
10591 
10592 /*
10593  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10594  * in one IRE walk.
10595  */
10596 static mblk_t *
10597 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10598     ip_stack_t *ipst)
10599 {
10600 	struct opthdr	*optp;
10601 	mblk_t		*mp2ctl;	/* Returned */
10602 	mblk_t		*mp3ctl;	/* nettomedia */
10603 	mblk_t		*mp4ctl;	/* routeattrs */
10604 	iproutedata_t	ird;
10605 	zoneid_t	zoneid;
10606 
10607 	/*
10608 	 * make copies of the original message
10609 	 *	- mp2ctl is returned unchanged to the caller for its use
10610 	 *	- mpctl is sent upstream as ipRouteEntryTable
10611 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10612 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10613 	 */
10614 	mp2ctl = copymsg(mpctl);
10615 	mp3ctl = copymsg(mpctl);
10616 	mp4ctl = copymsg(mpctl);
10617 	if (mp3ctl == NULL || mp4ctl == NULL) {
10618 		freemsg(mp4ctl);
10619 		freemsg(mp3ctl);
10620 		freemsg(mp2ctl);
10621 		freemsg(mpctl);
10622 		return (NULL);
10623 	}
10624 
10625 	bzero(&ird, sizeof (ird));
10626 
10627 	ird.ird_route.lp_head = mpctl->b_cont;
10628 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10629 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10630 	/*
10631 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10632 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10633 	 * intended a temporary solution until a proper MIB API is provided
10634 	 * that provides complete filtering/caller-opt-in.
10635 	 */
10636 	if (level == EXPER_IP_AND_ALL_IRES)
10637 		ird.ird_flags |= IRD_REPORT_ALL;
10638 
10639 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10640 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10641 
10642 	/* ipRouteEntryTable in mpctl */
10643 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10644 	optp->level = MIB2_IP;
10645 	optp->name = MIB2_IP_ROUTE;
10646 	optp->len = msgdsize(ird.ird_route.lp_head);
10647 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10648 	    (int)optp->level, (int)optp->name, (int)optp->len));
10649 	qreply(q, mpctl);
10650 
10651 	/* ipNetToMediaEntryTable in mp3ctl */
10652 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10653 
10654 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10655 	optp->level = MIB2_IP;
10656 	optp->name = MIB2_IP_MEDIA;
10657 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10658 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10659 	    (int)optp->level, (int)optp->name, (int)optp->len));
10660 	qreply(q, mp3ctl);
10661 
10662 	/* ipRouteAttributeTable in mp4ctl */
10663 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10664 	optp->level = MIB2_IP;
10665 	optp->name = EXPER_IP_RTATTR;
10666 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10667 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10668 	    (int)optp->level, (int)optp->name, (int)optp->len));
10669 	if (optp->len == 0)
10670 		freemsg(mp4ctl);
10671 	else
10672 		qreply(q, mp4ctl);
10673 
10674 	return (mp2ctl);
10675 }
10676 
10677 /*
10678  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10679  * ipv6NetToMediaEntryTable in an NDP walk.
10680  */
10681 static mblk_t *
10682 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10683     ip_stack_t *ipst)
10684 {
10685 	struct opthdr	*optp;
10686 	mblk_t		*mp2ctl;	/* Returned */
10687 	mblk_t		*mp3ctl;	/* nettomedia */
10688 	mblk_t		*mp4ctl;	/* routeattrs */
10689 	iproutedata_t	ird;
10690 	zoneid_t	zoneid;
10691 
10692 	/*
10693 	 * make copies of the original message
10694 	 *	- mp2ctl is returned unchanged to the caller for its use
10695 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10696 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10697 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10698 	 */
10699 	mp2ctl = copymsg(mpctl);
10700 	mp3ctl = copymsg(mpctl);
10701 	mp4ctl = copymsg(mpctl);
10702 	if (mp3ctl == NULL || mp4ctl == NULL) {
10703 		freemsg(mp4ctl);
10704 		freemsg(mp3ctl);
10705 		freemsg(mp2ctl);
10706 		freemsg(mpctl);
10707 		return (NULL);
10708 	}
10709 
10710 	bzero(&ird, sizeof (ird));
10711 
10712 	ird.ird_route.lp_head = mpctl->b_cont;
10713 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10714 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10715 	/*
10716 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10717 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10718 	 * intended a temporary solution until a proper MIB API is provided
10719 	 * that provides complete filtering/caller-opt-in.
10720 	 */
10721 	if (level == EXPER_IP_AND_ALL_IRES)
10722 		ird.ird_flags |= IRD_REPORT_ALL;
10723 
10724 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10725 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10726 
10727 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10728 	optp->level = MIB2_IP6;
10729 	optp->name = MIB2_IP6_ROUTE;
10730 	optp->len = msgdsize(ird.ird_route.lp_head);
10731 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10732 	    (int)optp->level, (int)optp->name, (int)optp->len));
10733 	qreply(q, mpctl);
10734 
10735 	/* ipv6NetToMediaEntryTable in mp3ctl */
10736 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10737 
10738 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10739 	optp->level = MIB2_IP6;
10740 	optp->name = MIB2_IP6_MEDIA;
10741 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10742 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10743 	    (int)optp->level, (int)optp->name, (int)optp->len));
10744 	qreply(q, mp3ctl);
10745 
10746 	/* ipv6RouteAttributeTable in mp4ctl */
10747 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10748 	optp->level = MIB2_IP6;
10749 	optp->name = EXPER_IP_RTATTR;
10750 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10751 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10752 	    (int)optp->level, (int)optp->name, (int)optp->len));
10753 	if (optp->len == 0)
10754 		freemsg(mp4ctl);
10755 	else
10756 		qreply(q, mp4ctl);
10757 
10758 	return (mp2ctl);
10759 }
10760 
10761 /*
10762  * IPv6 mib: One per ill
10763  */
10764 static mblk_t *
10765 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10766     boolean_t legacy_req)
10767 {
10768 	struct opthdr		*optp;
10769 	mblk_t			*mp2ctl;
10770 	ill_t			*ill;
10771 	ill_walk_context_t	ctx;
10772 	mblk_t			*mp_tail = NULL;
10773 	mib2_ipv6AddrEntry_t	mae6;
10774 	mib2_ipIfStatsEntry_t	*ise;
10775 	size_t			ise_size, iae_size;
10776 
10777 	/*
10778 	 * Make a copy of the original message
10779 	 */
10780 	mp2ctl = copymsg(mpctl);
10781 
10782 	/* fixed length IPv6 structure ... */
10783 
10784 	if (legacy_req) {
10785 		ise_size = LEGACY_MIB_SIZE(&ipst->ips_ip6_mib,
10786 		    mib2_ipIfStatsEntry_t);
10787 		iae_size = LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t);
10788 	} else {
10789 		ise_size = sizeof (mib2_ipIfStatsEntry_t);
10790 		iae_size = sizeof (mib2_ipv6AddrEntry_t);
10791 	}
10792 
10793 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10794 	optp->level = MIB2_IP6;
10795 	optp->name = 0;
10796 	/* Include "unknown interface" ip6_mib */
10797 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10798 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10799 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10800 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10801 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10802 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10803 	    ipst->ips_ipv6_def_hops);
10804 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10805 	    sizeof (mib2_ipIfStatsEntry_t));
10806 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10807 	    sizeof (mib2_ipv6AddrEntry_t));
10808 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10809 	    sizeof (mib2_ipv6RouteEntry_t));
10810 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10811 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10812 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10813 	    sizeof (ipv6_member_t));
10814 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10815 	    sizeof (ipv6_grpsrc_t));
10816 
10817 	/*
10818 	 * Synchronize 64- and 32-bit counters
10819 	 */
10820 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10821 	    ipIfStatsHCInReceives);
10822 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10823 	    ipIfStatsHCInDelivers);
10824 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10825 	    ipIfStatsHCOutRequests);
10826 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10827 	    ipIfStatsHCOutForwDatagrams);
10828 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10829 	    ipIfStatsHCOutMcastPkts);
10830 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10831 	    ipIfStatsHCInMcastPkts);
10832 
10833 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10834 	    (char *)&ipst->ips_ip6_mib, (int)ise_size)) {
10835 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10836 		    (uint_t)ise_size));
10837 	} else if (legacy_req) {
10838 		/* Adjust the EntrySize fields for legacy requests. */
10839 		ise =
10840 		    (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr - (int)ise_size);
10841 		SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10842 		SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10843 	}
10844 
10845 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10846 	ill = ILL_START_WALK_V6(&ctx, ipst);
10847 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10848 		ill->ill_ip_mib->ipIfStatsIfIndex =
10849 		    ill->ill_phyint->phyint_ifindex;
10850 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10851 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10852 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10853 		    ill->ill_max_hops);
10854 
10855 		/*
10856 		 * Synchronize 64- and 32-bit counters
10857 		 */
10858 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10859 		    ipIfStatsHCInReceives);
10860 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10861 		    ipIfStatsHCInDelivers);
10862 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10863 		    ipIfStatsHCOutRequests);
10864 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10865 		    ipIfStatsHCOutForwDatagrams);
10866 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10867 		    ipIfStatsHCOutMcastPkts);
10868 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10869 		    ipIfStatsHCInMcastPkts);
10870 
10871 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10872 		    (char *)ill->ill_ip_mib, (int)ise_size)) {
10873 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10874 			"%u bytes\n", (uint_t)ise_size));
10875 		} else if (legacy_req) {
10876 			/* Adjust the EntrySize fields for legacy requests. */
10877 			ise = (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr -
10878 			    (int)ise_size);
10879 			SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10880 			SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10881 		}
10882 	}
10883 	rw_exit(&ipst->ips_ill_g_lock);
10884 
10885 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10886 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10887 	    (int)optp->level, (int)optp->name, (int)optp->len));
10888 	qreply(q, mpctl);
10889 	return (mp2ctl);
10890 }
10891 
10892 /*
10893  * ICMPv6 mib: One per ill
10894  */
10895 static mblk_t *
10896 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10897 {
10898 	struct opthdr		*optp;
10899 	mblk_t			*mp2ctl;
10900 	ill_t			*ill;
10901 	ill_walk_context_t	ctx;
10902 	mblk_t			*mp_tail = NULL;
10903 	/*
10904 	 * Make a copy of the original message
10905 	 */
10906 	mp2ctl = copymsg(mpctl);
10907 
10908 	/* fixed length ICMPv6 structure ... */
10909 
10910 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10911 	optp->level = MIB2_ICMP6;
10912 	optp->name = 0;
10913 	/* Include "unknown interface" icmp6_mib */
10914 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10915 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10916 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10917 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10918 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10919 	    (char *)&ipst->ips_icmp6_mib,
10920 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10921 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10922 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10923 	}
10924 
10925 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10926 	ill = ILL_START_WALK_V6(&ctx, ipst);
10927 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10928 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10929 		    ill->ill_phyint->phyint_ifindex;
10930 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10931 		    (char *)ill->ill_icmp6_mib,
10932 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10933 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10934 			    "%u bytes\n",
10935 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10936 		}
10937 	}
10938 	rw_exit(&ipst->ips_ill_g_lock);
10939 
10940 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10941 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10942 	    (int)optp->level, (int)optp->name, (int)optp->len));
10943 	qreply(q, mpctl);
10944 	return (mp2ctl);
10945 }
10946 
10947 /*
10948  * ire_walk routine to create both ipRouteEntryTable and
10949  * ipRouteAttributeTable in one IRE walk
10950  */
10951 static void
10952 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10953 {
10954 	ill_t				*ill;
10955 	mib2_ipRouteEntry_t		*re;
10956 	mib2_ipAttributeEntry_t		iaes;
10957 	tsol_ire_gw_secattr_t		*attrp;
10958 	tsol_gc_t			*gc = NULL;
10959 	tsol_gcgrp_t			*gcgrp = NULL;
10960 	ip_stack_t			*ipst = ire->ire_ipst;
10961 
10962 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10963 
10964 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10965 		if (ire->ire_testhidden)
10966 			return;
10967 		if (ire->ire_type & IRE_IF_CLONE)
10968 			return;
10969 	}
10970 
10971 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10972 		return;
10973 
10974 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10975 		mutex_enter(&attrp->igsa_lock);
10976 		if ((gc = attrp->igsa_gc) != NULL) {
10977 			gcgrp = gc->gc_grp;
10978 			ASSERT(gcgrp != NULL);
10979 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10980 		}
10981 		mutex_exit(&attrp->igsa_lock);
10982 	}
10983 	/*
10984 	 * Return all IRE types for route table... let caller pick and choose
10985 	 */
10986 	re->ipRouteDest = ire->ire_addr;
10987 	ill = ire->ire_ill;
10988 	re->ipRouteIfIndex.o_length = 0;
10989 	if (ill != NULL) {
10990 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10991 		re->ipRouteIfIndex.o_length =
10992 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10993 	}
10994 	re->ipRouteMetric1 = -1;
10995 	re->ipRouteMetric2 = -1;
10996 	re->ipRouteMetric3 = -1;
10997 	re->ipRouteMetric4 = -1;
10998 
10999 	re->ipRouteNextHop = ire->ire_gateway_addr;
11000 	/* indirect(4), direct(3), or invalid(2) */
11001 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11002 		re->ipRouteType = 2;
11003 	else if (ire->ire_type & IRE_ONLINK)
11004 		re->ipRouteType = 3;
11005 	else
11006 		re->ipRouteType = 4;
11007 
11008 	re->ipRouteProto = -1;
11009 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
11010 	re->ipRouteMask = ire->ire_mask;
11011 	re->ipRouteMetric5 = -1;
11012 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11013 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
11014 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11015 
11016 	re->ipRouteInfo.re_frag_flag	= 0;
11017 	re->ipRouteInfo.re_rtt		= 0;
11018 	re->ipRouteInfo.re_src_addr	= 0;
11019 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
11020 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11021 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11022 	re->ipRouteInfo.re_flags	= ire->ire_flags;
11023 
11024 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11025 	if (ire->ire_type & IRE_INTERFACE) {
11026 		ire_t *child;
11027 
11028 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11029 		child = ire->ire_dep_children;
11030 		while (child != NULL) {
11031 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
11032 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11033 			child = child->ire_dep_sib_next;
11034 		}
11035 		rw_exit(&ipst->ips_ire_dep_lock);
11036 	}
11037 
11038 	if (ire->ire_flags & RTF_DYNAMIC) {
11039 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11040 	} else {
11041 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
11042 	}
11043 
11044 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11045 	    (char *)re, (int)sizeof (*re))) {
11046 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
11047 		    (uint_t)sizeof (*re)));
11048 	}
11049 
11050 	if (gc != NULL) {
11051 		iaes.iae_routeidx = ird->ird_idx;
11052 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11053 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11054 
11055 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11056 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11057 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
11058 			    "bytes\n", (uint_t)sizeof (iaes)));
11059 		}
11060 	}
11061 
11062 	/* bump route index for next pass */
11063 	ird->ird_idx++;
11064 
11065 	kmem_free(re, sizeof (*re));
11066 	if (gcgrp != NULL)
11067 		rw_exit(&gcgrp->gcgrp_rwlock);
11068 }
11069 
11070 /*
11071  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
11072  */
11073 static void
11074 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
11075 {
11076 	ill_t				*ill;
11077 	mib2_ipv6RouteEntry_t		*re;
11078 	mib2_ipAttributeEntry_t		iaes;
11079 	tsol_ire_gw_secattr_t		*attrp;
11080 	tsol_gc_t			*gc = NULL;
11081 	tsol_gcgrp_t			*gcgrp = NULL;
11082 	ip_stack_t			*ipst = ire->ire_ipst;
11083 
11084 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
11085 
11086 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11087 		if (ire->ire_testhidden)
11088 			return;
11089 		if (ire->ire_type & IRE_IF_CLONE)
11090 			return;
11091 	}
11092 
11093 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11094 		return;
11095 
11096 	if ((attrp = ire->ire_gw_secattr) != NULL) {
11097 		mutex_enter(&attrp->igsa_lock);
11098 		if ((gc = attrp->igsa_gc) != NULL) {
11099 			gcgrp = gc->gc_grp;
11100 			ASSERT(gcgrp != NULL);
11101 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11102 		}
11103 		mutex_exit(&attrp->igsa_lock);
11104 	}
11105 	/*
11106 	 * Return all IRE types for route table... let caller pick and choose
11107 	 */
11108 	re->ipv6RouteDest = ire->ire_addr_v6;
11109 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11110 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
11111 	re->ipv6RouteIfIndex.o_length = 0;
11112 	ill = ire->ire_ill;
11113 	if (ill != NULL) {
11114 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11115 		re->ipv6RouteIfIndex.o_length =
11116 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11117 	}
11118 
11119 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
11120 
11121 	mutex_enter(&ire->ire_lock);
11122 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11123 	mutex_exit(&ire->ire_lock);
11124 
11125 	/* remote(4), local(3), or discard(2) */
11126 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11127 		re->ipv6RouteType = 2;
11128 	else if (ire->ire_type & IRE_ONLINK)
11129 		re->ipv6RouteType = 3;
11130 	else
11131 		re->ipv6RouteType = 4;
11132 
11133 	re->ipv6RouteProtocol	= -1;
11134 	re->ipv6RoutePolicy	= 0;
11135 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
11136 	re->ipv6RouteNextHopRDI	= 0;
11137 	re->ipv6RouteWeight	= 0;
11138 	re->ipv6RouteMetric	= 0;
11139 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11140 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11141 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11142 
11143 	re->ipv6RouteInfo.re_frag_flag	= 0;
11144 	re->ipv6RouteInfo.re_rtt	= 0;
11145 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
11146 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11147 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11148 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
11149 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
11150 
11151 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11152 	if (ire->ire_type & IRE_INTERFACE) {
11153 		ire_t *child;
11154 
11155 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11156 		child = ire->ire_dep_children;
11157 		while (child != NULL) {
11158 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11159 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11160 			child = child->ire_dep_sib_next;
11161 		}
11162 		rw_exit(&ipst->ips_ire_dep_lock);
11163 	}
11164 	if (ire->ire_flags & RTF_DYNAMIC) {
11165 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11166 	} else {
11167 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
11168 	}
11169 
11170 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11171 	    (char *)re, (int)sizeof (*re))) {
11172 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11173 		    (uint_t)sizeof (*re)));
11174 	}
11175 
11176 	if (gc != NULL) {
11177 		iaes.iae_routeidx = ird->ird_idx;
11178 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11179 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11180 
11181 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11182 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11183 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11184 			    "bytes\n", (uint_t)sizeof (iaes)));
11185 		}
11186 	}
11187 
11188 	/* bump route index for next pass */
11189 	ird->ird_idx++;
11190 
11191 	kmem_free(re, sizeof (*re));
11192 	if (gcgrp != NULL)
11193 		rw_exit(&gcgrp->gcgrp_rwlock);
11194 }
11195 
11196 /*
11197  * ncec_walk routine to create ipv6NetToMediaEntryTable
11198  */
11199 static void
11200 ip_snmp_get2_v6_media(ncec_t *ncec, void *ptr)
11201 {
11202 	iproutedata_t *ird		= ptr;
11203 	ill_t				*ill;
11204 	mib2_ipv6NetToMediaEntry_t	ntme;
11205 
11206 	ill = ncec->ncec_ill;
11207 	/* skip arpce entries, and loopback ncec entries */
11208 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11209 		return;
11210 	/*
11211 	 * Neighbor cache entry attached to IRE with on-link
11212 	 * destination.
11213 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11214 	 */
11215 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11216 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11217 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11218 	if (ncec->ncec_lladdr != NULL) {
11219 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11220 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11221 	}
11222 	/*
11223 	 * Note: Returns ND_* states. Should be:
11224 	 * reachable(1), stale(2), delay(3), probe(4),
11225 	 * invalid(5), unknown(6)
11226 	 */
11227 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11228 	ntme.ipv6NetToMediaLastUpdated = 0;
11229 
11230 	/* other(1), dynamic(2), static(3), local(4) */
11231 	if (NCE_MYADDR(ncec)) {
11232 		ntme.ipv6NetToMediaType = 4;
11233 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11234 		ntme.ipv6NetToMediaType = 1; /* proxy */
11235 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11236 		ntme.ipv6NetToMediaType = 3;
11237 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11238 		ntme.ipv6NetToMediaType = 1;
11239 	} else {
11240 		ntme.ipv6NetToMediaType = 2;
11241 	}
11242 
11243 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11244 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11245 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11246 		    (uint_t)sizeof (ntme)));
11247 	}
11248 }
11249 
11250 int
11251 nce2ace(ncec_t *ncec)
11252 {
11253 	int flags = 0;
11254 
11255 	if (NCE_ISREACHABLE(ncec))
11256 		flags |= ACE_F_RESOLVED;
11257 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11258 		flags |= ACE_F_AUTHORITY;
11259 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11260 		flags |= ACE_F_PUBLISH;
11261 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11262 		flags |= ACE_F_PERMANENT;
11263 	if (NCE_MYADDR(ncec))
11264 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11265 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11266 		flags |= ACE_F_UNVERIFIED;
11267 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11268 		flags |= ACE_F_AUTHORITY;
11269 	if (ncec->ncec_flags & NCE_F_DELAYED)
11270 		flags |= ACE_F_DELAYED;
11271 	return (flags);
11272 }
11273 
11274 /*
11275  * ncec_walk routine to create ipNetToMediaEntryTable
11276  */
11277 static void
11278 ip_snmp_get2_v4_media(ncec_t *ncec, void *ptr)
11279 {
11280 	iproutedata_t *ird		= ptr;
11281 	ill_t				*ill;
11282 	mib2_ipNetToMediaEntry_t	ntme;
11283 	const char			*name = "unknown";
11284 	ipaddr_t			ncec_addr;
11285 
11286 	ill = ncec->ncec_ill;
11287 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11288 	    ill->ill_net_type == IRE_LOOPBACK)
11289 		return;
11290 
11291 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11292 	name = ill->ill_name;
11293 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11294 	if (NCE_MYADDR(ncec)) {
11295 		ntme.ipNetToMediaType = 4;
11296 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11297 		ntme.ipNetToMediaType = 1;
11298 	} else {
11299 		ntme.ipNetToMediaType = 3;
11300 	}
11301 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11302 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11303 	    ntme.ipNetToMediaIfIndex.o_length);
11304 
11305 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11306 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11307 
11308 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11309 	ncec_addr = INADDR_BROADCAST;
11310 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11311 	    sizeof (ncec_addr));
11312 	/*
11313 	 * map all the flags to the ACE counterpart.
11314 	 */
11315 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11316 
11317 	ntme.ipNetToMediaPhysAddress.o_length =
11318 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11319 
11320 	if (!NCE_ISREACHABLE(ncec))
11321 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11322 	else {
11323 		if (ncec->ncec_lladdr != NULL) {
11324 			bcopy(ncec->ncec_lladdr,
11325 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11326 			    ntme.ipNetToMediaPhysAddress.o_length);
11327 		}
11328 	}
11329 
11330 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11331 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11332 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11333 		    (uint_t)sizeof (ntme)));
11334 	}
11335 }
11336 
11337 /*
11338  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11339  */
11340 /* ARGSUSED */
11341 int
11342 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11343 {
11344 	switch (level) {
11345 	case MIB2_IP:
11346 	case MIB2_ICMP:
11347 		switch (name) {
11348 		default:
11349 			break;
11350 		}
11351 		return (1);
11352 	default:
11353 		return (1);
11354 	}
11355 }
11356 
11357 /*
11358  * When there exists both a 64- and 32-bit counter of a particular type
11359  * (i.e., InReceives), only the 64-bit counters are added.
11360  */
11361 void
11362 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11363 {
11364 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11365 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11366 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11367 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11368 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11369 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11370 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11371 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11372 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11373 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11374 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11375 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11376 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11377 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11378 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11379 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11380 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11381 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11382 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11383 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11384 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11385 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11386 	    o2->ipIfStatsInWrongIPVersion);
11387 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11388 	    o2->ipIfStatsInWrongIPVersion);
11389 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11390 	    o2->ipIfStatsOutSwitchIPVersion);
11391 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11392 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11393 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11394 	    o2->ipIfStatsHCInForwDatagrams);
11395 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11396 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11397 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11398 	    o2->ipIfStatsHCOutForwDatagrams);
11399 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11400 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11401 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11402 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11403 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11404 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11405 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11406 	    o2->ipIfStatsHCOutMcastOctets);
11407 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11408 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11409 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11410 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11411 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11412 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11413 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11414 }
11415 
11416 void
11417 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11418 {
11419 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11420 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11421 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11422 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11423 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11424 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11425 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11426 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11427 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11428 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11429 	    o2->ipv6IfIcmpInRouterSolicits);
11430 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11431 	    o2->ipv6IfIcmpInRouterAdvertisements);
11432 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11433 	    o2->ipv6IfIcmpInNeighborSolicits);
11434 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11435 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11436 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11437 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11438 	    o2->ipv6IfIcmpInGroupMembQueries);
11439 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11440 	    o2->ipv6IfIcmpInGroupMembResponses);
11441 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11442 	    o2->ipv6IfIcmpInGroupMembReductions);
11443 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11444 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11445 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11446 	    o2->ipv6IfIcmpOutDestUnreachs);
11447 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11448 	    o2->ipv6IfIcmpOutAdminProhibs);
11449 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11450 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11451 	    o2->ipv6IfIcmpOutParmProblems);
11452 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11453 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11454 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11455 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11456 	    o2->ipv6IfIcmpOutRouterSolicits);
11457 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11458 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11459 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11460 	    o2->ipv6IfIcmpOutNeighborSolicits);
11461 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11462 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11463 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11464 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11465 	    o2->ipv6IfIcmpOutGroupMembQueries);
11466 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11467 	    o2->ipv6IfIcmpOutGroupMembResponses);
11468 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11469 	    o2->ipv6IfIcmpOutGroupMembReductions);
11470 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11471 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11472 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11473 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11474 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11475 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11476 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11477 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11478 	    o2->ipv6IfIcmpInGroupMembTotal);
11479 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11480 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11481 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11482 	    o2->ipv6IfIcmpInGroupMembBadReports);
11483 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11484 	    o2->ipv6IfIcmpInGroupMembOurReports);
11485 }
11486 
11487 /*
11488  * Called before the options are updated to check if this packet will
11489  * be source routed from here.
11490  * This routine assumes that the options are well formed i.e. that they
11491  * have already been checked.
11492  */
11493 boolean_t
11494 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11495 {
11496 	ipoptp_t	opts;
11497 	uchar_t		*opt;
11498 	uint8_t		optval;
11499 	uint8_t		optlen;
11500 	ipaddr_t	dst;
11501 
11502 	if (IS_SIMPLE_IPH(ipha)) {
11503 		ip2dbg(("not source routed\n"));
11504 		return (B_FALSE);
11505 	}
11506 	dst = ipha->ipha_dst;
11507 	for (optval = ipoptp_first(&opts, ipha);
11508 	    optval != IPOPT_EOL;
11509 	    optval = ipoptp_next(&opts)) {
11510 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11511 		opt = opts.ipoptp_cur;
11512 		optlen = opts.ipoptp_len;
11513 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11514 		    optval, optlen));
11515 		switch (optval) {
11516 			uint32_t off;
11517 		case IPOPT_SSRR:
11518 		case IPOPT_LSRR:
11519 			/*
11520 			 * If dst is one of our addresses and there are some
11521 			 * entries left in the source route return (true).
11522 			 */
11523 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11524 				ip2dbg(("ip_source_routed: not next"
11525 				    " source route 0x%x\n",
11526 				    ntohl(dst)));
11527 				return (B_FALSE);
11528 			}
11529 			off = opt[IPOPT_OFFSET];
11530 			off--;
11531 			if (optlen < IP_ADDR_LEN ||
11532 			    off > optlen - IP_ADDR_LEN) {
11533 				/* End of source route */
11534 				ip1dbg(("ip_source_routed: end of SR\n"));
11535 				return (B_FALSE);
11536 			}
11537 			return (B_TRUE);
11538 		}
11539 	}
11540 	ip2dbg(("not source routed\n"));
11541 	return (B_FALSE);
11542 }
11543 
11544 /*
11545  * ip_unbind is called by the transports to remove a conn from
11546  * the fanout table.
11547  */
11548 void
11549 ip_unbind(conn_t *connp)
11550 {
11551 
11552 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11553 
11554 	if (is_system_labeled() && connp->conn_anon_port) {
11555 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11556 		    connp->conn_mlp_type, connp->conn_proto,
11557 		    ntohs(connp->conn_lport), B_FALSE);
11558 		connp->conn_anon_port = 0;
11559 	}
11560 	connp->conn_mlp_type = mlptSingle;
11561 
11562 	ipcl_hash_remove(connp);
11563 }
11564 
11565 /*
11566  * Used for deciding the MSS size for the upper layer. Thus
11567  * we need to check the outbound policy values in the conn.
11568  */
11569 int
11570 conn_ipsec_length(conn_t *connp)
11571 {
11572 	ipsec_latch_t *ipl;
11573 
11574 	ipl = connp->conn_latch;
11575 	if (ipl == NULL)
11576 		return (0);
11577 
11578 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11579 		return (0);
11580 
11581 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11582 }
11583 
11584 /*
11585  * Returns an estimate of the IPsec headers size. This is used if
11586  * we don't want to call into IPsec to get the exact size.
11587  */
11588 int
11589 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11590 {
11591 	ipsec_action_t *a;
11592 
11593 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11594 		return (0);
11595 
11596 	a = ixa->ixa_ipsec_action;
11597 	if (a == NULL) {
11598 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11599 		a = ixa->ixa_ipsec_policy->ipsp_act;
11600 	}
11601 	ASSERT(a != NULL);
11602 
11603 	return (a->ipa_ovhd);
11604 }
11605 
11606 /*
11607  * If there are any source route options, return the true final
11608  * destination. Otherwise, return the destination.
11609  */
11610 ipaddr_t
11611 ip_get_dst(ipha_t *ipha)
11612 {
11613 	ipoptp_t	opts;
11614 	uchar_t		*opt;
11615 	uint8_t		optval;
11616 	uint8_t		optlen;
11617 	ipaddr_t	dst;
11618 	uint32_t off;
11619 
11620 	dst = ipha->ipha_dst;
11621 
11622 	if (IS_SIMPLE_IPH(ipha))
11623 		return (dst);
11624 
11625 	for (optval = ipoptp_first(&opts, ipha);
11626 	    optval != IPOPT_EOL;
11627 	    optval = ipoptp_next(&opts)) {
11628 		opt = opts.ipoptp_cur;
11629 		optlen = opts.ipoptp_len;
11630 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11631 		switch (optval) {
11632 		case IPOPT_SSRR:
11633 		case IPOPT_LSRR:
11634 			off = opt[IPOPT_OFFSET];
11635 			/*
11636 			 * If one of the conditions is true, it means
11637 			 * end of options and dst already has the right
11638 			 * value.
11639 			 */
11640 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11641 				off = optlen - IP_ADDR_LEN;
11642 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11643 			}
11644 			return (dst);
11645 		default:
11646 			break;
11647 		}
11648 	}
11649 
11650 	return (dst);
11651 }
11652 
11653 /*
11654  * Outbound IP fragmentation routine.
11655  * Assumes the caller has checked whether or not fragmentation should
11656  * be allowed. Here we copy the DF bit from the header to all the generated
11657  * fragments.
11658  */
11659 int
11660 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11661     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11662     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11663 {
11664 	int		i1;
11665 	int		hdr_len;
11666 	mblk_t		*hdr_mp;
11667 	ipha_t		*ipha;
11668 	int		ip_data_end;
11669 	int		len;
11670 	mblk_t		*mp = mp_orig;
11671 	int		offset;
11672 	ill_t		*ill = nce->nce_ill;
11673 	ip_stack_t	*ipst = ill->ill_ipst;
11674 	mblk_t		*carve_mp;
11675 	uint32_t	frag_flag;
11676 	uint_t		priority = mp->b_band;
11677 	int		error = 0;
11678 
11679 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11680 
11681 	if (pkt_len != msgdsize(mp)) {
11682 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11683 		    pkt_len, msgdsize(mp)));
11684 		freemsg(mp);
11685 		return (EINVAL);
11686 	}
11687 
11688 	if (max_frag == 0) {
11689 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11690 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11691 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11692 		freemsg(mp);
11693 		return (EINVAL);
11694 	}
11695 
11696 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11697 	ipha = (ipha_t *)mp->b_rptr;
11698 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11699 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11700 
11701 	/*
11702 	 * Establish the starting offset.  May not be zero if we are fragging
11703 	 * a fragment that is being forwarded.
11704 	 */
11705 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11706 
11707 	/* TODO why is this test needed? */
11708 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11709 		/* TODO: notify ulp somehow */
11710 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11711 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11712 		freemsg(mp);
11713 		return (EINVAL);
11714 	}
11715 
11716 	hdr_len = IPH_HDR_LENGTH(ipha);
11717 	ipha->ipha_hdr_checksum = 0;
11718 
11719 	/*
11720 	 * Establish the number of bytes maximum per frag, after putting
11721 	 * in the header.
11722 	 */
11723 	len = (max_frag - hdr_len) & ~7;
11724 
11725 	/* Get a copy of the header for the trailing frags */
11726 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11727 	    mp);
11728 	if (hdr_mp == NULL) {
11729 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11730 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11731 		freemsg(mp);
11732 		return (ENOBUFS);
11733 	}
11734 
11735 	/* Store the starting offset, with the MoreFrags flag. */
11736 	i1 = offset | IPH_MF | frag_flag;
11737 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11738 
11739 	/* Establish the ending byte offset, based on the starting offset. */
11740 	offset <<= 3;
11741 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11742 
11743 	/* Store the length of the first fragment in the IP header. */
11744 	i1 = len + hdr_len;
11745 	ASSERT(i1 <= IP_MAXPACKET);
11746 	ipha->ipha_length = htons((uint16_t)i1);
11747 
11748 	/*
11749 	 * Compute the IP header checksum for the first frag.  We have to
11750 	 * watch out that we stop at the end of the header.
11751 	 */
11752 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11753 
11754 	/*
11755 	 * Now carve off the first frag.  Note that this will include the
11756 	 * original IP header.
11757 	 */
11758 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11759 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11760 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11761 		freeb(hdr_mp);
11762 		freemsg(mp_orig);
11763 		return (ENOBUFS);
11764 	}
11765 
11766 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11767 
11768 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11769 	    ixa_cookie);
11770 	if (error != 0 && error != EWOULDBLOCK) {
11771 		/* No point in sending the other fragments */
11772 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11773 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11774 		freeb(hdr_mp);
11775 		freemsg(mp_orig);
11776 		return (error);
11777 	}
11778 
11779 	/* No need to redo state machine in loop */
11780 	ixaflags &= ~IXAF_REACH_CONF;
11781 
11782 	/* Advance the offset to the second frag starting point. */
11783 	offset += len;
11784 	/*
11785 	 * Update hdr_len from the copied header - there might be less options
11786 	 * in the later fragments.
11787 	 */
11788 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11789 	/* Loop until done. */
11790 	for (;;) {
11791 		uint16_t	offset_and_flags;
11792 		uint16_t	ip_len;
11793 
11794 		if (ip_data_end - offset > len) {
11795 			/*
11796 			 * Carve off the appropriate amount from the original
11797 			 * datagram.
11798 			 */
11799 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11800 				mp = NULL;
11801 				break;
11802 			}
11803 			/*
11804 			 * More frags after this one.  Get another copy
11805 			 * of the header.
11806 			 */
11807 			if (carve_mp->b_datap->db_ref == 1 &&
11808 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11809 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11810 				/* Inline IP header */
11811 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11812 				    hdr_mp->b_rptr;
11813 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11814 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11815 				mp = carve_mp;
11816 			} else {
11817 				if (!(mp = copyb(hdr_mp))) {
11818 					freemsg(carve_mp);
11819 					break;
11820 				}
11821 				/* Get priority marking, if any. */
11822 				mp->b_band = priority;
11823 				mp->b_cont = carve_mp;
11824 			}
11825 			ipha = (ipha_t *)mp->b_rptr;
11826 			offset_and_flags = IPH_MF;
11827 		} else {
11828 			/*
11829 			 * Last frag.  Consume the header. Set len to
11830 			 * the length of this last piece.
11831 			 */
11832 			len = ip_data_end - offset;
11833 
11834 			/*
11835 			 * Carve off the appropriate amount from the original
11836 			 * datagram.
11837 			 */
11838 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11839 				mp = NULL;
11840 				break;
11841 			}
11842 			if (carve_mp->b_datap->db_ref == 1 &&
11843 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11844 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11845 				/* Inline IP header */
11846 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11847 				    hdr_mp->b_rptr;
11848 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11849 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11850 				mp = carve_mp;
11851 				freeb(hdr_mp);
11852 				hdr_mp = mp;
11853 			} else {
11854 				mp = hdr_mp;
11855 				/* Get priority marking, if any. */
11856 				mp->b_band = priority;
11857 				mp->b_cont = carve_mp;
11858 			}
11859 			ipha = (ipha_t *)mp->b_rptr;
11860 			/* A frag of a frag might have IPH_MF non-zero */
11861 			offset_and_flags =
11862 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11863 			    IPH_MF;
11864 		}
11865 		offset_and_flags |= (uint16_t)(offset >> 3);
11866 		offset_and_flags |= (uint16_t)frag_flag;
11867 		/* Store the offset and flags in the IP header. */
11868 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11869 
11870 		/* Store the length in the IP header. */
11871 		ip_len = (uint16_t)(len + hdr_len);
11872 		ipha->ipha_length = htons(ip_len);
11873 
11874 		/*
11875 		 * Set the IP header checksum.	Note that mp is just
11876 		 * the header, so this is easy to pass to ip_csum.
11877 		 */
11878 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11879 
11880 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11881 
11882 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11883 		    nolzid, ixa_cookie);
11884 		/* All done if we just consumed the hdr_mp. */
11885 		if (mp == hdr_mp) {
11886 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11887 			return (error);
11888 		}
11889 		if (error != 0 && error != EWOULDBLOCK) {
11890 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11891 			    mblk_t *, hdr_mp);
11892 			/* No point in sending the other fragments */
11893 			break;
11894 		}
11895 
11896 		/* Otherwise, advance and loop. */
11897 		offset += len;
11898 	}
11899 	/* Clean up following allocation failure. */
11900 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11901 	ip_drop_output("FragFails: loop ended", NULL, ill);
11902 	if (mp != hdr_mp)
11903 		freeb(hdr_mp);
11904 	if (mp != mp_orig)
11905 		freemsg(mp_orig);
11906 	return (error);
11907 }
11908 
11909 /*
11910  * Copy the header plus those options which have the copy bit set
11911  */
11912 static mblk_t *
11913 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11914     mblk_t *src)
11915 {
11916 	mblk_t	*mp;
11917 	uchar_t	*up;
11918 
11919 	/*
11920 	 * Quick check if we need to look for options without the copy bit
11921 	 * set
11922 	 */
11923 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11924 	if (!mp)
11925 		return (mp);
11926 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11927 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11928 		bcopy(rptr, mp->b_rptr, hdr_len);
11929 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11930 		return (mp);
11931 	}
11932 	up  = mp->b_rptr;
11933 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11934 	up += IP_SIMPLE_HDR_LENGTH;
11935 	rptr += IP_SIMPLE_HDR_LENGTH;
11936 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11937 	while (hdr_len > 0) {
11938 		uint32_t optval;
11939 		uint32_t optlen;
11940 
11941 		optval = *rptr;
11942 		if (optval == IPOPT_EOL)
11943 			break;
11944 		if (optval == IPOPT_NOP)
11945 			optlen = 1;
11946 		else
11947 			optlen = rptr[1];
11948 		if (optval & IPOPT_COPY) {
11949 			bcopy(rptr, up, optlen);
11950 			up += optlen;
11951 		}
11952 		rptr += optlen;
11953 		hdr_len -= optlen;
11954 	}
11955 	/*
11956 	 * Make sure that we drop an even number of words by filling
11957 	 * with EOL to the next word boundary.
11958 	 */
11959 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11960 	    hdr_len & 0x3; hdr_len++)
11961 		*up++ = IPOPT_EOL;
11962 	mp->b_wptr = up;
11963 	/* Update header length */
11964 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11965 	return (mp);
11966 }
11967 
11968 /*
11969  * Update any source route, record route, or timestamp options when
11970  * sending a packet back to ourselves.
11971  * Check that we are at end of strict source route.
11972  * The options have been sanity checked by ip_output_options().
11973  */
11974 void
11975 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11976 {
11977 	ipoptp_t	opts;
11978 	uchar_t		*opt;
11979 	uint8_t		optval;
11980 	uint8_t		optlen;
11981 	ipaddr_t	dst;
11982 	uint32_t	ts;
11983 	timestruc_t	now;
11984 	uint32_t	off = 0;
11985 
11986 	for (optval = ipoptp_first(&opts, ipha);
11987 	    optval != IPOPT_EOL;
11988 	    optval = ipoptp_next(&opts)) {
11989 		opt = opts.ipoptp_cur;
11990 		optlen = opts.ipoptp_len;
11991 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11992 		switch (optval) {
11993 		case IPOPT_SSRR:
11994 		case IPOPT_LSRR:
11995 			off = opt[IPOPT_OFFSET];
11996 			off--;
11997 			if (optlen < IP_ADDR_LEN ||
11998 			    off > optlen - IP_ADDR_LEN) {
11999 				/* End of source route */
12000 				break;
12001 			}
12002 			/*
12003 			 * This will only happen if two consecutive entries
12004 			 * in the source route contains our address or if
12005 			 * it is a packet with a loose source route which
12006 			 * reaches us before consuming the whole source route
12007 			 */
12008 
12009 			if (optval == IPOPT_SSRR) {
12010 				return;
12011 			}
12012 			/*
12013 			 * Hack: instead of dropping the packet truncate the
12014 			 * source route to what has been used by filling the
12015 			 * rest with IPOPT_NOP.
12016 			 */
12017 			opt[IPOPT_OLEN] = (uint8_t)off;
12018 			while (off < optlen) {
12019 				opt[off++] = IPOPT_NOP;
12020 			}
12021 			break;
12022 		case IPOPT_RR:
12023 			off = opt[IPOPT_OFFSET];
12024 			off--;
12025 			if (optlen < IP_ADDR_LEN ||
12026 			    off > optlen - IP_ADDR_LEN) {
12027 				/* No more room - ignore */
12028 				ip1dbg((
12029 				    "ip_output_local_options: end of RR\n"));
12030 				break;
12031 			}
12032 			dst = htonl(INADDR_LOOPBACK);
12033 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12034 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12035 			break;
12036 		case IPOPT_TS:
12037 			/* Insert timestamp if there is romm */
12038 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12039 			case IPOPT_TS_TSONLY:
12040 				off = IPOPT_TS_TIMELEN;
12041 				break;
12042 			case IPOPT_TS_PRESPEC:
12043 			case IPOPT_TS_PRESPEC_RFC791:
12044 				/* Verify that the address matched */
12045 				off = opt[IPOPT_OFFSET] - 1;
12046 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
12047 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
12048 					/* Not for us */
12049 					break;
12050 				}
12051 				/* FALLTHROUGH */
12052 			case IPOPT_TS_TSANDADDR:
12053 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12054 				break;
12055 			default:
12056 				/*
12057 				 * ip_*put_options should have already
12058 				 * dropped this packet.
12059 				 */
12060 				cmn_err(CE_PANIC, "ip_output_local_options: "
12061 				    "unknown IT - bug in ip_output_options?\n");
12062 			}
12063 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
12064 				/* Increase overflow counter */
12065 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
12066 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
12067 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
12068 				    (off << 4);
12069 				break;
12070 			}
12071 			off = opt[IPOPT_OFFSET] - 1;
12072 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12073 			case IPOPT_TS_PRESPEC:
12074 			case IPOPT_TS_PRESPEC_RFC791:
12075 			case IPOPT_TS_TSANDADDR:
12076 				dst = htonl(INADDR_LOOPBACK);
12077 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12078 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12079 				/* FALLTHROUGH */
12080 			case IPOPT_TS_TSONLY:
12081 				off = opt[IPOPT_OFFSET] - 1;
12082 				/* Compute # of milliseconds since midnight */
12083 				gethrestime(&now);
12084 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
12085 				    NSEC2MSEC(now.tv_nsec);
12086 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
12087 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
12088 				break;
12089 			}
12090 			break;
12091 		}
12092 	}
12093 }
12094 
12095 /*
12096  * Prepend an M_DATA fastpath header, and if none present prepend a
12097  * DL_UNITDATA_REQ. Frees the mblk on failure.
12098  *
12099  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12100  * If there is a change to them, the nce will be deleted (condemned) and
12101  * a new nce_t will be created when packets are sent. Thus we need no locks
12102  * to access those fields.
12103  *
12104  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12105  * we place b_band in dl_priority.dl_max.
12106  */
12107 static mblk_t *
12108 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12109 {
12110 	uint_t	hlen;
12111 	mblk_t *mp1;
12112 	uint_t	priority;
12113 	uchar_t *rptr;
12114 
12115 	rptr = mp->b_rptr;
12116 
12117 	ASSERT(DB_TYPE(mp) == M_DATA);
12118 	priority = mp->b_band;
12119 
12120 	ASSERT(nce != NULL);
12121 	if ((mp1 = nce->nce_fp_mp) != NULL) {
12122 		hlen = MBLKL(mp1);
12123 		/*
12124 		 * Check if we have enough room to prepend fastpath
12125 		 * header
12126 		 */
12127 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12128 			rptr -= hlen;
12129 			bcopy(mp1->b_rptr, rptr, hlen);
12130 			/*
12131 			 * Set the b_rptr to the start of the link layer
12132 			 * header
12133 			 */
12134 			mp->b_rptr = rptr;
12135 			return (mp);
12136 		}
12137 		mp1 = copyb(mp1);
12138 		if (mp1 == NULL) {
12139 			ill_t *ill = nce->nce_ill;
12140 
12141 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12142 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12143 			freemsg(mp);
12144 			return (NULL);
12145 		}
12146 		mp1->b_band = priority;
12147 		mp1->b_cont = mp;
12148 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12149 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12150 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12151 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12152 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12153 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12154 		/*
12155 		 * XXX disable ICK_VALID and compute checksum
12156 		 * here; can happen if nce_fp_mp changes and
12157 		 * it can't be copied now due to insufficient
12158 		 * space. (unlikely, fp mp can change, but it
12159 		 * does not increase in length)
12160 		 */
12161 		return (mp1);
12162 	}
12163 	mp1 = copyb(nce->nce_dlur_mp);
12164 
12165 	if (mp1 == NULL) {
12166 		ill_t *ill = nce->nce_ill;
12167 
12168 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12169 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12170 		freemsg(mp);
12171 		return (NULL);
12172 	}
12173 	mp1->b_cont = mp;
12174 	if (priority != 0) {
12175 		mp1->b_band = priority;
12176 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12177 		    priority;
12178 	}
12179 	return (mp1);
12180 }
12181 
12182 /*
12183  * Finish the outbound IPsec processing. This function is called from
12184  * ipsec_out_process() if the IPsec packet was processed
12185  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12186  * asynchronously.
12187  *
12188  * This is common to IPv4 and IPv6.
12189  */
12190 int
12191 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12192 {
12193 	iaflags_t	ixaflags = ixa->ixa_flags;
12194 	uint_t		pktlen;
12195 
12196 
12197 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12198 	if (ixaflags & IXAF_IS_IPV4) {
12199 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12200 
12201 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12202 		pktlen = ntohs(ipha->ipha_length);
12203 	} else {
12204 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12205 
12206 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12207 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12208 	}
12209 
12210 	/*
12211 	 * We release any hard reference on the SAs here to make
12212 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12213 	 * on the SAs.
12214 	 * If in the future we want the hard latching of the SAs in the
12215 	 * ip_xmit_attr_t then we should remove this.
12216 	 */
12217 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12218 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12219 		ixa->ixa_ipsec_esp_sa = NULL;
12220 	}
12221 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12222 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12223 		ixa->ixa_ipsec_ah_sa = NULL;
12224 	}
12225 
12226 	/* Do we need to fragment? */
12227 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12228 	    pktlen > ixa->ixa_fragsize) {
12229 		if (ixaflags & IXAF_IS_IPV4) {
12230 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12231 			/*
12232 			 * We check for the DF case in ipsec_out_process
12233 			 * hence this only handles the non-DF case.
12234 			 */
12235 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12236 			    pktlen, ixa->ixa_fragsize,
12237 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12238 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12239 			    &ixa->ixa_cookie));
12240 		} else {
12241 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12242 			if (mp == NULL) {
12243 				/* MIB and ip_drop_output already done */
12244 				return (ENOMEM);
12245 			}
12246 			pktlen += sizeof (ip6_frag_t);
12247 			if (pktlen > ixa->ixa_fragsize) {
12248 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12249 				    ixa->ixa_flags, pktlen,
12250 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12251 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12252 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12253 			}
12254 		}
12255 	}
12256 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12257 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12258 	    ixa->ixa_no_loop_zoneid, NULL));
12259 }
12260 
12261 /*
12262  * Finish the inbound IPsec processing. This function is called from
12263  * ipsec_out_process() if the IPsec packet was processed
12264  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12265  * asynchronously.
12266  *
12267  * This is common to IPv4 and IPv6.
12268  */
12269 void
12270 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12271 {
12272 	iaflags_t	iraflags = ira->ira_flags;
12273 
12274 	/* Length might have changed */
12275 	if (iraflags & IRAF_IS_IPV4) {
12276 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12277 
12278 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12279 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12280 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12281 		ira->ira_protocol = ipha->ipha_protocol;
12282 
12283 		ip_fanout_v4(mp, ipha, ira);
12284 	} else {
12285 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12286 		uint8_t		*nexthdrp;
12287 
12288 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12289 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12290 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12291 		    &nexthdrp)) {
12292 			/* Malformed packet */
12293 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12294 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12295 			freemsg(mp);
12296 			return;
12297 		}
12298 		ira->ira_protocol = *nexthdrp;
12299 		ip_fanout_v6(mp, ip6h, ira);
12300 	}
12301 }
12302 
12303 /*
12304  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12305  *
12306  * If this function returns B_TRUE, the requested SA's have been filled
12307  * into the ixa_ipsec_*_sa pointers.
12308  *
12309  * If the function returns B_FALSE, the packet has been "consumed", most
12310  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12311  *
12312  * The SA references created by the protocol-specific "select"
12313  * function will be released in ip_output_post_ipsec.
12314  */
12315 static boolean_t
12316 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12317 {
12318 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12319 	ipsec_policy_t *pp;
12320 	ipsec_action_t *ap;
12321 
12322 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12323 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12324 	    (ixa->ixa_ipsec_action != NULL));
12325 
12326 	ap = ixa->ixa_ipsec_action;
12327 	if (ap == NULL) {
12328 		pp = ixa->ixa_ipsec_policy;
12329 		ASSERT(pp != NULL);
12330 		ap = pp->ipsp_act;
12331 		ASSERT(ap != NULL);
12332 	}
12333 
12334 	/*
12335 	 * We have an action.  now, let's select SA's.
12336 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12337 	 * be cached in the conn_t.
12338 	 */
12339 	if (ap->ipa_want_esp) {
12340 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12341 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12342 			    IPPROTO_ESP);
12343 		}
12344 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12345 	}
12346 
12347 	if (ap->ipa_want_ah) {
12348 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12349 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12350 			    IPPROTO_AH);
12351 		}
12352 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12353 		/*
12354 		 * The ESP and AH processing order needs to be preserved
12355 		 * when both protocols are required (ESP should be applied
12356 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12357 		 * when both ESP and AH are required, and an AH ACQUIRE
12358 		 * is needed.
12359 		 */
12360 		if (ap->ipa_want_esp && need_ah_acquire)
12361 			need_esp_acquire = B_TRUE;
12362 	}
12363 
12364 	/*
12365 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12366 	 * Release SAs that got referenced, but will not be used until we
12367 	 * acquire _all_ of the SAs we need.
12368 	 */
12369 	if (need_ah_acquire || need_esp_acquire) {
12370 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12371 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12372 			ixa->ixa_ipsec_ah_sa = NULL;
12373 		}
12374 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12375 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12376 			ixa->ixa_ipsec_esp_sa = NULL;
12377 		}
12378 
12379 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12380 		return (B_FALSE);
12381 	}
12382 
12383 	return (B_TRUE);
12384 }
12385 
12386 /*
12387  * Handle IPsec output processing.
12388  * This function is only entered once for a given packet.
12389  * We try to do things synchronously, but if we need to have user-level
12390  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12391  * will be completed
12392  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12393  *  - when asynchronous ESP is done it will do AH
12394  *
12395  * In all cases we come back in ip_output_post_ipsec() to fragment and
12396  * send out the packet.
12397  */
12398 int
12399 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12400 {
12401 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12402 	ip_stack_t	*ipst = ixa->ixa_ipst;
12403 	ipsec_stack_t	*ipss;
12404 	ipsec_policy_t	*pp;
12405 	ipsec_action_t	*ap;
12406 
12407 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12408 
12409 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12410 	    (ixa->ixa_ipsec_action != NULL));
12411 
12412 	ipss = ipst->ips_netstack->netstack_ipsec;
12413 	if (!ipsec_loaded(ipss)) {
12414 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12415 		ip_drop_packet(mp, B_TRUE, ill,
12416 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12417 		    &ipss->ipsec_dropper);
12418 		return (ENOTSUP);
12419 	}
12420 
12421 	ap = ixa->ixa_ipsec_action;
12422 	if (ap == NULL) {
12423 		pp = ixa->ixa_ipsec_policy;
12424 		ASSERT(pp != NULL);
12425 		ap = pp->ipsp_act;
12426 		ASSERT(ap != NULL);
12427 	}
12428 
12429 	/* Handle explicit drop action and bypass. */
12430 	switch (ap->ipa_act.ipa_type) {
12431 	case IPSEC_ACT_DISCARD:
12432 	case IPSEC_ACT_REJECT:
12433 		ip_drop_packet(mp, B_FALSE, ill,
12434 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12435 		return (EHOSTUNREACH);	/* IPsec policy failure */
12436 	case IPSEC_ACT_BYPASS:
12437 		return (ip_output_post_ipsec(mp, ixa));
12438 	}
12439 
12440 	/*
12441 	 * The order of processing is first insert a IP header if needed.
12442 	 * Then insert the ESP header and then the AH header.
12443 	 */
12444 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12445 		/*
12446 		 * First get the outer IP header before sending
12447 		 * it to ESP.
12448 		 */
12449 		ipha_t *oipha, *iipha;
12450 		mblk_t *outer_mp, *inner_mp;
12451 
12452 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12453 			(void) mi_strlog(ill->ill_rq, 0,
12454 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12455 			    "ipsec_out_process: "
12456 			    "Self-Encapsulation failed: Out of memory\n");
12457 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12458 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12459 			freemsg(mp);
12460 			return (ENOBUFS);
12461 		}
12462 		inner_mp = mp;
12463 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12464 		oipha = (ipha_t *)outer_mp->b_rptr;
12465 		iipha = (ipha_t *)inner_mp->b_rptr;
12466 		*oipha = *iipha;
12467 		outer_mp->b_wptr += sizeof (ipha_t);
12468 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12469 		    sizeof (ipha_t));
12470 		oipha->ipha_protocol = IPPROTO_ENCAP;
12471 		oipha->ipha_version_and_hdr_length =
12472 		    IP_SIMPLE_HDR_VERSION;
12473 		oipha->ipha_hdr_checksum = 0;
12474 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12475 		outer_mp->b_cont = inner_mp;
12476 		mp = outer_mp;
12477 
12478 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12479 	}
12480 
12481 	/* If we need to wait for a SA then we can't return any errno */
12482 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12483 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12484 	    !ipsec_out_select_sa(mp, ixa))
12485 		return (0);
12486 
12487 	/*
12488 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12489 	 * to do the heavy lifting.
12490 	 */
12491 	if (ap->ipa_want_esp) {
12492 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12493 
12494 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12495 		if (mp == NULL) {
12496 			/*
12497 			 * Either it failed or is pending. In the former case
12498 			 * ipIfStatsInDiscards was increased.
12499 			 */
12500 			return (0);
12501 		}
12502 	}
12503 
12504 	if (ap->ipa_want_ah) {
12505 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12506 
12507 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12508 		if (mp == NULL) {
12509 			/*
12510 			 * Either it failed or is pending. In the former case
12511 			 * ipIfStatsInDiscards was increased.
12512 			 */
12513 			return (0);
12514 		}
12515 	}
12516 	/*
12517 	 * We are done with IPsec processing. Send it over
12518 	 * the wire.
12519 	 */
12520 	return (ip_output_post_ipsec(mp, ixa));
12521 }
12522 
12523 /*
12524  * ioctls that go through a down/up sequence may need to wait for the down
12525  * to complete. This involves waiting for the ire and ipif refcnts to go down
12526  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12527  */
12528 /* ARGSUSED */
12529 void
12530 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12531 {
12532 	struct iocblk *iocp;
12533 	mblk_t *mp1;
12534 	ip_ioctl_cmd_t *ipip;
12535 	int err;
12536 	sin_t	*sin;
12537 	struct lifreq *lifr;
12538 	struct ifreq *ifr;
12539 
12540 	iocp = (struct iocblk *)mp->b_rptr;
12541 	ASSERT(ipsq != NULL);
12542 	/* Existence of mp1 verified in ip_wput_nondata */
12543 	mp1 = mp->b_cont->b_cont;
12544 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12545 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12546 		/*
12547 		 * Special case where ipx_current_ipif is not set:
12548 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12549 		 * We are here as were not able to complete the operation in
12550 		 * ipif_set_values because we could not become exclusive on
12551 		 * the new ipsq.
12552 		 */
12553 		ill_t *ill = q->q_ptr;
12554 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12555 	}
12556 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12557 
12558 	if (ipip->ipi_cmd_type == IF_CMD) {
12559 		/* This a old style SIOC[GS]IF* command */
12560 		ifr = (struct ifreq *)mp1->b_rptr;
12561 		sin = (sin_t *)&ifr->ifr_addr;
12562 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12563 		/* This a new style SIOC[GS]LIF* command */
12564 		lifr = (struct lifreq *)mp1->b_rptr;
12565 		sin = (sin_t *)&lifr->lifr_addr;
12566 	} else {
12567 		sin = NULL;
12568 	}
12569 
12570 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12571 	    q, mp, ipip, mp1->b_rptr);
12572 
12573 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12574 	    int, ipip->ipi_cmd,
12575 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12576 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12577 
12578 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12579 }
12580 
12581 /*
12582  * ioctl processing
12583  *
12584  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12585  * the ioctl command in the ioctl tables, determines the copyin data size
12586  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12587  *
12588  * ioctl processing then continues when the M_IOCDATA makes its way down to
12589  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12590  * associated 'conn' is refheld till the end of the ioctl and the general
12591  * ioctl processing function ip_process_ioctl() is called to extract the
12592  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12593  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12594  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12595  * is used to extract the ioctl's arguments.
12596  *
12597  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12598  * so goes thru the serialization primitive ipsq_try_enter. Then the
12599  * appropriate function to handle the ioctl is called based on the entry in
12600  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12601  * which also refreleases the 'conn' that was refheld at the start of the
12602  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12603  *
12604  * Many exclusive ioctls go thru an internal down up sequence as part of
12605  * the operation. For example an attempt to change the IP address of an
12606  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12607  * does all the cleanup such as deleting all ires that use this address.
12608  * Then we need to wait till all references to the interface go away.
12609  */
12610 void
12611 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12612 {
12613 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12614 	ip_ioctl_cmd_t *ipip = arg;
12615 	ip_extract_func_t *extract_funcp;
12616 	cmd_info_t ci;
12617 	int err;
12618 	boolean_t entered_ipsq = B_FALSE;
12619 
12620 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12621 
12622 	if (ipip == NULL)
12623 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12624 
12625 	/*
12626 	 * SIOCLIFADDIF needs to go thru a special path since the
12627 	 * ill may not exist yet. This happens in the case of lo0
12628 	 * which is created using this ioctl.
12629 	 */
12630 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12631 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12632 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12633 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12634 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12635 		return;
12636 	}
12637 
12638 	ci.ci_ipif = NULL;
12639 	extract_funcp = NULL;
12640 	switch (ipip->ipi_cmd_type) {
12641 	case MISC_CMD:
12642 	case MSFILT_CMD:
12643 		/*
12644 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12645 		 */
12646 		if (ipip->ipi_cmd == IF_UNITSEL) {
12647 			/* ioctl comes down the ill */
12648 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12649 			ipif_refhold(ci.ci_ipif);
12650 		}
12651 		err = 0;
12652 		ci.ci_sin = NULL;
12653 		ci.ci_sin6 = NULL;
12654 		ci.ci_lifr = NULL;
12655 		extract_funcp = NULL;
12656 		break;
12657 
12658 	case IF_CMD:
12659 	case LIF_CMD:
12660 		extract_funcp = ip_extract_lifreq;
12661 		break;
12662 
12663 	case ARP_CMD:
12664 	case XARP_CMD:
12665 		extract_funcp = ip_extract_arpreq;
12666 		break;
12667 
12668 	default:
12669 		ASSERT(0);
12670 	}
12671 
12672 	if (extract_funcp != NULL) {
12673 		err = (*extract_funcp)(q, mp, ipip, &ci);
12674 		if (err != 0) {
12675 			DTRACE_PROBE4(ipif__ioctl,
12676 			    char *, "ip_process_ioctl finish err",
12677 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12678 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12679 			return;
12680 		}
12681 
12682 		/*
12683 		 * All of the extraction functions return a refheld ipif.
12684 		 */
12685 		ASSERT(ci.ci_ipif != NULL);
12686 	}
12687 
12688 	if (!(ipip->ipi_flags & IPI_WR)) {
12689 		/*
12690 		 * A return value of EINPROGRESS means the ioctl is
12691 		 * either queued and waiting for some reason or has
12692 		 * already completed.
12693 		 */
12694 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12695 		    ci.ci_lifr);
12696 		if (ci.ci_ipif != NULL) {
12697 			DTRACE_PROBE4(ipif__ioctl,
12698 			    char *, "ip_process_ioctl finish RD",
12699 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12700 			    ipif_t *, ci.ci_ipif);
12701 			ipif_refrele(ci.ci_ipif);
12702 		} else {
12703 			DTRACE_PROBE4(ipif__ioctl,
12704 			    char *, "ip_process_ioctl finish RD",
12705 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12706 		}
12707 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12708 		return;
12709 	}
12710 
12711 	ASSERT(ci.ci_ipif != NULL);
12712 
12713 	/*
12714 	 * If ipsq is non-NULL, we are already being called exclusively
12715 	 */
12716 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12717 	if (ipsq == NULL) {
12718 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12719 		    NEW_OP, B_TRUE);
12720 		if (ipsq == NULL) {
12721 			ipif_refrele(ci.ci_ipif);
12722 			return;
12723 		}
12724 		entered_ipsq = B_TRUE;
12725 	}
12726 	/*
12727 	 * Release the ipif so that ipif_down and friends that wait for
12728 	 * references to go away are not misled about the current ipif_refcnt
12729 	 * values. We are writer so we can access the ipif even after releasing
12730 	 * the ipif.
12731 	 */
12732 	ipif_refrele(ci.ci_ipif);
12733 
12734 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12735 
12736 	/*
12737 	 * A return value of EINPROGRESS means the ioctl is
12738 	 * either queued and waiting for some reason or has
12739 	 * already completed.
12740 	 */
12741 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12742 
12743 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12744 	    int, ipip->ipi_cmd,
12745 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12746 	    ipif_t *, ci.ci_ipif);
12747 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12748 
12749 	if (entered_ipsq)
12750 		ipsq_exit(ipsq);
12751 }
12752 
12753 /*
12754  * Complete the ioctl. Typically ioctls use the mi package and need to
12755  * do mi_copyout/mi_copy_done.
12756  */
12757 void
12758 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12759 {
12760 	conn_t	*connp = NULL;
12761 
12762 	if (err == EINPROGRESS)
12763 		return;
12764 
12765 	if (CONN_Q(q)) {
12766 		connp = Q_TO_CONN(q);
12767 		ASSERT(connp->conn_ref >= 2);
12768 	}
12769 
12770 	switch (mode) {
12771 	case COPYOUT:
12772 		if (err == 0)
12773 			mi_copyout(q, mp);
12774 		else
12775 			mi_copy_done(q, mp, err);
12776 		break;
12777 
12778 	case NO_COPYOUT:
12779 		mi_copy_done(q, mp, err);
12780 		break;
12781 
12782 	default:
12783 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12784 		break;
12785 	}
12786 
12787 	/*
12788 	 * The conn refhold and ioctlref placed on the conn at the start of the
12789 	 * ioctl are released here.
12790 	 */
12791 	if (connp != NULL) {
12792 		CONN_DEC_IOCTLREF(connp);
12793 		CONN_OPER_PENDING_DONE(connp);
12794 	}
12795 
12796 	if (ipsq != NULL)
12797 		ipsq_current_finish(ipsq);
12798 }
12799 
12800 /* Handles all non data messages */
12801 int
12802 ip_wput_nondata(queue_t *q, mblk_t *mp)
12803 {
12804 	mblk_t		*mp1;
12805 	struct iocblk	*iocp;
12806 	ip_ioctl_cmd_t	*ipip;
12807 	conn_t		*connp;
12808 	cred_t		*cr;
12809 	char		*proto_str;
12810 
12811 	if (CONN_Q(q))
12812 		connp = Q_TO_CONN(q);
12813 	else
12814 		connp = NULL;
12815 
12816 	iocp = NULL;
12817 	switch (DB_TYPE(mp)) {
12818 	case M_IOCTL:
12819 		/*
12820 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12821 		 * will arrange to copy in associated control structures.
12822 		 */
12823 		ip_sioctl_copyin_setup(q, mp);
12824 		return (0);
12825 	case M_IOCDATA:
12826 		/*
12827 		 * Ensure that this is associated with one of our trans-
12828 		 * parent ioctls.  If it's not ours, discard it if we're
12829 		 * running as a driver, or pass it on if we're a module.
12830 		 */
12831 		iocp = (struct iocblk *)mp->b_rptr;
12832 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12833 		if (ipip == NULL) {
12834 			if (q->q_next == NULL) {
12835 				goto nak;
12836 			} else {
12837 				putnext(q, mp);
12838 			}
12839 			return (0);
12840 		}
12841 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12842 			/*
12843 			 * The ioctl is one we recognise, but is not consumed
12844 			 * by IP as a module and we are a module, so we drop
12845 			 */
12846 			goto nak;
12847 		}
12848 
12849 		/* IOCTL continuation following copyin or copyout. */
12850 		if (mi_copy_state(q, mp, NULL) == -1) {
12851 			/*
12852 			 * The copy operation failed.  mi_copy_state already
12853 			 * cleaned up, so we're out of here.
12854 			 */
12855 			return (0);
12856 		}
12857 		/*
12858 		 * If we just completed a copy in, we become writer and
12859 		 * continue processing in ip_sioctl_copyin_done.  If it
12860 		 * was a copy out, we call mi_copyout again.  If there is
12861 		 * nothing more to copy out, it will complete the IOCTL.
12862 		 */
12863 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12864 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12865 				mi_copy_done(q, mp, EPROTO);
12866 				return (0);
12867 			}
12868 			/*
12869 			 * Check for cases that need more copying.  A return
12870 			 * value of 0 means a second copyin has been started,
12871 			 * so we return; a return value of 1 means no more
12872 			 * copying is needed, so we continue.
12873 			 */
12874 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12875 			    MI_COPY_COUNT(mp) == 1) {
12876 				if (ip_copyin_msfilter(q, mp) == 0)
12877 					return (0);
12878 			}
12879 			/*
12880 			 * Refhold the conn, till the ioctl completes. This is
12881 			 * needed in case the ioctl ends up in the pending mp
12882 			 * list. Every mp in the ipx_pending_mp list must have
12883 			 * a refhold on the conn to resume processing. The
12884 			 * refhold is released when the ioctl completes
12885 			 * (whether normally or abnormally). An ioctlref is also
12886 			 * placed on the conn to prevent TCP from removing the
12887 			 * queue needed to send the ioctl reply back.
12888 			 * In all cases ip_ioctl_finish is called to finish
12889 			 * the ioctl and release the refholds.
12890 			 */
12891 			if (connp != NULL) {
12892 				/* This is not a reentry */
12893 				CONN_INC_REF(connp);
12894 				CONN_INC_IOCTLREF(connp);
12895 			} else {
12896 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12897 					mi_copy_done(q, mp, EINVAL);
12898 					return (0);
12899 				}
12900 			}
12901 
12902 			ip_process_ioctl(NULL, q, mp, ipip);
12903 
12904 		} else {
12905 			mi_copyout(q, mp);
12906 		}
12907 		return (0);
12908 
12909 	case M_IOCNAK:
12910 		/*
12911 		 * The only way we could get here is if a resolver didn't like
12912 		 * an IOCTL we sent it.	 This shouldn't happen.
12913 		 */
12914 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12915 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12916 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12917 		freemsg(mp);
12918 		return (0);
12919 	case M_IOCACK:
12920 		/* /dev/ip shouldn't see this */
12921 		goto nak;
12922 	case M_FLUSH:
12923 		if (*mp->b_rptr & FLUSHW)
12924 			flushq(q, FLUSHALL);
12925 		if (q->q_next) {
12926 			putnext(q, mp);
12927 			return (0);
12928 		}
12929 		if (*mp->b_rptr & FLUSHR) {
12930 			*mp->b_rptr &= ~FLUSHW;
12931 			qreply(q, mp);
12932 			return (0);
12933 		}
12934 		freemsg(mp);
12935 		return (0);
12936 	case M_CTL:
12937 		break;
12938 	case M_PROTO:
12939 	case M_PCPROTO:
12940 		/*
12941 		 * The only PROTO messages we expect are SNMP-related.
12942 		 */
12943 		switch (((union T_primitives *)mp->b_rptr)->type) {
12944 		case T_SVR4_OPTMGMT_REQ:
12945 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12946 			    "flags %x\n",
12947 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12948 
12949 			if (connp == NULL) {
12950 				proto_str = "T_SVR4_OPTMGMT_REQ";
12951 				goto protonak;
12952 			}
12953 
12954 			/*
12955 			 * All Solaris components should pass a db_credp
12956 			 * for this TPI message, hence we ASSERT.
12957 			 * But in case there is some other M_PROTO that looks
12958 			 * like a TPI message sent by some other kernel
12959 			 * component, we check and return an error.
12960 			 */
12961 			cr = msg_getcred(mp, NULL);
12962 			ASSERT(cr != NULL);
12963 			if (cr == NULL) {
12964 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12965 				if (mp != NULL)
12966 					qreply(q, mp);
12967 				return (0);
12968 			}
12969 
12970 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12971 				proto_str = "Bad SNMPCOM request?";
12972 				goto protonak;
12973 			}
12974 			return (0);
12975 		default:
12976 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12977 			    (int)*(uint_t *)mp->b_rptr));
12978 			freemsg(mp);
12979 			return (0);
12980 		}
12981 	default:
12982 		break;
12983 	}
12984 	if (q->q_next) {
12985 		putnext(q, mp);
12986 	} else
12987 		freemsg(mp);
12988 	return (0);
12989 
12990 nak:
12991 	iocp->ioc_error = EINVAL;
12992 	mp->b_datap->db_type = M_IOCNAK;
12993 	iocp->ioc_count = 0;
12994 	qreply(q, mp);
12995 	return (0);
12996 
12997 protonak:
12998 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12999 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
13000 		qreply(q, mp);
13001 	return (0);
13002 }
13003 
13004 /*
13005  * Process IP options in an outbound packet.  Verify that the nexthop in a
13006  * strict source route is onlink.
13007  * Returns non-zero if something fails in which case an ICMP error has been
13008  * sent and mp freed.
13009  *
13010  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
13011  */
13012 int
13013 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
13014 {
13015 	ipoptp_t	opts;
13016 	uchar_t		*opt;
13017 	uint8_t		optval;
13018 	uint8_t		optlen;
13019 	ipaddr_t	dst;
13020 	intptr_t	code = 0;
13021 	ire_t		*ire;
13022 	ip_stack_t	*ipst = ixa->ixa_ipst;
13023 	ip_recv_attr_t	iras;
13024 
13025 	ip2dbg(("ip_output_options\n"));
13026 
13027 	opt = NULL;
13028 	dst = ipha->ipha_dst;
13029 	for (optval = ipoptp_first(&opts, ipha);
13030 	    optval != IPOPT_EOL;
13031 	    optval = ipoptp_next(&opts)) {
13032 		opt = opts.ipoptp_cur;
13033 		optlen = opts.ipoptp_len;
13034 		ip2dbg(("ip_output_options: opt %d, len %d\n",
13035 		    optval, optlen));
13036 		switch (optval) {
13037 			uint32_t off;
13038 		case IPOPT_SSRR:
13039 		case IPOPT_LSRR:
13040 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13041 				ip1dbg((
13042 				    "ip_output_options: bad option offset\n"));
13043 				code = (char *)&opt[IPOPT_OLEN] -
13044 				    (char *)ipha;
13045 				goto param_prob;
13046 			}
13047 			off = opt[IPOPT_OFFSET];
13048 			ip1dbg(("ip_output_options: next hop 0x%x\n",
13049 			    ntohl(dst)));
13050 			/*
13051 			 * For strict: verify that dst is directly
13052 			 * reachable.
13053 			 */
13054 			if (optval == IPOPT_SSRR) {
13055 				ire = ire_ftable_lookup_v4(dst, 0, 0,
13056 				    IRE_INTERFACE, NULL, ALL_ZONES,
13057 				    ixa->ixa_tsl,
13058 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
13059 				    NULL);
13060 				if (ire == NULL) {
13061 					ip1dbg(("ip_output_options: SSRR not"
13062 					    " directly reachable: 0x%x\n",
13063 					    ntohl(dst)));
13064 					goto bad_src_route;
13065 				}
13066 				ire_refrele(ire);
13067 			}
13068 			break;
13069 		case IPOPT_RR:
13070 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13071 				ip1dbg((
13072 				    "ip_output_options: bad option offset\n"));
13073 				code = (char *)&opt[IPOPT_OLEN] -
13074 				    (char *)ipha;
13075 				goto param_prob;
13076 			}
13077 			break;
13078 		case IPOPT_TS:
13079 			/*
13080 			 * Verify that length >=5 and that there is either
13081 			 * room for another timestamp or that the overflow
13082 			 * counter is not maxed out.
13083 			 */
13084 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
13085 			if (optlen < IPOPT_MINLEN_IT) {
13086 				goto param_prob;
13087 			}
13088 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13089 				ip1dbg((
13090 				    "ip_output_options: bad option offset\n"));
13091 				code = (char *)&opt[IPOPT_OFFSET] -
13092 				    (char *)ipha;
13093 				goto param_prob;
13094 			}
13095 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13096 			case IPOPT_TS_TSONLY:
13097 				off = IPOPT_TS_TIMELEN;
13098 				break;
13099 			case IPOPT_TS_TSANDADDR:
13100 			case IPOPT_TS_PRESPEC:
13101 			case IPOPT_TS_PRESPEC_RFC791:
13102 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13103 				break;
13104 			default:
13105 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
13106 				    (char *)ipha;
13107 				goto param_prob;
13108 			}
13109 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13110 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13111 				/*
13112 				 * No room and the overflow counter is 15
13113 				 * already.
13114 				 */
13115 				goto param_prob;
13116 			}
13117 			break;
13118 		}
13119 	}
13120 
13121 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13122 		return (0);
13123 
13124 	ip1dbg(("ip_output_options: error processing IP options."));
13125 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13126 
13127 param_prob:
13128 	bzero(&iras, sizeof (iras));
13129 	iras.ira_ill = iras.ira_rill = ill;
13130 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13131 	iras.ira_rifindex = iras.ira_ruifindex;
13132 	iras.ira_flags = IRAF_IS_IPV4;
13133 
13134 	ip_drop_output("ip_output_options", mp, ill);
13135 	icmp_param_problem(mp, (uint8_t)code, &iras);
13136 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13137 	return (-1);
13138 
13139 bad_src_route:
13140 	bzero(&iras, sizeof (iras));
13141 	iras.ira_ill = iras.ira_rill = ill;
13142 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13143 	iras.ira_rifindex = iras.ira_ruifindex;
13144 	iras.ira_flags = IRAF_IS_IPV4;
13145 
13146 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13147 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13148 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13149 	return (-1);
13150 }
13151 
13152 /*
13153  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13154  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13155  * thru /etc/system.
13156  */
13157 #define	CONN_MAXDRAINCNT	64
13158 
13159 static void
13160 conn_drain_init(ip_stack_t *ipst)
13161 {
13162 	int i, j;
13163 	idl_tx_list_t *itl_tx;
13164 
13165 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13166 
13167 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
13168 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13169 		/*
13170 		 * Default value of the number of drainers is the
13171 		 * number of cpus, subject to maximum of 8 drainers.
13172 		 */
13173 		if (boot_max_ncpus != -1)
13174 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13175 		else
13176 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13177 	}
13178 
13179 	ipst->ips_idl_tx_list =
13180 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13181 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13182 		itl_tx =  &ipst->ips_idl_tx_list[i];
13183 		itl_tx->txl_drain_list =
13184 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13185 		    sizeof (idl_t), KM_SLEEP);
13186 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13187 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13188 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13189 			    MUTEX_DEFAULT, NULL);
13190 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13191 		}
13192 	}
13193 }
13194 
13195 static void
13196 conn_drain_fini(ip_stack_t *ipst)
13197 {
13198 	int i;
13199 	idl_tx_list_t *itl_tx;
13200 
13201 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13202 		itl_tx =  &ipst->ips_idl_tx_list[i];
13203 		kmem_free(itl_tx->txl_drain_list,
13204 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13205 	}
13206 	kmem_free(ipst->ips_idl_tx_list,
13207 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13208 	ipst->ips_idl_tx_list = NULL;
13209 }
13210 
13211 /*
13212  * Flow control has blocked us from proceeding.  Insert the given conn in one
13213  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13214  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13215  * will call conn_walk_drain().  See the flow control notes at the top of this
13216  * file for more details.
13217  */
13218 void
13219 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13220 {
13221 	idl_t	*idl = tx_list->txl_drain_list;
13222 	uint_t	index;
13223 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13224 
13225 	mutex_enter(&connp->conn_lock);
13226 	if (connp->conn_state_flags & CONN_CLOSING) {
13227 		/*
13228 		 * The conn is closing as a result of which CONN_CLOSING
13229 		 * is set. Return.
13230 		 */
13231 		mutex_exit(&connp->conn_lock);
13232 		return;
13233 	} else if (connp->conn_idl == NULL) {
13234 		/*
13235 		 * Assign the next drain list round robin. We dont' use
13236 		 * a lock, and thus it may not be strictly round robin.
13237 		 * Atomicity of load/stores is enough to make sure that
13238 		 * conn_drain_list_index is always within bounds.
13239 		 */
13240 		index = tx_list->txl_drain_index;
13241 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13242 		connp->conn_idl = &tx_list->txl_drain_list[index];
13243 		index++;
13244 		if (index == ipst->ips_conn_drain_list_cnt)
13245 			index = 0;
13246 		tx_list->txl_drain_index = index;
13247 	} else {
13248 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13249 	}
13250 	mutex_exit(&connp->conn_lock);
13251 
13252 	idl = connp->conn_idl;
13253 	mutex_enter(&idl->idl_lock);
13254 	if ((connp->conn_drain_prev != NULL) ||
13255 	    (connp->conn_state_flags & CONN_CLOSING)) {
13256 		/*
13257 		 * The conn is either already in the drain list or closing.
13258 		 * (We needed to check for CONN_CLOSING again since close can
13259 		 * sneak in between dropping conn_lock and acquiring idl_lock.)
13260 		 */
13261 		mutex_exit(&idl->idl_lock);
13262 		return;
13263 	}
13264 
13265 	/*
13266 	 * The conn is not in the drain list. Insert it at the
13267 	 * tail of the drain list. The drain list is circular
13268 	 * and doubly linked. idl_conn points to the 1st element
13269 	 * in the list.
13270 	 */
13271 	if (idl->idl_conn == NULL) {
13272 		idl->idl_conn = connp;
13273 		connp->conn_drain_next = connp;
13274 		connp->conn_drain_prev = connp;
13275 	} else {
13276 		conn_t *head = idl->idl_conn;
13277 
13278 		connp->conn_drain_next = head;
13279 		connp->conn_drain_prev = head->conn_drain_prev;
13280 		head->conn_drain_prev->conn_drain_next = connp;
13281 		head->conn_drain_prev = connp;
13282 	}
13283 	/*
13284 	 * For non streams based sockets assert flow control.
13285 	 */
13286 	conn_setqfull(connp, NULL);
13287 	mutex_exit(&idl->idl_lock);
13288 }
13289 
13290 static void
13291 conn_drain_remove(conn_t *connp)
13292 {
13293 	idl_t *idl = connp->conn_idl;
13294 
13295 	if (idl != NULL) {
13296 		/*
13297 		 * Remove ourself from the drain list.
13298 		 */
13299 		if (connp->conn_drain_next == connp) {
13300 			/* Singleton in the list */
13301 			ASSERT(connp->conn_drain_prev == connp);
13302 			idl->idl_conn = NULL;
13303 		} else {
13304 			connp->conn_drain_prev->conn_drain_next =
13305 			    connp->conn_drain_next;
13306 			connp->conn_drain_next->conn_drain_prev =
13307 			    connp->conn_drain_prev;
13308 			if (idl->idl_conn == connp)
13309 				idl->idl_conn = connp->conn_drain_next;
13310 		}
13311 
13312 		/*
13313 		 * NOTE: because conn_idl is associated with a specific drain
13314 		 * list which in turn is tied to the index the TX ring
13315 		 * (txl_cookie) hashes to, and because the TX ring can change
13316 		 * over the lifetime of the conn_t, we must clear conn_idl so
13317 		 * a subsequent conn_drain_insert() will set conn_idl again
13318 		 * based on the latest txl_cookie.
13319 		 */
13320 		connp->conn_idl = NULL;
13321 	}
13322 	connp->conn_drain_next = NULL;
13323 	connp->conn_drain_prev = NULL;
13324 
13325 	conn_clrqfull(connp, NULL);
13326 	/*
13327 	 * For streams based sockets open up flow control.
13328 	 */
13329 	if (!IPCL_IS_NONSTR(connp))
13330 		enableok(connp->conn_wq);
13331 }
13332 
13333 /*
13334  * This conn is closing, and we are called from ip_close. OR
13335  * this conn is draining because flow-control on the ill has been relieved.
13336  *
13337  * We must also need to remove conn's on this idl from the list, and also
13338  * inform the sockfs upcalls about the change in flow-control.
13339  */
13340 static void
13341 conn_drain(conn_t *connp, boolean_t closing)
13342 {
13343 	idl_t *idl;
13344 	conn_t *next_connp;
13345 
13346 	/*
13347 	 * connp->conn_idl is stable at this point, and no lock is needed
13348 	 * to check it. If we are called from ip_close, close has already
13349 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13350 	 * called us only because conn_idl is non-null. If we are called thru
13351 	 * service, conn_idl could be null, but it cannot change because
13352 	 * service is single-threaded per queue, and there cannot be another
13353 	 * instance of service trying to call conn_drain_insert on this conn
13354 	 * now.
13355 	 */
13356 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13357 
13358 	/*
13359 	 * If the conn doesn't exist or is not on a drain list, bail.
13360 	 */
13361 	if (connp == NULL || connp->conn_idl == NULL ||
13362 	    connp->conn_drain_prev == NULL) {
13363 		return;
13364 	}
13365 
13366 	idl = connp->conn_idl;
13367 	ASSERT(MUTEX_HELD(&idl->idl_lock));
13368 
13369 	if (!closing) {
13370 		next_connp = connp->conn_drain_next;
13371 		while (next_connp != connp) {
13372 			conn_t *delconnp = next_connp;
13373 
13374 			next_connp = next_connp->conn_drain_next;
13375 			conn_drain_remove(delconnp);
13376 		}
13377 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13378 	}
13379 	conn_drain_remove(connp);
13380 }
13381 
13382 /*
13383  * Write service routine. Shared perimeter entry point.
13384  * The device queue's messages has fallen below the low water mark and STREAMS
13385  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13386  * each waiting conn.
13387  */
13388 int
13389 ip_wsrv(queue_t *q)
13390 {
13391 	ill_t	*ill;
13392 
13393 	ill = (ill_t *)q->q_ptr;
13394 	if (ill->ill_state_flags == 0) {
13395 		ip_stack_t *ipst = ill->ill_ipst;
13396 
13397 		/*
13398 		 * The device flow control has opened up.
13399 		 * Walk through conn drain lists and qenable the
13400 		 * first conn in each list. This makes sense only
13401 		 * if the stream is fully plumbed and setup.
13402 		 * Hence the ill_state_flags check above.
13403 		 */
13404 		ip1dbg(("ip_wsrv: walking\n"));
13405 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13406 		enableok(ill->ill_wq);
13407 	}
13408 	return (0);
13409 }
13410 
13411 /*
13412  * Callback to disable flow control in IP.
13413  *
13414  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13415  * is enabled.
13416  *
13417  * When MAC_TX() is not able to send any more packets, dld sets its queue
13418  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13419  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13420  * function and wakes up corresponding mac worker threads, which in turn
13421  * calls this callback function, and disables flow control.
13422  */
13423 void
13424 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13425 {
13426 	ill_t *ill = (ill_t *)arg;
13427 	ip_stack_t *ipst = ill->ill_ipst;
13428 	idl_tx_list_t *idl_txl;
13429 
13430 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13431 	mutex_enter(&idl_txl->txl_lock);
13432 	/* add code to to set a flag to indicate idl_txl is enabled */
13433 	conn_walk_drain(ipst, idl_txl);
13434 	mutex_exit(&idl_txl->txl_lock);
13435 }
13436 
13437 /*
13438  * Flow control has been relieved and STREAMS has backenabled us; drain
13439  * all the conn lists on `tx_list'.
13440  */
13441 static void
13442 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13443 {
13444 	int i;
13445 	idl_t *idl;
13446 
13447 	IP_STAT(ipst, ip_conn_walk_drain);
13448 
13449 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13450 		idl = &tx_list->txl_drain_list[i];
13451 		mutex_enter(&idl->idl_lock);
13452 		conn_drain(idl->idl_conn, B_FALSE);
13453 		mutex_exit(&idl->idl_lock);
13454 	}
13455 }
13456 
13457 /*
13458  * Determine if the ill and multicast aspects of that packets
13459  * "matches" the conn.
13460  */
13461 boolean_t
13462 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13463 {
13464 	ill_t		*ill = ira->ira_rill;
13465 	zoneid_t	zoneid = ira->ira_zoneid;
13466 	uint_t		in_ifindex;
13467 	ipaddr_t	dst, src;
13468 
13469 	dst = ipha->ipha_dst;
13470 	src = ipha->ipha_src;
13471 
13472 	/*
13473 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13474 	 * unicast, broadcast and multicast reception to
13475 	 * conn_incoming_ifindex.
13476 	 * conn_wantpacket is called for unicast, broadcast and
13477 	 * multicast packets.
13478 	 */
13479 	in_ifindex = connp->conn_incoming_ifindex;
13480 
13481 	/* mpathd can bind to the under IPMP interface, which we allow */
13482 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13483 		if (!IS_UNDER_IPMP(ill))
13484 			return (B_FALSE);
13485 
13486 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13487 			return (B_FALSE);
13488 	}
13489 
13490 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13491 		return (B_FALSE);
13492 
13493 	if (!(ira->ira_flags & IRAF_MULTICAST))
13494 		return (B_TRUE);
13495 
13496 	if (connp->conn_multi_router) {
13497 		/* multicast packet and multicast router socket: send up */
13498 		return (B_TRUE);
13499 	}
13500 
13501 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13502 	    ipha->ipha_protocol == IPPROTO_RSVP)
13503 		return (B_TRUE);
13504 
13505 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13506 }
13507 
13508 void
13509 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13510 {
13511 	if (IPCL_IS_NONSTR(connp)) {
13512 		(*connp->conn_upcalls->su_txq_full)
13513 		    (connp->conn_upper_handle, B_TRUE);
13514 		if (flow_stopped != NULL)
13515 			*flow_stopped = B_TRUE;
13516 	} else {
13517 		queue_t *q = connp->conn_wq;
13518 
13519 		ASSERT(q != NULL);
13520 		if (!(q->q_flag & QFULL)) {
13521 			mutex_enter(QLOCK(q));
13522 			if (!(q->q_flag & QFULL)) {
13523 				/* still need to set QFULL */
13524 				q->q_flag |= QFULL;
13525 				/* set flow_stopped to true under QLOCK */
13526 				if (flow_stopped != NULL)
13527 					*flow_stopped = B_TRUE;
13528 				mutex_exit(QLOCK(q));
13529 			} else {
13530 				/* flow_stopped is left unchanged */
13531 				mutex_exit(QLOCK(q));
13532 			}
13533 		}
13534 	}
13535 }
13536 
13537 void
13538 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13539 {
13540 	if (IPCL_IS_NONSTR(connp)) {
13541 		(*connp->conn_upcalls->su_txq_full)
13542 		    (connp->conn_upper_handle, B_FALSE);
13543 		if (flow_stopped != NULL)
13544 			*flow_stopped = B_FALSE;
13545 	} else {
13546 		queue_t *q = connp->conn_wq;
13547 
13548 		ASSERT(q != NULL);
13549 		if (q->q_flag & QFULL) {
13550 			mutex_enter(QLOCK(q));
13551 			if (q->q_flag & QFULL) {
13552 				q->q_flag &= ~QFULL;
13553 				/* set flow_stopped to false under QLOCK */
13554 				if (flow_stopped != NULL)
13555 					*flow_stopped = B_FALSE;
13556 				mutex_exit(QLOCK(q));
13557 				if (q->q_flag & QWANTW)
13558 					qbackenable(q, 0);
13559 			} else {
13560 				/* flow_stopped is left unchanged */
13561 				mutex_exit(QLOCK(q));
13562 			}
13563 		}
13564 	}
13565 
13566 	mutex_enter(&connp->conn_lock);
13567 	connp->conn_blocked = B_FALSE;
13568 	mutex_exit(&connp->conn_lock);
13569 }
13570 
13571 /*
13572  * Return the length in bytes of the IPv4 headers (base header, label, and
13573  * other IP options) that will be needed based on the
13574  * ip_pkt_t structure passed by the caller.
13575  *
13576  * The returned length does not include the length of the upper level
13577  * protocol (ULP) header.
13578  * The caller needs to check that the length doesn't exceed the max for IPv4.
13579  */
13580 int
13581 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13582 {
13583 	int len;
13584 
13585 	len = IP_SIMPLE_HDR_LENGTH;
13586 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13587 		ASSERT(ipp->ipp_label_len_v4 != 0);
13588 		/* We need to round up here */
13589 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13590 	}
13591 
13592 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13593 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13594 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13595 		len += ipp->ipp_ipv4_options_len;
13596 	}
13597 	return (len);
13598 }
13599 
13600 /*
13601  * All-purpose routine to build an IPv4 header with options based
13602  * on the abstract ip_pkt_t.
13603  *
13604  * The caller has to set the source and destination address as well as
13605  * ipha_length. The caller has to massage any source route and compensate
13606  * for the ULP pseudo-header checksum due to the source route.
13607  */
13608 void
13609 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13610     uint8_t protocol)
13611 {
13612 	ipha_t	*ipha = (ipha_t *)buf;
13613 	uint8_t *cp;
13614 
13615 	/* Initialize IPv4 header */
13616 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13617 	ipha->ipha_length = 0;	/* Caller will set later */
13618 	ipha->ipha_ident = 0;
13619 	ipha->ipha_fragment_offset_and_flags = 0;
13620 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13621 	ipha->ipha_protocol = protocol;
13622 	ipha->ipha_hdr_checksum = 0;
13623 
13624 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13625 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13626 		ipha->ipha_src = ipp->ipp_addr_v4;
13627 
13628 	cp = (uint8_t *)&ipha[1];
13629 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13630 		ASSERT(ipp->ipp_label_len_v4 != 0);
13631 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13632 		cp += ipp->ipp_label_len_v4;
13633 		/* We need to round up here */
13634 		while ((uintptr_t)cp & 0x3) {
13635 			*cp++ = IPOPT_NOP;
13636 		}
13637 	}
13638 
13639 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13640 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13641 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13642 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13643 		cp += ipp->ipp_ipv4_options_len;
13644 	}
13645 	ipha->ipha_version_and_hdr_length =
13646 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13647 
13648 	ASSERT((int)(cp - buf) == buf_len);
13649 }
13650 
13651 /* Allocate the private structure */
13652 static int
13653 ip_priv_alloc(void **bufp)
13654 {
13655 	void	*buf;
13656 
13657 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13658 		return (ENOMEM);
13659 
13660 	*bufp = buf;
13661 	return (0);
13662 }
13663 
13664 /* Function to delete the private structure */
13665 void
13666 ip_priv_free(void *buf)
13667 {
13668 	ASSERT(buf != NULL);
13669 	kmem_free(buf, sizeof (ip_priv_t));
13670 }
13671 
13672 /*
13673  * The entry point for IPPF processing.
13674  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13675  * routine just returns.
13676  *
13677  * When called, ip_process generates an ipp_packet_t structure
13678  * which holds the state information for this packet and invokes the
13679  * the classifier (via ipp_packet_process). The classification, depending on
13680  * configured filters, results in a list of actions for this packet. Invoking
13681  * an action may cause the packet to be dropped, in which case we return NULL.
13682  * proc indicates the callout position for
13683  * this packet and ill is the interface this packet arrived on or will leave
13684  * on (inbound and outbound resp.).
13685  *
13686  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13687  * on the ill corrsponding to the destination IP address.
13688  */
13689 mblk_t *
13690 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13691 {
13692 	ip_priv_t	*priv;
13693 	ipp_action_id_t	aid;
13694 	int		rc = 0;
13695 	ipp_packet_t	*pp;
13696 
13697 	/* If the classifier is not loaded, return  */
13698 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13699 		return (mp);
13700 	}
13701 
13702 	ASSERT(mp != NULL);
13703 
13704 	/* Allocate the packet structure */
13705 	rc = ipp_packet_alloc(&pp, "ip", aid);
13706 	if (rc != 0)
13707 		goto drop;
13708 
13709 	/* Allocate the private structure */
13710 	rc = ip_priv_alloc((void **)&priv);
13711 	if (rc != 0) {
13712 		ipp_packet_free(pp);
13713 		goto drop;
13714 	}
13715 	priv->proc = proc;
13716 	priv->ill_index = ill_get_upper_ifindex(rill);
13717 
13718 	ipp_packet_set_private(pp, priv, ip_priv_free);
13719 	ipp_packet_set_data(pp, mp);
13720 
13721 	/* Invoke the classifier */
13722 	rc = ipp_packet_process(&pp);
13723 	if (pp != NULL) {
13724 		mp = ipp_packet_get_data(pp);
13725 		ipp_packet_free(pp);
13726 		if (rc != 0)
13727 			goto drop;
13728 		return (mp);
13729 	} else {
13730 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13731 		mp = NULL;
13732 	}
13733 drop:
13734 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13735 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13736 		ip_drop_input("ip_process", mp, ill);
13737 	} else {
13738 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13739 		ip_drop_output("ip_process", mp, ill);
13740 	}
13741 	freemsg(mp);
13742 	return (NULL);
13743 }
13744 
13745 /*
13746  * Propagate a multicast group membership operation (add/drop) on
13747  * all the interfaces crossed by the related multirt routes.
13748  * The call is considered successful if the operation succeeds
13749  * on at least one interface.
13750  *
13751  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13752  * multicast addresses with the ire argument being the first one.
13753  * We walk the bucket to find all the of those.
13754  *
13755  * Common to IPv4 and IPv6.
13756  */
13757 static int
13758 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13759     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13760     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13761     mcast_record_t fmode, const in6_addr_t *v6src)
13762 {
13763 	ire_t		*ire_gw;
13764 	irb_t		*irb;
13765 	int		ifindex;
13766 	int		error = 0;
13767 	int		result;
13768 	ip_stack_t	*ipst = ire->ire_ipst;
13769 	ipaddr_t	group;
13770 	boolean_t	isv6;
13771 	int		match_flags;
13772 
13773 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13774 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13775 		isv6 = B_FALSE;
13776 	} else {
13777 		isv6 = B_TRUE;
13778 	}
13779 
13780 	irb = ire->ire_bucket;
13781 	ASSERT(irb != NULL);
13782 
13783 	result = 0;
13784 	irb_refhold(irb);
13785 	for (; ire != NULL; ire = ire->ire_next) {
13786 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13787 			continue;
13788 
13789 		/* We handle -ifp routes by matching on the ill if set */
13790 		match_flags = MATCH_IRE_TYPE;
13791 		if (ire->ire_ill != NULL)
13792 			match_flags |= MATCH_IRE_ILL;
13793 
13794 		if (isv6) {
13795 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13796 				continue;
13797 
13798 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13799 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13800 			    match_flags, 0, ipst, NULL);
13801 		} else {
13802 			if (ire->ire_addr != group)
13803 				continue;
13804 
13805 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13806 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13807 			    match_flags, 0, ipst, NULL);
13808 		}
13809 		/* No interface route exists for the gateway; skip this ire. */
13810 		if (ire_gw == NULL)
13811 			continue;
13812 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13813 			ire_refrele(ire_gw);
13814 			continue;
13815 		}
13816 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13817 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13818 
13819 		/*
13820 		 * The operation is considered a success if
13821 		 * it succeeds at least once on any one interface.
13822 		 */
13823 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13824 		    fmode, v6src);
13825 		if (error == 0)
13826 			result = CGTP_MCAST_SUCCESS;
13827 
13828 		ire_refrele(ire_gw);
13829 	}
13830 	irb_refrele(irb);
13831 	/*
13832 	 * Consider the call as successful if we succeeded on at least
13833 	 * one interface. Otherwise, return the last encountered error.
13834 	 */
13835 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13836 }
13837 
13838 /*
13839  * Return the expected CGTP hooks version number.
13840  */
13841 int
13842 ip_cgtp_filter_supported(void)
13843 {
13844 	return (ip_cgtp_filter_rev);
13845 }
13846 
13847 /*
13848  * CGTP hooks can be registered by invoking this function.
13849  * Checks that the version number matches.
13850  */
13851 int
13852 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13853 {
13854 	netstack_t *ns;
13855 	ip_stack_t *ipst;
13856 
13857 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13858 		return (ENOTSUP);
13859 
13860 	ns = netstack_find_by_stackid(stackid);
13861 	if (ns == NULL)
13862 		return (EINVAL);
13863 	ipst = ns->netstack_ip;
13864 	ASSERT(ipst != NULL);
13865 
13866 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13867 		netstack_rele(ns);
13868 		return (EALREADY);
13869 	}
13870 
13871 	ipst->ips_ip_cgtp_filter_ops = ops;
13872 
13873 	ill_set_inputfn_all(ipst);
13874 
13875 	netstack_rele(ns);
13876 	return (0);
13877 }
13878 
13879 /*
13880  * CGTP hooks can be unregistered by invoking this function.
13881  * Returns ENXIO if there was no registration.
13882  * Returns EBUSY if the ndd variable has not been turned off.
13883  */
13884 int
13885 ip_cgtp_filter_unregister(netstackid_t stackid)
13886 {
13887 	netstack_t *ns;
13888 	ip_stack_t *ipst;
13889 
13890 	ns = netstack_find_by_stackid(stackid);
13891 	if (ns == NULL)
13892 		return (EINVAL);
13893 	ipst = ns->netstack_ip;
13894 	ASSERT(ipst != NULL);
13895 
13896 	if (ipst->ips_ip_cgtp_filter) {
13897 		netstack_rele(ns);
13898 		return (EBUSY);
13899 	}
13900 
13901 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13902 		netstack_rele(ns);
13903 		return (ENXIO);
13904 	}
13905 	ipst->ips_ip_cgtp_filter_ops = NULL;
13906 
13907 	ill_set_inputfn_all(ipst);
13908 
13909 	netstack_rele(ns);
13910 	return (0);
13911 }
13912 
13913 /*
13914  * Check whether there is a CGTP filter registration.
13915  * Returns non-zero if there is a registration, otherwise returns zero.
13916  * Note: returns zero if bad stackid.
13917  */
13918 int
13919 ip_cgtp_filter_is_registered(netstackid_t stackid)
13920 {
13921 	netstack_t *ns;
13922 	ip_stack_t *ipst;
13923 	int ret;
13924 
13925 	ns = netstack_find_by_stackid(stackid);
13926 	if (ns == NULL)
13927 		return (0);
13928 	ipst = ns->netstack_ip;
13929 	ASSERT(ipst != NULL);
13930 
13931 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13932 		ret = 1;
13933 	else
13934 		ret = 0;
13935 
13936 	netstack_rele(ns);
13937 	return (ret);
13938 }
13939 
13940 static int
13941 ip_squeue_switch(int val)
13942 {
13943 	int rval;
13944 
13945 	switch (val) {
13946 	case IP_SQUEUE_ENTER_NODRAIN:
13947 		rval = SQ_NODRAIN;
13948 		break;
13949 	case IP_SQUEUE_ENTER:
13950 		rval = SQ_PROCESS;
13951 		break;
13952 	case IP_SQUEUE_FILL:
13953 	default:
13954 		rval = SQ_FILL;
13955 		break;
13956 	}
13957 	return (rval);
13958 }
13959 
13960 static void *
13961 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13962 {
13963 	kstat_t *ksp;
13964 
13965 	ip_stat_t template = {
13966 		{ "ip_udp_fannorm",		KSTAT_DATA_UINT64 },
13967 		{ "ip_udp_fanmb",		KSTAT_DATA_UINT64 },
13968 		{ "ip_recv_pullup",		KSTAT_DATA_UINT64 },
13969 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13970 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13971 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13972 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13973 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13974 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13975 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13976 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13977 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13978 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13979 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13980 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13981 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13982 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13983 		{ "ip_nce_mcast_reclaim_calls",	KSTAT_DATA_UINT64 },
13984 		{ "ip_nce_mcast_reclaim_deleted",	KSTAT_DATA_UINT64 },
13985 		{ "ip_nce_mcast_reclaim_tqfail",	KSTAT_DATA_UINT64 },
13986 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13987 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13988 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13989 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13990 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13991 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13992 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13993 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13994 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13995 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13996 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13997 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13998 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13999 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
14000 		{ "conn_in_recvtos",		KSTAT_DATA_UINT64 },
14001 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
14002 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
14003 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
14004 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
14005 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
14006 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
14007 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
14008 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
14009 	};
14010 
14011 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
14012 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
14013 	    KSTAT_FLAG_VIRTUAL, stackid);
14014 
14015 	if (ksp == NULL)
14016 		return (NULL);
14017 
14018 	bcopy(&template, ip_statisticsp, sizeof (template));
14019 	ksp->ks_data = (void *)ip_statisticsp;
14020 	ksp->ks_private = (void *)(uintptr_t)stackid;
14021 
14022 	kstat_install(ksp);
14023 	return (ksp);
14024 }
14025 
14026 static void
14027 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
14028 {
14029 	if (ksp != NULL) {
14030 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14031 		kstat_delete_netstack(ksp, stackid);
14032 	}
14033 }
14034 
14035 static void *
14036 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
14037 {
14038 	kstat_t	*ksp;
14039 
14040 	ip_named_kstat_t template = {
14041 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
14042 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
14043 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
14044 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
14045 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
14046 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
14047 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
14048 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
14049 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
14050 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
14051 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
14052 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
14053 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
14054 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
14055 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
14056 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
14057 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
14058 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
14059 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
14060 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
14061 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
14062 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
14063 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
14064 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
14065 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
14066 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
14067 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
14068 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
14069 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
14070 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
14071 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
14072 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
14073 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
14074 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
14075 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
14076 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
14077 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
14078 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
14079 	};
14080 
14081 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
14082 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
14083 	if (ksp == NULL || ksp->ks_data == NULL)
14084 		return (NULL);
14085 
14086 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
14087 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
14088 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
14089 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
14090 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14091 
14092 	template.netToMediaEntrySize.value.i32 =
14093 	    sizeof (mib2_ipNetToMediaEntry_t);
14094 
14095 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14096 
14097 	bcopy(&template, ksp->ks_data, sizeof (template));
14098 	ksp->ks_update = ip_kstat_update;
14099 	ksp->ks_private = (void *)(uintptr_t)stackid;
14100 
14101 	kstat_install(ksp);
14102 	return (ksp);
14103 }
14104 
14105 static void
14106 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14107 {
14108 	if (ksp != NULL) {
14109 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14110 		kstat_delete_netstack(ksp, stackid);
14111 	}
14112 }
14113 
14114 static int
14115 ip_kstat_update(kstat_t *kp, int rw)
14116 {
14117 	ip_named_kstat_t *ipkp;
14118 	mib2_ipIfStatsEntry_t ipmib;
14119 	ill_walk_context_t ctx;
14120 	ill_t *ill;
14121 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14122 	netstack_t	*ns;
14123 	ip_stack_t	*ipst;
14124 
14125 	if (kp->ks_data == NULL)
14126 		return (EIO);
14127 
14128 	if (rw == KSTAT_WRITE)
14129 		return (EACCES);
14130 
14131 	ns = netstack_find_by_stackid(stackid);
14132 	if (ns == NULL)
14133 		return (-1);
14134 	ipst = ns->netstack_ip;
14135 	if (ipst == NULL) {
14136 		netstack_rele(ns);
14137 		return (-1);
14138 	}
14139 	ipkp = (ip_named_kstat_t *)kp->ks_data;
14140 
14141 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14142 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14143 	ill = ILL_START_WALK_V4(&ctx, ipst);
14144 	for (; ill != NULL; ill = ill_next(&ctx, ill))
14145 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14146 	rw_exit(&ipst->ips_ill_g_lock);
14147 
14148 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
14149 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
14150 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
14151 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
14152 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
14153 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14154 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
14155 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
14156 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
14157 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
14158 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
14159 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
14160 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
14161 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
14162 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
14163 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
14164 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
14165 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
14166 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
14167 
14168 	ipkp->routingDiscards.value.ui32 =	0;
14169 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
14170 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
14171 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
14172 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
14173 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
14174 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
14175 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
14176 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
14177 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
14178 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
14179 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
14180 
14181 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
14182 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
14183 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14184 
14185 	netstack_rele(ns);
14186 
14187 	return (0);
14188 }
14189 
14190 static void *
14191 icmp_kstat_init(netstackid_t stackid)
14192 {
14193 	kstat_t	*ksp;
14194 
14195 	icmp_named_kstat_t template = {
14196 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14197 		{ "inErrors",		KSTAT_DATA_UINT32 },
14198 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14199 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14200 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14201 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14202 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14203 		{ "inEchos",		KSTAT_DATA_UINT32 },
14204 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14205 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14206 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14207 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14208 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14209 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14210 		{ "outErrors",		KSTAT_DATA_UINT32 },
14211 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14212 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14213 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14214 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14215 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14216 		{ "outEchos",		KSTAT_DATA_UINT32 },
14217 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14218 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14219 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14220 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14221 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14222 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14223 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14224 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14225 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14226 		{ "outDrops",		KSTAT_DATA_UINT32 },
14227 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14228 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14229 	};
14230 
14231 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14232 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14233 	if (ksp == NULL || ksp->ks_data == NULL)
14234 		return (NULL);
14235 
14236 	bcopy(&template, ksp->ks_data, sizeof (template));
14237 
14238 	ksp->ks_update = icmp_kstat_update;
14239 	ksp->ks_private = (void *)(uintptr_t)stackid;
14240 
14241 	kstat_install(ksp);
14242 	return (ksp);
14243 }
14244 
14245 static void
14246 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14247 {
14248 	if (ksp != NULL) {
14249 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14250 		kstat_delete_netstack(ksp, stackid);
14251 	}
14252 }
14253 
14254 static int
14255 icmp_kstat_update(kstat_t *kp, int rw)
14256 {
14257 	icmp_named_kstat_t *icmpkp;
14258 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14259 	netstack_t	*ns;
14260 	ip_stack_t	*ipst;
14261 
14262 	if (kp->ks_data == NULL)
14263 		return (EIO);
14264 
14265 	if (rw == KSTAT_WRITE)
14266 		return (EACCES);
14267 
14268 	ns = netstack_find_by_stackid(stackid);
14269 	if (ns == NULL)
14270 		return (-1);
14271 	ipst = ns->netstack_ip;
14272 	if (ipst == NULL) {
14273 		netstack_rele(ns);
14274 		return (-1);
14275 	}
14276 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14277 
14278 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14279 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14280 	icmpkp->inDestUnreachs.value.ui32 =
14281 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14282 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14283 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14284 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14285 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14286 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14287 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14288 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14289 	icmpkp->inTimestampReps.value.ui32 =
14290 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14291 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14292 	icmpkp->inAddrMaskReps.value.ui32 =
14293 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14294 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14295 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14296 	icmpkp->outDestUnreachs.value.ui32 =
14297 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14298 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14299 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14300 	icmpkp->outSrcQuenchs.value.ui32 =
14301 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14302 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14303 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14304 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14305 	icmpkp->outTimestamps.value.ui32 =
14306 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14307 	icmpkp->outTimestampReps.value.ui32 =
14308 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14309 	icmpkp->outAddrMasks.value.ui32 =
14310 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14311 	icmpkp->outAddrMaskReps.value.ui32 =
14312 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14313 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14314 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14315 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14316 	icmpkp->outFragNeeded.value.ui32 =
14317 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14318 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14319 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14320 	icmpkp->inBadRedirects.value.ui32 =
14321 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14322 
14323 	netstack_rele(ns);
14324 	return (0);
14325 }
14326 
14327 /*
14328  * This is the fanout function for raw socket opened for SCTP.  Note
14329  * that it is called after SCTP checks that there is no socket which
14330  * wants a packet.  Then before SCTP handles this out of the blue packet,
14331  * this function is called to see if there is any raw socket for SCTP.
14332  * If there is and it is bound to the correct address, the packet will
14333  * be sent to that socket.  Note that only one raw socket can be bound to
14334  * a port.  This is assured in ipcl_sctp_hash_insert();
14335  */
14336 void
14337 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14338     ip_recv_attr_t *ira)
14339 {
14340 	conn_t		*connp;
14341 	queue_t		*rq;
14342 	boolean_t	secure;
14343 	ill_t		*ill = ira->ira_ill;
14344 	ip_stack_t	*ipst = ill->ill_ipst;
14345 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14346 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14347 	iaflags_t	iraflags = ira->ira_flags;
14348 	ill_t		*rill = ira->ira_rill;
14349 
14350 	secure = iraflags & IRAF_IPSEC_SECURE;
14351 
14352 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14353 	    ira, ipst);
14354 	if (connp == NULL) {
14355 		/*
14356 		 * Although raw sctp is not summed, OOB chunks must be.
14357 		 * Drop the packet here if the sctp checksum failed.
14358 		 */
14359 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14360 			SCTPS_BUMP_MIB(sctps, sctpChecksumError);
14361 			freemsg(mp);
14362 			return;
14363 		}
14364 		ira->ira_ill = ira->ira_rill = NULL;
14365 		sctp_ootb_input(mp, ira, ipst);
14366 		ira->ira_ill = ill;
14367 		ira->ira_rill = rill;
14368 		return;
14369 	}
14370 	rq = connp->conn_rq;
14371 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14372 		CONN_DEC_REF(connp);
14373 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14374 		freemsg(mp);
14375 		return;
14376 	}
14377 	if (((iraflags & IRAF_IS_IPV4) ?
14378 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14379 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14380 	    secure) {
14381 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14382 		    ip6h, ira);
14383 		if (mp == NULL) {
14384 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14385 			/* Note that mp is NULL */
14386 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14387 			CONN_DEC_REF(connp);
14388 			return;
14389 		}
14390 	}
14391 
14392 	if (iraflags & IRAF_ICMP_ERROR) {
14393 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14394 	} else {
14395 		ill_t *rill = ira->ira_rill;
14396 
14397 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14398 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14399 		ira->ira_ill = ira->ira_rill = NULL;
14400 		(connp->conn_recv)(connp, mp, NULL, ira);
14401 		ira->ira_ill = ill;
14402 		ira->ira_rill = rill;
14403 	}
14404 	CONN_DEC_REF(connp);
14405 }
14406 
14407 /*
14408  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14409  * header before the ip payload.
14410  */
14411 static void
14412 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14413 {
14414 	int len = (mp->b_wptr - mp->b_rptr);
14415 	mblk_t *ip_mp;
14416 
14417 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14418 	if (is_fp_mp || len != fp_mp_len) {
14419 		if (len > fp_mp_len) {
14420 			/*
14421 			 * fastpath header and ip header in the first mblk
14422 			 */
14423 			mp->b_rptr += fp_mp_len;
14424 		} else {
14425 			/*
14426 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14427 			 * attach the fastpath header before ip header.
14428 			 */
14429 			ip_mp = mp->b_cont;
14430 			freeb(mp);
14431 			mp = ip_mp;
14432 			mp->b_rptr += (fp_mp_len - len);
14433 		}
14434 	} else {
14435 		ip_mp = mp->b_cont;
14436 		freeb(mp);
14437 		mp = ip_mp;
14438 	}
14439 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14440 	freemsg(mp);
14441 }
14442 
14443 /*
14444  * Normal post fragmentation function.
14445  *
14446  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14447  * using the same state machine.
14448  *
14449  * We return an error on failure. In particular we return EWOULDBLOCK
14450  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14451  * (currently by canputnext failure resulting in backenabling from GLD.)
14452  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14453  * indication that they can flow control until ip_wsrv() tells then to restart.
14454  *
14455  * If the nce passed by caller is incomplete, this function
14456  * queues the packet and if necessary, sends ARP request and bails.
14457  * If the Neighbor Cache passed is fully resolved, we simply prepend
14458  * the link-layer header to the packet, do ipsec hw acceleration
14459  * work if necessary, and send the packet out on the wire.
14460  */
14461 /* ARGSUSED6 */
14462 int
14463 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14464     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14465 {
14466 	queue_t		*wq;
14467 	ill_t		*ill = nce->nce_ill;
14468 	ip_stack_t	*ipst = ill->ill_ipst;
14469 	uint64_t	delta;
14470 	boolean_t	isv6 = ill->ill_isv6;
14471 	boolean_t	fp_mp;
14472 	ncec_t		*ncec = nce->nce_common;
14473 	int64_t		now = LBOLT_FASTPATH64;
14474 	boolean_t	is_probe;
14475 
14476 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14477 
14478 	ASSERT(mp != NULL);
14479 	ASSERT(mp->b_datap->db_type == M_DATA);
14480 	ASSERT(pkt_len == msgdsize(mp));
14481 
14482 	/*
14483 	 * If we have already been here and are coming back after ARP/ND.
14484 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14485 	 * in that case since they have seen the packet when it came here
14486 	 * the first time.
14487 	 */
14488 	if (ixaflags & IXAF_NO_TRACE)
14489 		goto sendit;
14490 
14491 	if (ixaflags & IXAF_IS_IPV4) {
14492 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14493 
14494 		ASSERT(!isv6);
14495 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14496 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14497 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14498 			int	error;
14499 
14500 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14501 			    ipst->ips_ipv4firewall_physical_out,
14502 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14503 			DTRACE_PROBE1(ip4__physical__out__end,
14504 			    mblk_t *, mp);
14505 			if (mp == NULL)
14506 				return (error);
14507 
14508 			/* The length could have changed */
14509 			pkt_len = msgdsize(mp);
14510 		}
14511 		if (ipst->ips_ip4_observe.he_interested) {
14512 			/*
14513 			 * Note that for TX the zoneid is the sending
14514 			 * zone, whether or not MLP is in play.
14515 			 * Since the szone argument is the IP zoneid (i.e.,
14516 			 * zero for exclusive-IP zones) and ipobs wants
14517 			 * the system zoneid, we map it here.
14518 			 */
14519 			szone = IP_REAL_ZONEID(szone, ipst);
14520 
14521 			/*
14522 			 * On the outbound path the destination zone will be
14523 			 * unknown as we're sending this packet out on the
14524 			 * wire.
14525 			 */
14526 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14527 			    ill, ipst);
14528 		}
14529 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14530 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14531 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14532 	} else {
14533 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14534 
14535 		ASSERT(isv6);
14536 		ASSERT(pkt_len ==
14537 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14538 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14539 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14540 			int	error;
14541 
14542 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14543 			    ipst->ips_ipv6firewall_physical_out,
14544 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14545 			DTRACE_PROBE1(ip6__physical__out__end,
14546 			    mblk_t *, mp);
14547 			if (mp == NULL)
14548 				return (error);
14549 
14550 			/* The length could have changed */
14551 			pkt_len = msgdsize(mp);
14552 		}
14553 		if (ipst->ips_ip6_observe.he_interested) {
14554 			/* See above */
14555 			szone = IP_REAL_ZONEID(szone, ipst);
14556 
14557 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14558 			    ill, ipst);
14559 		}
14560 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14561 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14562 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14563 	}
14564 
14565 sendit:
14566 	/*
14567 	 * We check the state without a lock because the state can never
14568 	 * move "backwards" to initial or incomplete.
14569 	 */
14570 	switch (ncec->ncec_state) {
14571 	case ND_REACHABLE:
14572 	case ND_STALE:
14573 	case ND_DELAY:
14574 	case ND_PROBE:
14575 		mp = ip_xmit_attach_llhdr(mp, nce);
14576 		if (mp == NULL) {
14577 			/*
14578 			 * ip_xmit_attach_llhdr has increased
14579 			 * ipIfStatsOutDiscards and called ip_drop_output()
14580 			 */
14581 			return (ENOBUFS);
14582 		}
14583 		/*
14584 		 * check if nce_fastpath completed and we tagged on a
14585 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14586 		 */
14587 		fp_mp = (mp->b_datap->db_type == M_DATA);
14588 
14589 		if (fp_mp &&
14590 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14591 			ill_dld_direct_t *idd;
14592 
14593 			idd = &ill->ill_dld_capab->idc_direct;
14594 			/*
14595 			 * Send the packet directly to DLD, where it
14596 			 * may be queued depending on the availability
14597 			 * of transmit resources at the media layer.
14598 			 * Return value should be taken into
14599 			 * account and flow control the TCP.
14600 			 */
14601 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14602 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14603 			    pkt_len);
14604 
14605 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14606 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14607 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14608 			} else {
14609 				uintptr_t cookie;
14610 
14611 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14612 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14613 					if (ixacookie != NULL)
14614 						*ixacookie = cookie;
14615 					return (EWOULDBLOCK);
14616 				}
14617 			}
14618 		} else {
14619 			wq = ill->ill_wq;
14620 
14621 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14622 			    !canputnext(wq)) {
14623 				if (ixacookie != NULL)
14624 					*ixacookie = 0;
14625 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14626 				    nce->nce_fp_mp != NULL ?
14627 				    MBLKL(nce->nce_fp_mp) : 0);
14628 				return (EWOULDBLOCK);
14629 			}
14630 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14631 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14632 			    pkt_len);
14633 			putnext(wq, mp);
14634 		}
14635 
14636 		/*
14637 		 * The rest of this function implements Neighbor Unreachability
14638 		 * detection. Determine if the ncec is eligible for NUD.
14639 		 */
14640 		if (ncec->ncec_flags & NCE_F_NONUD)
14641 			return (0);
14642 
14643 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14644 
14645 		/*
14646 		 * Check for upper layer advice
14647 		 */
14648 		if (ixaflags & IXAF_REACH_CONF) {
14649 			timeout_id_t tid;
14650 
14651 			/*
14652 			 * It should be o.k. to check the state without
14653 			 * a lock here, at most we lose an advice.
14654 			 */
14655 			ncec->ncec_last = TICK_TO_MSEC(now);
14656 			if (ncec->ncec_state != ND_REACHABLE) {
14657 				mutex_enter(&ncec->ncec_lock);
14658 				ncec->ncec_state = ND_REACHABLE;
14659 				tid = ncec->ncec_timeout_id;
14660 				ncec->ncec_timeout_id = 0;
14661 				mutex_exit(&ncec->ncec_lock);
14662 				(void) untimeout(tid);
14663 				if (ip_debug > 2) {
14664 					/* ip1dbg */
14665 					pr_addr_dbg("ip_xmit: state"
14666 					    " for %s changed to"
14667 					    " REACHABLE\n", AF_INET6,
14668 					    &ncec->ncec_addr);
14669 				}
14670 			}
14671 			return (0);
14672 		}
14673 
14674 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14675 		ip1dbg(("ip_xmit: delta = %" PRId64
14676 		    " ill_reachable_time = %d \n", delta,
14677 		    ill->ill_reachable_time));
14678 		if (delta > (uint64_t)ill->ill_reachable_time) {
14679 			mutex_enter(&ncec->ncec_lock);
14680 			switch (ncec->ncec_state) {
14681 			case ND_REACHABLE:
14682 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14683 				/* FALLTHROUGH */
14684 			case ND_STALE:
14685 				/*
14686 				 * ND_REACHABLE is identical to
14687 				 * ND_STALE in this specific case. If
14688 				 * reachable time has expired for this
14689 				 * neighbor (delta is greater than
14690 				 * reachable time), conceptually, the
14691 				 * neighbor cache is no longer in
14692 				 * REACHABLE state, but already in
14693 				 * STALE state.  So the correct
14694 				 * transition here is to ND_DELAY.
14695 				 */
14696 				ncec->ncec_state = ND_DELAY;
14697 				mutex_exit(&ncec->ncec_lock);
14698 				nce_restart_timer(ncec,
14699 				    ipst->ips_delay_first_probe_time);
14700 				if (ip_debug > 3) {
14701 					/* ip2dbg */
14702 					pr_addr_dbg("ip_xmit: state"
14703 					    " for %s changed to"
14704 					    " DELAY\n", AF_INET6,
14705 					    &ncec->ncec_addr);
14706 				}
14707 				break;
14708 			case ND_DELAY:
14709 			case ND_PROBE:
14710 				mutex_exit(&ncec->ncec_lock);
14711 				/* Timers have already started */
14712 				break;
14713 			case ND_UNREACHABLE:
14714 				/*
14715 				 * nce_timer has detected that this ncec
14716 				 * is unreachable and initiated deleting
14717 				 * this ncec.
14718 				 * This is a harmless race where we found the
14719 				 * ncec before it was deleted and have
14720 				 * just sent out a packet using this
14721 				 * unreachable ncec.
14722 				 */
14723 				mutex_exit(&ncec->ncec_lock);
14724 				break;
14725 			default:
14726 				ASSERT(0);
14727 				mutex_exit(&ncec->ncec_lock);
14728 			}
14729 		}
14730 		return (0);
14731 
14732 	case ND_INCOMPLETE:
14733 		/*
14734 		 * the state could have changed since we didn't hold the lock.
14735 		 * Re-verify state under lock.
14736 		 */
14737 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14738 		mutex_enter(&ncec->ncec_lock);
14739 		if (NCE_ISREACHABLE(ncec)) {
14740 			mutex_exit(&ncec->ncec_lock);
14741 			goto sendit;
14742 		}
14743 		/* queue the packet */
14744 		nce_queue_mp(ncec, mp, is_probe);
14745 		mutex_exit(&ncec->ncec_lock);
14746 		DTRACE_PROBE2(ip__xmit__incomplete,
14747 		    (ncec_t *), ncec, (mblk_t *), mp);
14748 		return (0);
14749 
14750 	case ND_INITIAL:
14751 		/*
14752 		 * State could have changed since we didn't hold the lock, so
14753 		 * re-verify state.
14754 		 */
14755 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14756 		mutex_enter(&ncec->ncec_lock);
14757 		if (NCE_ISREACHABLE(ncec))  {
14758 			mutex_exit(&ncec->ncec_lock);
14759 			goto sendit;
14760 		}
14761 		nce_queue_mp(ncec, mp, is_probe);
14762 		if (ncec->ncec_state == ND_INITIAL) {
14763 			ncec->ncec_state = ND_INCOMPLETE;
14764 			mutex_exit(&ncec->ncec_lock);
14765 			/*
14766 			 * figure out the source we want to use
14767 			 * and resolve it.
14768 			 */
14769 			ip_ndp_resolve(ncec);
14770 		} else  {
14771 			mutex_exit(&ncec->ncec_lock);
14772 		}
14773 		return (0);
14774 
14775 	case ND_UNREACHABLE:
14776 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14777 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14778 		    mp, ill);
14779 		freemsg(mp);
14780 		return (0);
14781 
14782 	default:
14783 		ASSERT(0);
14784 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14785 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14786 		    mp, ill);
14787 		freemsg(mp);
14788 		return (ENETUNREACH);
14789 	}
14790 }
14791 
14792 /*
14793  * Return B_TRUE if the buffers differ in length or content.
14794  * This is used for comparing extension header buffers.
14795  * Note that an extension header would be declared different
14796  * even if all that changed was the next header value in that header i.e.
14797  * what really changed is the next extension header.
14798  */
14799 boolean_t
14800 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14801     uint_t blen)
14802 {
14803 	if (!b_valid)
14804 		blen = 0;
14805 
14806 	if (alen != blen)
14807 		return (B_TRUE);
14808 	if (alen == 0)
14809 		return (B_FALSE);	/* Both zero length */
14810 	return (bcmp(abuf, bbuf, alen));
14811 }
14812 
14813 /*
14814  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14815  * Return B_FALSE if memory allocation fails - don't change any state!
14816  */
14817 boolean_t
14818 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14819     const void *src, uint_t srclen)
14820 {
14821 	void *dst;
14822 
14823 	if (!src_valid)
14824 		srclen = 0;
14825 
14826 	ASSERT(*dstlenp == 0);
14827 	if (src != NULL && srclen != 0) {
14828 		dst = mi_alloc(srclen, BPRI_MED);
14829 		if (dst == NULL)
14830 			return (B_FALSE);
14831 	} else {
14832 		dst = NULL;
14833 	}
14834 	if (*dstp != NULL)
14835 		mi_free(*dstp);
14836 	*dstp = dst;
14837 	*dstlenp = dst == NULL ? 0 : srclen;
14838 	return (B_TRUE);
14839 }
14840 
14841 /*
14842  * Replace what is in *dst, *dstlen with the source.
14843  * Assumes ip_allocbuf has already been called.
14844  */
14845 void
14846 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14847     const void *src, uint_t srclen)
14848 {
14849 	if (!src_valid)
14850 		srclen = 0;
14851 
14852 	ASSERT(*dstlenp == srclen);
14853 	if (src != NULL && srclen != 0)
14854 		bcopy(src, *dstp, srclen);
14855 }
14856 
14857 /*
14858  * Free the storage pointed to by the members of an ip_pkt_t.
14859  */
14860 void
14861 ip_pkt_free(ip_pkt_t *ipp)
14862 {
14863 	uint_t	fields = ipp->ipp_fields;
14864 
14865 	if (fields & IPPF_HOPOPTS) {
14866 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14867 		ipp->ipp_hopopts = NULL;
14868 		ipp->ipp_hopoptslen = 0;
14869 	}
14870 	if (fields & IPPF_RTHDRDSTOPTS) {
14871 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14872 		ipp->ipp_rthdrdstopts = NULL;
14873 		ipp->ipp_rthdrdstoptslen = 0;
14874 	}
14875 	if (fields & IPPF_DSTOPTS) {
14876 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14877 		ipp->ipp_dstopts = NULL;
14878 		ipp->ipp_dstoptslen = 0;
14879 	}
14880 	if (fields & IPPF_RTHDR) {
14881 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14882 		ipp->ipp_rthdr = NULL;
14883 		ipp->ipp_rthdrlen = 0;
14884 	}
14885 	if (fields & IPPF_IPV4_OPTIONS) {
14886 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14887 		ipp->ipp_ipv4_options = NULL;
14888 		ipp->ipp_ipv4_options_len = 0;
14889 	}
14890 	if (fields & IPPF_LABEL_V4) {
14891 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14892 		ipp->ipp_label_v4 = NULL;
14893 		ipp->ipp_label_len_v4 = 0;
14894 	}
14895 	if (fields & IPPF_LABEL_V6) {
14896 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14897 		ipp->ipp_label_v6 = NULL;
14898 		ipp->ipp_label_len_v6 = 0;
14899 	}
14900 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14901 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14902 }
14903 
14904 /*
14905  * Copy from src to dst and allocate as needed.
14906  * Returns zero or ENOMEM.
14907  *
14908  * The caller must initialize dst to zero.
14909  */
14910 int
14911 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14912 {
14913 	uint_t	fields = src->ipp_fields;
14914 
14915 	/* Start with fields that don't require memory allocation */
14916 	dst->ipp_fields = fields &
14917 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14918 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14919 
14920 	dst->ipp_addr = src->ipp_addr;
14921 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14922 	dst->ipp_hoplimit = src->ipp_hoplimit;
14923 	dst->ipp_tclass = src->ipp_tclass;
14924 	dst->ipp_type_of_service = src->ipp_type_of_service;
14925 
14926 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14927 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14928 		return (0);
14929 
14930 	if (fields & IPPF_HOPOPTS) {
14931 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14932 		if (dst->ipp_hopopts == NULL) {
14933 			ip_pkt_free(dst);
14934 			return (ENOMEM);
14935 		}
14936 		dst->ipp_fields |= IPPF_HOPOPTS;
14937 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14938 		    src->ipp_hopoptslen);
14939 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14940 	}
14941 	if (fields & IPPF_RTHDRDSTOPTS) {
14942 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14943 		    kmflag);
14944 		if (dst->ipp_rthdrdstopts == NULL) {
14945 			ip_pkt_free(dst);
14946 			return (ENOMEM);
14947 		}
14948 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14949 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14950 		    src->ipp_rthdrdstoptslen);
14951 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14952 	}
14953 	if (fields & IPPF_DSTOPTS) {
14954 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14955 		if (dst->ipp_dstopts == NULL) {
14956 			ip_pkt_free(dst);
14957 			return (ENOMEM);
14958 		}
14959 		dst->ipp_fields |= IPPF_DSTOPTS;
14960 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14961 		    src->ipp_dstoptslen);
14962 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14963 	}
14964 	if (fields & IPPF_RTHDR) {
14965 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14966 		if (dst->ipp_rthdr == NULL) {
14967 			ip_pkt_free(dst);
14968 			return (ENOMEM);
14969 		}
14970 		dst->ipp_fields |= IPPF_RTHDR;
14971 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14972 		    src->ipp_rthdrlen);
14973 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14974 	}
14975 	if (fields & IPPF_IPV4_OPTIONS) {
14976 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14977 		    kmflag);
14978 		if (dst->ipp_ipv4_options == NULL) {
14979 			ip_pkt_free(dst);
14980 			return (ENOMEM);
14981 		}
14982 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14983 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14984 		    src->ipp_ipv4_options_len);
14985 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14986 	}
14987 	if (fields & IPPF_LABEL_V4) {
14988 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14989 		if (dst->ipp_label_v4 == NULL) {
14990 			ip_pkt_free(dst);
14991 			return (ENOMEM);
14992 		}
14993 		dst->ipp_fields |= IPPF_LABEL_V4;
14994 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14995 		    src->ipp_label_len_v4);
14996 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14997 	}
14998 	if (fields & IPPF_LABEL_V6) {
14999 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
15000 		if (dst->ipp_label_v6 == NULL) {
15001 			ip_pkt_free(dst);
15002 			return (ENOMEM);
15003 		}
15004 		dst->ipp_fields |= IPPF_LABEL_V6;
15005 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
15006 		    src->ipp_label_len_v6);
15007 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
15008 	}
15009 	if (fields & IPPF_FRAGHDR) {
15010 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
15011 		if (dst->ipp_fraghdr == NULL) {
15012 			ip_pkt_free(dst);
15013 			return (ENOMEM);
15014 		}
15015 		dst->ipp_fields |= IPPF_FRAGHDR;
15016 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
15017 		    src->ipp_fraghdrlen);
15018 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
15019 	}
15020 	return (0);
15021 }
15022 
15023 /*
15024  * Returns INADDR_ANY if no source route
15025  */
15026 ipaddr_t
15027 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
15028 {
15029 	ipaddr_t	nexthop = INADDR_ANY;
15030 	ipoptp_t	opts;
15031 	uchar_t		*opt;
15032 	uint8_t		optval;
15033 	uint8_t		optlen;
15034 	uint32_t	totallen;
15035 
15036 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15037 		return (INADDR_ANY);
15038 
15039 	totallen = ipp->ipp_ipv4_options_len;
15040 	if (totallen & 0x3)
15041 		return (INADDR_ANY);
15042 
15043 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15044 	    optval != IPOPT_EOL;
15045 	    optval = ipoptp_next(&opts)) {
15046 		opt = opts.ipoptp_cur;
15047 		switch (optval) {
15048 			uint8_t off;
15049 		case IPOPT_SSRR:
15050 		case IPOPT_LSRR:
15051 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15052 				break;
15053 			}
15054 			optlen = opts.ipoptp_len;
15055 			off = opt[IPOPT_OFFSET];
15056 			off--;
15057 			if (optlen < IP_ADDR_LEN ||
15058 			    off > optlen - IP_ADDR_LEN) {
15059 				/* End of source route */
15060 				break;
15061 			}
15062 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
15063 			if (nexthop == htonl(INADDR_LOOPBACK)) {
15064 				/* Ignore */
15065 				nexthop = INADDR_ANY;
15066 				break;
15067 			}
15068 			break;
15069 		}
15070 	}
15071 	return (nexthop);
15072 }
15073 
15074 /*
15075  * Reverse a source route.
15076  */
15077 void
15078 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
15079 {
15080 	ipaddr_t	tmp;
15081 	ipoptp_t	opts;
15082 	uchar_t		*opt;
15083 	uint8_t		optval;
15084 	uint32_t	totallen;
15085 
15086 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15087 		return;
15088 
15089 	totallen = ipp->ipp_ipv4_options_len;
15090 	if (totallen & 0x3)
15091 		return;
15092 
15093 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15094 	    optval != IPOPT_EOL;
15095 	    optval = ipoptp_next(&opts)) {
15096 		uint8_t off1, off2;
15097 
15098 		opt = opts.ipoptp_cur;
15099 		switch (optval) {
15100 		case IPOPT_SSRR:
15101 		case IPOPT_LSRR:
15102 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15103 				break;
15104 			}
15105 			off1 = IPOPT_MINOFF_SR - 1;
15106 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15107 			while (off2 > off1) {
15108 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15109 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15110 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15111 				off2 -= IP_ADDR_LEN;
15112 				off1 += IP_ADDR_LEN;
15113 			}
15114 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15115 			break;
15116 		}
15117 	}
15118 }
15119 
15120 /*
15121  * Returns NULL if no routing header
15122  */
15123 in6_addr_t *
15124 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15125 {
15126 	in6_addr_t	*nexthop = NULL;
15127 	ip6_rthdr0_t	*rthdr;
15128 
15129 	if (!(ipp->ipp_fields & IPPF_RTHDR))
15130 		return (NULL);
15131 
15132 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15133 	if (rthdr->ip6r0_segleft == 0)
15134 		return (NULL);
15135 
15136 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15137 	return (nexthop);
15138 }
15139 
15140 zoneid_t
15141 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15142     zoneid_t lookup_zoneid)
15143 {
15144 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15145 	ire_t		*ire;
15146 	int		ire_flags = MATCH_IRE_TYPE;
15147 	zoneid_t	zoneid = ALL_ZONES;
15148 
15149 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15150 		return (ALL_ZONES);
15151 
15152 	if (lookup_zoneid != ALL_ZONES)
15153 		ire_flags |= MATCH_IRE_ZONEONLY;
15154 	ire = ire_ftable_lookup_v4(addr, 0, 0, IRE_LOCAL | IRE_LOOPBACK,
15155 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15156 	if (ire != NULL) {
15157 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15158 		ire_refrele(ire);
15159 	}
15160 	return (zoneid);
15161 }
15162 
15163 zoneid_t
15164 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15165     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15166 {
15167 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15168 	ire_t		*ire;
15169 	int		ire_flags = MATCH_IRE_TYPE;
15170 	zoneid_t	zoneid = ALL_ZONES;
15171 
15172 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15173 		return (ALL_ZONES);
15174 
15175 	if (IN6_IS_ADDR_LINKLOCAL(addr))
15176 		ire_flags |= MATCH_IRE_ILL;
15177 
15178 	if (lookup_zoneid != ALL_ZONES)
15179 		ire_flags |= MATCH_IRE_ZONEONLY;
15180 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15181 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15182 	if (ire != NULL) {
15183 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15184 		ire_refrele(ire);
15185 	}
15186 	return (zoneid);
15187 }
15188 
15189 /*
15190  * IP obserability hook support functions.
15191  */
15192 static void
15193 ipobs_init(ip_stack_t *ipst)
15194 {
15195 	netid_t id;
15196 
15197 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15198 
15199 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15200 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15201 
15202 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15203 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15204 }
15205 
15206 static void
15207 ipobs_fini(ip_stack_t *ipst)
15208 {
15209 
15210 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15211 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15212 }
15213 
15214 /*
15215  * hook_pkt_observe_t is composed in network byte order so that the
15216  * entire mblk_t chain handed into hook_run can be used as-is.
15217  * The caveat is that use of the fields, such as the zone fields,
15218  * requires conversion into host byte order first.
15219  */
15220 void
15221 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15222     const ill_t *ill, ip_stack_t *ipst)
15223 {
15224 	hook_pkt_observe_t *hdr;
15225 	uint64_t grifindex;
15226 	mblk_t *imp;
15227 
15228 	imp = allocb(sizeof (*hdr), BPRI_HI);
15229 	if (imp == NULL)
15230 		return;
15231 
15232 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15233 	/*
15234 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15235 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15236 	 */
15237 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15238 	imp->b_cont = mp;
15239 
15240 	ASSERT(DB_TYPE(mp) == M_DATA);
15241 
15242 	if (IS_UNDER_IPMP(ill))
15243 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15244 	else
15245 		grifindex = 0;
15246 
15247 	hdr->hpo_version = 1;
15248 	hdr->hpo_htype = htons(htype);
15249 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15250 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15251 	hdr->hpo_grifindex = htonl(grifindex);
15252 	hdr->hpo_zsrc = htonl(zsrc);
15253 	hdr->hpo_zdst = htonl(zdst);
15254 	hdr->hpo_pkt = imp;
15255 	hdr->hpo_ctx = ipst->ips_netstack;
15256 
15257 	if (ill->ill_isv6) {
15258 		hdr->hpo_family = AF_INET6;
15259 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15260 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15261 	} else {
15262 		hdr->hpo_family = AF_INET;
15263 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15264 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15265 	}
15266 
15267 	imp->b_cont = NULL;
15268 	freemsg(imp);
15269 }
15270 
15271 /*
15272  * Utility routine that checks if `v4srcp' is a valid address on underlying
15273  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15274  * associated with `v4srcp' on success.  NOTE: if this is not called from
15275  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15276  * group during or after this lookup.
15277  */
15278 boolean_t
15279 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15280 {
15281 	ipif_t *ipif;
15282 
15283 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15284 	if (ipif != NULL) {
15285 		if (ipifp != NULL)
15286 			*ipifp = ipif;
15287 		else
15288 			ipif_refrele(ipif);
15289 		return (B_TRUE);
15290 	}
15291 
15292 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15293 	    *v4srcp));
15294 	return (B_FALSE);
15295 }
15296 
15297 /*
15298  * Transport protocol call back function for CPU state change.
15299  */
15300 /* ARGSUSED */
15301 static int
15302 ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
15303 {
15304 	processorid_t cpu_seqid;
15305 	netstack_handle_t nh;
15306 	netstack_t *ns;
15307 
15308 	ASSERT(MUTEX_HELD(&cpu_lock));
15309 
15310 	switch (what) {
15311 	case CPU_CONFIG:
15312 	case CPU_ON:
15313 	case CPU_INIT:
15314 	case CPU_CPUPART_IN:
15315 		cpu_seqid = cpu[id]->cpu_seqid;
15316 		netstack_next_init(&nh);
15317 		while ((ns = netstack_next(&nh)) != NULL) {
15318 			tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
15319 			sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
15320 			udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
15321 			netstack_rele(ns);
15322 		}
15323 		netstack_next_fini(&nh);
15324 		break;
15325 	case CPU_UNCONFIG:
15326 	case CPU_OFF:
15327 	case CPU_CPUPART_OUT:
15328 		/*
15329 		 * Nothing to do.  We don't remove the per CPU stats from
15330 		 * the IP stack even when the CPU goes offline.
15331 		 */
15332 		break;
15333 	default:
15334 		break;
15335 	}
15336 	return (0);
15337 }
15338