xref: /titanic_44/usr/src/uts/common/inet/ip/ip.c (revision d564a1c2c392e37baec0f96c9fa5796b264af787)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 1990 Mentat Inc.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/stream.h>
29 #include <sys/dlpi.h>
30 #include <sys/stropts.h>
31 #include <sys/sysmacros.h>
32 #include <sys/strsubr.h>
33 #include <sys/strlog.h>
34 #include <sys/strsun.h>
35 #include <sys/zone.h>
36 #define	_SUN_TPI_VERSION 2
37 #include <sys/tihdr.h>
38 #include <sys/xti_inet.h>
39 #include <sys/ddi.h>
40 #include <sys/suntpi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/sadb.h>
98 #include <inet/ipsec_impl.h>
99 #include <inet/iptun/iptun_impl.h>
100 #include <inet/ipdrop.h>
101 #include <inet/ip_netinfo.h>
102 #include <inet/ilb_ip.h>
103 
104 #include <sys/ethernet.h>
105 #include <net/if_types.h>
106 #include <sys/cpuvar.h>
107 
108 #include <ipp/ipp.h>
109 #include <ipp/ipp_impl.h>
110 #include <ipp/ipgpc/ipgpc.h>
111 
112 #include <sys/pattr.h>
113 #include <inet/ipclassifier.h>
114 #include <inet/sctp_ip.h>
115 #include <inet/sctp/sctp_impl.h>
116 #include <inet/udp_impl.h>
117 #include <inet/rawip_impl.h>
118 #include <inet/rts_impl.h>
119 
120 #include <sys/tsol/label.h>
121 #include <sys/tsol/tnet.h>
122 
123 #include <sys/squeue_impl.h>
124 #include <inet/ip_arp.h>
125 
126 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
131  * IP_SQUEUE_ENTER: SQ_PROCESS
132  * IP_SQUEUE_FILL: SQ_FILL
133  */
134 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
135 
136 int ip_squeue_flag;
137 
138 /*
139  * Setable in /etc/system
140  */
141 int ip_poll_normal_ms = 100;
142 int ip_poll_normal_ticks = 0;
143 int ip_modclose_ackwait_ms = 3000;
144 
145 /*
146  * It would be nice to have these present only in DEBUG systems, but the
147  * current design of the global symbol checking logic requires them to be
148  * unconditionally present.
149  */
150 uint_t ip_thread_data;			/* TSD key for debug support */
151 krwlock_t ip_thread_rwlock;
152 list_t	ip_thread_list;
153 
154 /*
155  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
156  */
157 
158 struct listptr_s {
159 	mblk_t	*lp_head;	/* pointer to the head of the list */
160 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
161 };
162 
163 typedef struct listptr_s listptr_t;
164 
165 /*
166  * This is used by ip_snmp_get_mib2_ip_route_media and
167  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
168  */
169 typedef struct iproutedata_s {
170 	uint_t		ird_idx;
171 	uint_t		ird_flags;	/* see below */
172 	listptr_t	ird_route;	/* ipRouteEntryTable */
173 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
174 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
175 } iproutedata_t;
176 
177 /* Include ire_testhidden and IRE_IF_CLONE routes */
178 #define	IRD_REPORT_ALL	0x01
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
199     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
200     void *args) = NULL;
201 
202 /*
203  * Hook function to generate cluster wide SPI.
204  */
205 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
206     void *) = NULL;
207 
208 /*
209  * Hook function to verify if the SPI is already utlized.
210  */
211 
212 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
213 
214 /*
215  * Hook function to delete the SPI from the cluster wide repository.
216  */
217 
218 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
219 
220 /*
221  * Hook function to inform the cluster when packet received on an IDLE SA
222  */
223 
224 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
225     in6_addr_t, in6_addr_t, void *) = NULL;
226 
227 /*
228  * Synchronization notes:
229  *
230  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
231  * MT level protection given by STREAMS. IP uses a combination of its own
232  * internal serialization mechanism and standard Solaris locking techniques.
233  * The internal serialization is per phyint.  This is used to serialize
234  * plumbing operations, IPMP operations, most set ioctls, etc.
235  *
236  * Plumbing is a long sequence of operations involving message
237  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
238  * involved in plumbing operations. A natural model is to serialize these
239  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
240  * parallel without any interference. But various set ioctls on hme0 are best
241  * serialized, along with IPMP operations and processing of DLPI control
242  * messages received from drivers on a per phyint basis. This serialization is
243  * provided by the ipsq_t and primitives operating on this. Details can
244  * be found in ip_if.c above the core primitives operating on ipsq_t.
245  *
246  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
247  * Simiarly lookup of an ire by a thread also returns a refheld ire.
248  * In addition ipif's and ill's referenced by the ire are also indirectly
249  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
250  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
251  * address of an ipif has to go through the ipsq_t. This ensures that only
252  * one such exclusive operation proceeds at any time on the ipif. It then
253  * waits for all refcnts
254  * associated with this ipif to come down to zero. The address is changed
255  * only after the ipif has been quiesced. Then the ipif is brought up again.
256  * More details are described above the comment in ip_sioctl_flags.
257  *
258  * Packet processing is based mostly on IREs and are fully multi-threaded
259  * using standard Solaris MT techniques.
260  *
261  * There are explicit locks in IP to handle:
262  * - The ip_g_head list maintained by mi_open_link() and friends.
263  *
264  * - The reassembly data structures (one lock per hash bucket)
265  *
266  * - conn_lock is meant to protect conn_t fields. The fields actually
267  *   protected by conn_lock are documented in the conn_t definition.
268  *
269  * - ire_lock to protect some of the fields of the ire, IRE tables
270  *   (one lock per hash bucket). Refer to ip_ire.c for details.
271  *
272  * - ndp_g_lock and ncec_lock for protecting NCEs.
273  *
274  * - ill_lock protects fields of the ill and ipif. Details in ip.h
275  *
276  * - ill_g_lock: This is a global reader/writer lock. Protects the following
277  *	* The AVL tree based global multi list of all ills.
278  *	* The linked list of all ipifs of an ill
279  *	* The <ipsq-xop> mapping
280  *	* <ill-phyint> association
281  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
282  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
283  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
284  *   writer for the actual duration of the insertion/deletion/change.
285  *
286  * - ill_lock:  This is a per ill mutex.
287  *   It protects some members of the ill_t struct; see ip.h for details.
288  *   It also protects the <ill-phyint> assoc.
289  *   It also protects the list of ipifs hanging off the ill.
290  *
291  * - ipsq_lock: This is a per ipsq_t mutex lock.
292  *   This protects some members of the ipsq_t struct; see ip.h for details.
293  *   It also protects the <ipsq-ipxop> mapping
294  *
295  * - ipx_lock: This is a per ipxop_t mutex lock.
296  *   This protects some members of the ipxop_t struct; see ip.h for details.
297  *
298  * - phyint_lock: This is a per phyint mutex lock. Protects just the
299  *   phyint_flags
300  *
301  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
302  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
303  *   uniqueness check also done atomically.
304  *
305  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
306  *   group list linked by ill_usesrc_grp_next. It also protects the
307  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
308  *   group is being added or deleted.  This lock is taken as a reader when
309  *   walking the list/group(eg: to get the number of members in a usesrc group).
310  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
311  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
312  *   example, it is not necessary to take this lock in the initial portion
313  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
314  *   operations are executed exclusively and that ensures that the "usesrc
315  *   group state" cannot change. The "usesrc group state" change can happen
316  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ipsq-xop> assocications:
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ipsq-xop> association, the ill_g_lock must be held as
325  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
326  * This is only done when ills are added or removed from IPMP groups.
327  *
328  * To add or delete an ipif from the list of ipifs hanging off the ill,
329  * ill_g_lock (writer) and ill_lock must be held and the thread must be
330  * a writer on the associated ipsq.
331  *
332  * To add or delete an ill to the system, the ill_g_lock must be held as
333  * writer and the thread must be a writer on the associated ipsq.
334  *
335  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
336  * must be a writer on the associated ipsq.
337  *
338  * Lock hierarchy
339  *
340  * Some lock hierarchy scenarios are listed below.
341  *
342  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
343  * ill_g_lock -> ill_lock(s) -> phyint_lock
344  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
345  * ill_g_lock -> ip_addr_avail_lock
346  * conn_lock -> irb_lock -> ill_lock -> ire_lock
347  * ill_g_lock -> ip_g_nd_lock
348  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
350  * arl_lock -> ill_lock
351  * ips_ire_dep_lock -> irb_lock
352  *
353  * When more than 1 ill lock is needed to be held, all ill lock addresses
354  * are sorted on address and locked starting from highest addressed lock
355  * downward.
356  *
357  * Multicast scenarios
358  * ips_ill_g_lock -> ill_mcast_lock
359  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
360  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
361  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
362  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
363  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
364  *
365  * IPsec scenarios
366  *
367  * ipsa_lock -> ill_g_lock -> ill_lock
368  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
369  *
370  * Trusted Solaris scenarios
371  *
372  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
373  * igsa_lock -> gcdb_lock
374  * gcgrp_rwlock -> ire_lock
375  * gcgrp_rwlock -> gcdb_lock
376  *
377  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
378  *
379  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
380  * sq_lock -> conn_lock -> QLOCK(q)
381  * ill_lock -> ft_lock -> fe_lock
382  *
383  * Routing/forwarding table locking notes:
384  *
385  * Lock acquisition order: Radix tree lock, irb_lock.
386  * Requirements:
387  * i.  Walker must not hold any locks during the walker callback.
388  * ii  Walker must not see a truncated tree during the walk because of any node
389  *     deletion.
390  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
391  *     in many places in the code to walk the irb list. Thus even if all the
392  *     ires in a bucket have been deleted, we still can't free the radix node
393  *     until the ires have actually been inactive'd (freed).
394  *
395  * Tree traversal - Need to hold the global tree lock in read mode.
396  * Before dropping the global tree lock, need to either increment the ire_refcnt
397  * to ensure that the radix node can't be deleted.
398  *
399  * Tree add - Need to hold the global tree lock in write mode to add a
400  * radix node. To prevent the node from being deleted, increment the
401  * irb_refcnt, after the node is added to the tree. The ire itself is
402  * added later while holding the irb_lock, but not the tree lock.
403  *
404  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
405  * All associated ires must be inactive (i.e. freed), and irb_refcnt
406  * must be zero.
407  *
408  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
409  * global tree lock (read mode) for traversal.
410  *
411  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
412  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
413  *
414  * IPsec notes :
415  *
416  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
417  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
418  * ip_xmit_attr_t has the
419  * information used by the IPsec code for applying the right level of
420  * protection. The information initialized by IP in the ip_xmit_attr_t
421  * is determined by the per-socket policy or global policy in the system.
422  * For inbound datagrams, the ip_recv_attr_t
423  * starts out with nothing in it. It gets filled
424  * with the right information if it goes through the AH/ESP code, which
425  * happens if the incoming packet is secure. The information initialized
426  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
427  * the policy requirements needed by per-socket policy or global policy
428  * is met or not.
429  *
430  * For fully connected sockets i.e dst, src [addr, port] is known,
431  * conn_policy_cached is set indicating that policy has been cached.
432  * conn_in_enforce_policy may or may not be set depending on whether
433  * there is a global policy match or per-socket policy match.
434  * Policy inheriting happpens in ip_policy_set once the destination is known.
435  * Once the right policy is set on the conn_t, policy cannot change for
436  * this socket. This makes life simpler for TCP (UDP ?) where
437  * re-transmissions go out with the same policy. For symmetry, policy
438  * is cached for fully connected UDP sockets also. Thus if policy is cached,
439  * it also implies that policy is latched i.e policy cannot change
440  * on these sockets. As we have the right policy on the conn, we don't
441  * have to lookup global policy for every outbound and inbound datagram
442  * and thus serving as an optimization. Note that a global policy change
443  * does not affect fully connected sockets if they have policy. If fully
444  * connected sockets did not have any policy associated with it, global
445  * policy change may affect them.
446  *
447  * IP Flow control notes:
448  * ---------------------
449  * Non-TCP streams are flow controlled by IP. The way this is accomplished
450  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
451  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
452  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
453  * functions.
454  *
455  * Per Tx ring udp flow control:
456  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
457  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
458  *
459  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
460  * To achieve best performance, outgoing traffic need to be fanned out among
461  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
462  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
463  * the address of connp as fanout hint to mac_tx(). Under flow controlled
464  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
465  * cookie points to a specific Tx ring that is blocked. The cookie is used to
466  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
467  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
468  * connp's. The drain list is not a single list but a configurable number of
469  * lists.
470  *
471  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
472  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
473  * which is equal to 128. This array in turn contains a pointer to idl_t[],
474  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
475  * list will point to the list of connp's that are flow controlled.
476  *
477  *                      ---------------   -------   -------   -------
478  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
479  *                   |  ---------------   -------   -------   -------
480  *                   |  ---------------   -------   -------   -------
481  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
482  * ----------------  |  ---------------   -------   -------   -------
483  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
484  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   .        .              .         .         .
487  *                   |  ---------------   -------   -------   -------
488  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
489  *                      ---------------   -------   -------   -------
490  *                      ---------------   -------   -------   -------
491  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
492  *                   |  ---------------   -------   -------   -------
493  *                   |  ---------------   -------   -------   -------
494  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
495  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
496  * ----------------  |        .              .         .         .
497  *                   |  ---------------   -------   -------   -------
498  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
499  *                      ---------------   -------   -------   -------
500  *     .....
501  * ----------------
502  * |idl_tx_list[n]|-> ...
503  * ----------------
504  *
505  * When mac_tx() returns a cookie, the cookie is hashed into an index into
506  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
507  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
508  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
509  * Further, conn_blocked is set to indicate that the conn is blocked.
510  *
511  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
512  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
513  * is again hashed to locate the appropriate idl_tx_list, which is then
514  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
515  * the drain list and calls conn_drain_remove() to clear flow control (via
516  * calling su_txq_full() or clearing QFULL), and remove the conn from the
517  * drain list.
518  *
519  * Note that the drain list is not a single list but a (configurable) array of
520  * lists (8 elements by default).  Synchronization between drain insertion and
521  * flow control wakeup is handled by using idl_txl->txl_lock, and only
522  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
523  *
524  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
525  * On the send side, if the packet cannot be sent down to the driver by IP
526  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
527  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
528  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
529  * control has been relieved, the blocked conns in the 0'th drain list are
530  * drained as in the non-STREAMS case.
531  *
532  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
533  * is done when the conn is inserted into the drain list (conn_drain_insert())
534  * and cleared when the conn is removed from the it (conn_drain_remove()).
535  *
536  * IPQOS notes:
537  *
538  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
539  * and IPQoS modules. IPPF includes hooks in IP at different control points
540  * (callout positions) which direct packets to IPQoS modules for policy
541  * processing. Policies, if present, are global.
542  *
543  * The callout positions are located in the following paths:
544  *		o local_in (packets destined for this host)
545  *		o local_out (packets orginating from this host )
546  *		o fwd_in  (packets forwarded by this m/c - inbound)
547  *		o fwd_out (packets forwarded by this m/c - outbound)
548  * Hooks at these callout points can be enabled/disabled using the ndd variable
549  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
550  * By default all the callout positions are enabled.
551  *
552  * Outbound (local_out)
553  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
554  *
555  * Inbound (local_in)
556  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
557  *
558  * Forwarding (in and out)
559  * Hooks are placed in ire_recv_forward_v4/v6.
560  *
561  * IP Policy Framework processing (IPPF processing)
562  * Policy processing for a packet is initiated by ip_process, which ascertains
563  * that the classifier (ipgpc) is loaded and configured, failing which the
564  * packet resumes normal processing in IP. If the clasifier is present, the
565  * packet is acted upon by one or more IPQoS modules (action instances), per
566  * filters configured in ipgpc and resumes normal IP processing thereafter.
567  * An action instance can drop a packet in course of its processing.
568  *
569  * Zones notes:
570  *
571  * The partitioning rules for networking are as follows:
572  * 1) Packets coming from a zone must have a source address belonging to that
573  * zone.
574  * 2) Packets coming from a zone can only be sent on a physical interface on
575  * which the zone has an IP address.
576  * 3) Between two zones on the same machine, packet delivery is only allowed if
577  * there's a matching route for the destination and zone in the forwarding
578  * table.
579  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
580  * different zones can bind to the same port with the wildcard address
581  * (INADDR_ANY).
582  *
583  * The granularity of interface partitioning is at the logical interface level.
584  * Therefore, every zone has its own IP addresses, and incoming packets can be
585  * attributed to a zone unambiguously. A logical interface is placed into a zone
586  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
587  * structure. Rule (1) is implemented by modifying the source address selection
588  * algorithm so that the list of eligible addresses is filtered based on the
589  * sending process zone.
590  *
591  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
592  * across all zones, depending on their type. Here is the break-up:
593  *
594  * IRE type				Shared/exclusive
595  * --------				----------------
596  * IRE_BROADCAST			Exclusive
597  * IRE_DEFAULT (default routes)		Shared (*)
598  * IRE_LOCAL				Exclusive (x)
599  * IRE_LOOPBACK				Exclusive
600  * IRE_PREFIX (net routes)		Shared (*)
601  * IRE_IF_NORESOLVER (interface routes)	Exclusive
602  * IRE_IF_RESOLVER (interface routes)	Exclusive
603  * IRE_IF_CLONE (interface routes)	Exclusive
604  * IRE_HOST (host routes)		Shared (*)
605  *
606  * (*) A zone can only use a default or off-subnet route if the gateway is
607  * directly reachable from the zone, that is, if the gateway's address matches
608  * one of the zone's logical interfaces.
609  *
610  * (x) IRE_LOCAL are handled a bit differently.
611  * When ip_restrict_interzone_loopback is set (the default),
612  * ire_route_recursive restricts loopback using an IRE_LOCAL
613  * between zone to the case when L2 would have conceptually looped the packet
614  * back, i.e. the loopback which is required since neither Ethernet drivers
615  * nor Ethernet hardware loops them back. This is the case when the normal
616  * routes (ignoring IREs with different zoneids) would send out the packet on
617  * the same ill as the ill with which is IRE_LOCAL is associated.
618  *
619  * Multiple zones can share a common broadcast address; typically all zones
620  * share the 255.255.255.255 address. Incoming as well as locally originated
621  * broadcast packets must be dispatched to all the zones on the broadcast
622  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
623  * since some zones may not be on the 10.16.72/24 network. To handle this, each
624  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
625  * sent to every zone that has an IRE_BROADCAST entry for the destination
626  * address on the input ill, see ip_input_broadcast().
627  *
628  * Applications in different zones can join the same multicast group address.
629  * The same logic applies for multicast as for broadcast. ip_input_multicast
630  * dispatches packets to all zones that have members on the physical interface.
631  */
632 
633 /*
634  * Squeue Fanout flags:
635  *	0: No fanout.
636  *	1: Fanout across all squeues
637  */
638 boolean_t	ip_squeue_fanout = 0;
639 
640 /*
641  * Maximum dups allowed per packet.
642  */
643 uint_t ip_max_frag_dups = 10;
644 
645 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
646 		    cred_t *credp, boolean_t isv6);
647 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
648 
649 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
650 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
651 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
652     ip_recv_attr_t *);
653 static void	icmp_options_update(ipha_t *);
654 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
655 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
656 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
657 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
658     ip_recv_attr_t *);
659 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
660 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
661     ip_recv_attr_t *);
662 
663 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
664 char		*ip_dot_addr(ipaddr_t, char *);
665 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
666 int		ip_close(queue_t *, int);
667 static char	*ip_dot_saddr(uchar_t *, char *);
668 static void	ip_lrput(queue_t *, mblk_t *);
669 ipaddr_t	ip_net_mask(ipaddr_t);
670 char		*ip_nv_lookup(nv_t *, int);
671 void	ip_rput(queue_t *, mblk_t *);
672 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
673 		    void *dummy_arg);
674 int		ip_snmp_get(queue_t *, mblk_t *, int, boolean_t);
675 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
676 		    mib2_ipIfStatsEntry_t *, ip_stack_t *, boolean_t);
677 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
678 		    ip_stack_t *, boolean_t);
679 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *,
680 		    boolean_t);
681 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
686 		    ip_stack_t *ipst, boolean_t);
687 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
688 		    ip_stack_t *ipst, boolean_t);
689 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst);
691 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
698 		    ip_stack_t *ipst);
699 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
700 		    ip_stack_t *ipst);
701 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
702 		    ip_stack_t *ipst);
703 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
704 		    ip_stack_t *ipst);
705 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
706 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
707 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
708 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
709 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
710 
711 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
712 		    mblk_t *);
713 
714 static void	conn_drain_init(ip_stack_t *);
715 static void	conn_drain_fini(ip_stack_t *);
716 static void	conn_drain(conn_t *connp, boolean_t closing);
717 
718 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
719 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
720 
721 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
722 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
723 static void	ip_stack_fini(netstackid_t stackid, void *arg);
724 
725 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
726     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
727     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
728     const in6_addr_t *);
729 
730 static int	ip_squeue_switch(int);
731 
732 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
733 static void	ip_kstat_fini(netstackid_t, kstat_t *);
734 static int	ip_kstat_update(kstat_t *kp, int rw);
735 static void	*icmp_kstat_init(netstackid_t);
736 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
737 static int	icmp_kstat_update(kstat_t *kp, int rw);
738 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
739 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
740 
741 static void	ipobs_init(ip_stack_t *);
742 static void	ipobs_fini(ip_stack_t *);
743 
744 static int	ip_tp_cpu_update(cpu_setup_t, int, void *);
745 
746 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
747 
748 static long ip_rput_pullups;
749 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
750 
751 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
752 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
753 
754 int	ip_debug;
755 
756 /*
757  * Multirouting/CGTP stuff
758  */
759 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
760 
761 /*
762  * IP tunables related declarations. Definitions are in ip_tunables.c
763  */
764 extern mod_prop_info_t ip_propinfo_tbl[];
765 extern int ip_propinfo_count;
766 
767 /*
768  * Table of IP ioctls encoding the various properties of the ioctl and
769  * indexed based on the last byte of the ioctl command. Occasionally there
770  * is a clash, and there is more than 1 ioctl with the same last byte.
771  * In such a case 1 ioctl is encoded in the ndx table and the remaining
772  * ioctls are encoded in the misc table. An entry in the ndx table is
773  * retrieved by indexing on the last byte of the ioctl command and comparing
774  * the ioctl command with the value in the ndx table. In the event of a
775  * mismatch the misc table is then searched sequentially for the desired
776  * ioctl command.
777  *
778  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
779  */
780 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
781 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
782 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
783 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
784 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
785 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
786 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
787 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
788 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
789 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
790 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
791 
792 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
793 			MISC_CMD, ip_siocaddrt, NULL },
794 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
795 			MISC_CMD, ip_siocdelrt, NULL },
796 
797 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
798 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
799 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
800 			IF_CMD, ip_sioctl_get_addr, NULL },
801 
802 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
803 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
804 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
805 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
806 
807 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
808 			IPI_PRIV | IPI_WR,
809 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
810 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
811 			IPI_MODOK | IPI_GET_CMD,
812 			IF_CMD, ip_sioctl_get_flags, NULL },
813 
814 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
815 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
816 
817 	/* copyin size cannot be coded for SIOCGIFCONF */
818 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
819 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
820 
821 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
822 			IF_CMD, ip_sioctl_mtu, NULL },
823 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
824 			IF_CMD, ip_sioctl_get_mtu, NULL },
825 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
826 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
827 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
828 			IF_CMD, ip_sioctl_brdaddr, NULL },
829 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
830 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
831 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
832 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
833 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
834 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
835 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
836 			IF_CMD, ip_sioctl_metric, NULL },
837 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
838 
839 	/* See 166-168 below for extended SIOC*XARP ioctls */
840 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
841 			ARP_CMD, ip_sioctl_arp, NULL },
842 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
843 			ARP_CMD, ip_sioctl_arp, NULL },
844 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
845 			ARP_CMD, ip_sioctl_arp, NULL },
846 
847 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
848 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
849 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
850 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
851 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
852 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
853 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
854 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
855 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
856 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
857 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
858 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
859 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
860 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
861 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
862 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
863 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
864 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
865 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
866 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
867 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
868 
869 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
870 			MISC_CMD, if_unitsel, if_unitsel_restart },
871 
872 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
873 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
874 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
875 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
876 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
877 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
878 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
879 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
880 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
881 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
882 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
883 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
884 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
885 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
886 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
887 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
888 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
889 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
890 
891 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
892 			IPI_PRIV | IPI_WR | IPI_MODOK,
893 			IF_CMD, ip_sioctl_sifname, NULL },
894 
895 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
896 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
897 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
898 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
899 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
900 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
901 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
902 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
903 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
904 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
905 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
906 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
907 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
908 
909 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
910 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
911 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
912 			IF_CMD, ip_sioctl_get_muxid, NULL },
913 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
914 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
915 
916 	/* Both if and lif variants share same func */
917 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
918 			IF_CMD, ip_sioctl_get_lifindex, NULL },
919 	/* Both if and lif variants share same func */
920 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
921 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
922 
923 	/* copyin size cannot be coded for SIOCGIFCONF */
924 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
925 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
926 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
927 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
928 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
929 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
930 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
931 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
932 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
933 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
934 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
935 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
936 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
937 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
938 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
939 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
940 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
941 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
942 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
943 
944 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
945 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
946 			ip_sioctl_removeif_restart },
947 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
948 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
949 			LIF_CMD, ip_sioctl_addif, NULL },
950 #define	SIOCLIFADDR_NDX 112
951 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
952 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
953 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
954 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
955 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
956 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
957 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
958 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
959 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
960 			IPI_PRIV | IPI_WR,
961 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
962 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
963 			IPI_GET_CMD | IPI_MODOK,
964 			LIF_CMD, ip_sioctl_get_flags, NULL },
965 
966 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
967 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
968 
969 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
970 			ip_sioctl_get_lifconf, NULL },
971 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
972 			LIF_CMD, ip_sioctl_mtu, NULL },
973 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
974 			LIF_CMD, ip_sioctl_get_mtu, NULL },
975 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
976 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
977 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
978 			LIF_CMD, ip_sioctl_brdaddr, NULL },
979 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
980 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
981 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
982 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
983 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
984 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
985 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
986 			LIF_CMD, ip_sioctl_metric, NULL },
987 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
988 			IPI_PRIV | IPI_WR | IPI_MODOK,
989 			LIF_CMD, ip_sioctl_slifname,
990 			ip_sioctl_slifname_restart },
991 
992 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
993 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
994 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
995 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
996 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
997 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
998 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
999 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1000 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1001 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1002 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1003 			LIF_CMD, ip_sioctl_token, NULL },
1004 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1005 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1006 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1007 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1008 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1009 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1010 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1011 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1012 
1013 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1014 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1015 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1016 			LIF_CMD, ip_siocdelndp_v6, NULL },
1017 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1018 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1019 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1020 			LIF_CMD, ip_siocsetndp_v6, NULL },
1021 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1022 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1023 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1024 			MISC_CMD, ip_sioctl_tonlink, NULL },
1025 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1026 			MISC_CMD, ip_sioctl_tmysite, NULL },
1027 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1030 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1031 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1032 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1033 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1034 
1035 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 
1037 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1038 			LIF_CMD, ip_sioctl_get_binding, NULL },
1039 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1040 			IPI_PRIV | IPI_WR,
1041 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1042 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1043 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1044 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1045 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1046 
1047 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1048 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 
1052 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 
1054 	/* These are handled in ip_sioctl_copyin_setup itself */
1055 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1056 			MISC_CMD, NULL, NULL },
1057 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1058 			MISC_CMD, NULL, NULL },
1059 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1060 
1061 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1062 			ip_sioctl_get_lifconf, NULL },
1063 
1064 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1065 			XARP_CMD, ip_sioctl_arp, NULL },
1066 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1067 			XARP_CMD, ip_sioctl_arp, NULL },
1068 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1069 			XARP_CMD, ip_sioctl_arp, NULL },
1070 
1071 	/* SIOCPOPSOCKFS is not handled by IP */
1072 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1073 
1074 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1075 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1076 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1077 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1078 			ip_sioctl_slifzone_restart },
1079 	/* 172-174 are SCTP ioctls and not handled by IP */
1080 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1084 			IPI_GET_CMD, LIF_CMD,
1085 			ip_sioctl_get_lifusesrc, 0 },
1086 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1087 			IPI_PRIV | IPI_WR,
1088 			LIF_CMD, ip_sioctl_slifusesrc,
1089 			NULL },
1090 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1091 			ip_sioctl_get_lifsrcof, NULL },
1092 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1093 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1094 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1095 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1096 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1097 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1098 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1099 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1100 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* SIOCSENABLESDP is handled by SDP */
1102 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1103 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1104 	/* 185 */ { SIOCGIFHWADDR, sizeof (struct ifreq), IPI_GET_CMD,
1105 			IF_CMD, ip_sioctl_get_ifhwaddr, NULL },
1106 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1107 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1108 			ip_sioctl_ilb_cmd, NULL },
1109 	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1110 	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1111 	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1112 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1113 	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1114 			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart },
1115 	/* 192 */ { SIOCGLIFHWADDR, sizeof (struct lifreq), IPI_GET_CMD,
1116 			LIF_CMD, ip_sioctl_get_lifhwaddr, NULL }
1117 };
1118 
1119 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1120 
1121 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1122 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1123 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1124 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1125 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1126 	{ ND_GET,	0, 0, 0, NULL, NULL },
1127 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1128 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1129 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1130 		MISC_CMD, mrt_ioctl},
1131 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1132 		MISC_CMD, mrt_ioctl},
1133 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1134 		MISC_CMD, mrt_ioctl}
1135 };
1136 
1137 int ip_misc_ioctl_count =
1138     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1139 
1140 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1141 					/* Settable in /etc/system */
1142 /* Defined in ip_ire.c */
1143 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1144 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1145 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1146 
1147 static nv_t	ire_nv_arr[] = {
1148 	{ IRE_BROADCAST, "BROADCAST" },
1149 	{ IRE_LOCAL, "LOCAL" },
1150 	{ IRE_LOOPBACK, "LOOPBACK" },
1151 	{ IRE_DEFAULT, "DEFAULT" },
1152 	{ IRE_PREFIX, "PREFIX" },
1153 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1154 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1155 	{ IRE_IF_CLONE, "IF_CLONE" },
1156 	{ IRE_HOST, "HOST" },
1157 	{ IRE_MULTICAST, "MULTICAST" },
1158 	{ IRE_NOROUTE, "NOROUTE" },
1159 	{ 0 }
1160 };
1161 
1162 nv_t	*ire_nv_tbl = ire_nv_arr;
1163 
1164 /* Simple ICMP IP Header Template */
1165 static ipha_t icmp_ipha = {
1166 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1167 };
1168 
1169 struct module_info ip_mod_info = {
1170 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1171 	IP_MOD_LOWAT
1172 };
1173 
1174 /*
1175  * Duplicate static symbols within a module confuses mdb; so we avoid the
1176  * problem by making the symbols here distinct from those in udp.c.
1177  */
1178 
1179 /*
1180  * Entry points for IP as a device and as a module.
1181  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1182  */
1183 static struct qinit iprinitv4 = {
1184 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1185 	&ip_mod_info
1186 };
1187 
1188 struct qinit iprinitv6 = {
1189 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1190 	&ip_mod_info
1191 };
1192 
1193 static struct qinit ipwinit = {
1194 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1195 	&ip_mod_info
1196 };
1197 
1198 static struct qinit iplrinit = {
1199 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1200 	&ip_mod_info
1201 };
1202 
1203 static struct qinit iplwinit = {
1204 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1205 	&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 		    now.tv_nsec / (NANOSEC / MILLISEC);
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 		/* FALLTHRU */
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 		/* FALLTHRU */
2283 	}
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 		/* FALLTHRU */
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 	switch (opt) {
2409 	case IPOPT_RR:
2410 	case IPOPT_TS:
2411 	case IPOPT_LSRR:
2412 	case IPOPT_SSRR:
2413 		if (len <= IPOPT_OFFSET) {
2414 			optp->ipoptp_flags |= IPOPTP_ERROR;
2415 			return (opt);
2416 		}
2417 		pointer = cur[IPOPT_OFFSET];
2418 		if (pointer - 1 > len) {
2419 			optp->ipoptp_flags |= IPOPTP_ERROR;
2420 			return (opt);
2421 		}
2422 		break;
2423 	}
2424 
2425 	/*
2426 	 * Sanity check the pointer field based on the type of the
2427 	 * option.
2428 	 */
2429 	switch (opt) {
2430 	case IPOPT_RR:
2431 	case IPOPT_SSRR:
2432 	case IPOPT_LSRR:
2433 		if (pointer < IPOPT_MINOFF_SR)
2434 			optp->ipoptp_flags |= IPOPTP_ERROR;
2435 		break;
2436 	case IPOPT_TS:
2437 		if (pointer < IPOPT_MINOFF_IT)
2438 			optp->ipoptp_flags |= IPOPTP_ERROR;
2439 		/*
2440 		 * Note that the Internet Timestamp option also
2441 		 * contains two four bit fields (the Overflow field,
2442 		 * and the Flag field), which follow the pointer
2443 		 * field.  We don't need to check that these fields
2444 		 * fall within the length of the option because this
2445 		 * was implicitely done above.  We've checked that the
2446 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2447 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2448 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2449 		 */
2450 		ASSERT(len > IPOPT_POS_OV_FLG);
2451 		break;
2452 	}
2453 
2454 	return (opt);
2455 }
2456 
2457 /*
2458  * Use the outgoing IP header to create an IP_OPTIONS option the way
2459  * it was passed down from the application.
2460  *
2461  * This is compatible with BSD in that it returns
2462  * the reverse source route with the final destination
2463  * as the last entry. The first 4 bytes of the option
2464  * will contain the final destination.
2465  */
2466 int
2467 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2468 {
2469 	ipoptp_t	opts;
2470 	uchar_t		*opt;
2471 	uint8_t		optval;
2472 	uint8_t		optlen;
2473 	uint32_t	len = 0;
2474 	uchar_t		*buf1 = buf;
2475 	uint32_t	totallen;
2476 	ipaddr_t	dst;
2477 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2478 
2479 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2480 		return (0);
2481 
2482 	totallen = ipp->ipp_ipv4_options_len;
2483 	if (totallen & 0x3)
2484 		return (0);
2485 
2486 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2487 	len += IP_ADDR_LEN;
2488 	bzero(buf1, IP_ADDR_LEN);
2489 
2490 	dst = connp->conn_faddr_v4;
2491 
2492 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2493 	    optval != IPOPT_EOL;
2494 	    optval = ipoptp_next(&opts)) {
2495 		int	off;
2496 
2497 		opt = opts.ipoptp_cur;
2498 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2499 			break;
2500 		}
2501 		optlen = opts.ipoptp_len;
2502 
2503 		switch (optval) {
2504 		case IPOPT_SSRR:
2505 		case IPOPT_LSRR:
2506 
2507 			/*
2508 			 * Insert destination as the first entry in the source
2509 			 * route and move down the entries on step.
2510 			 * The last entry gets placed at buf1.
2511 			 */
2512 			buf[IPOPT_OPTVAL] = optval;
2513 			buf[IPOPT_OLEN] = optlen;
2514 			buf[IPOPT_OFFSET] = optlen;
2515 
2516 			off = optlen - IP_ADDR_LEN;
2517 			if (off < 0) {
2518 				/* No entries in source route */
2519 				break;
2520 			}
2521 			/* Last entry in source route if not already set */
2522 			if (dst == INADDR_ANY)
2523 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2524 			off -= IP_ADDR_LEN;
2525 
2526 			while (off > 0) {
2527 				bcopy(opt + off,
2528 				    buf + off + IP_ADDR_LEN,
2529 				    IP_ADDR_LEN);
2530 				off -= IP_ADDR_LEN;
2531 			}
2532 			/* ipha_dst into first slot */
2533 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2534 			    IP_ADDR_LEN);
2535 			buf += optlen;
2536 			len += optlen;
2537 			break;
2538 
2539 		default:
2540 			bcopy(opt, buf, optlen);
2541 			buf += optlen;
2542 			len += optlen;
2543 			break;
2544 		}
2545 	}
2546 done:
2547 	/* Pad the resulting options */
2548 	while (len & 0x3) {
2549 		*buf++ = IPOPT_EOL;
2550 		len++;
2551 	}
2552 	return (len);
2553 }
2554 
2555 /*
2556  * Update any record route or timestamp options to include this host.
2557  * Reverse any source route option.
2558  * This routine assumes that the options are well formed i.e. that they
2559  * have already been checked.
2560  */
2561 static void
2562 icmp_options_update(ipha_t *ipha)
2563 {
2564 	ipoptp_t	opts;
2565 	uchar_t		*opt;
2566 	uint8_t		optval;
2567 	ipaddr_t	src;		/* Our local address */
2568 	ipaddr_t	dst;
2569 
2570 	ip2dbg(("icmp_options_update\n"));
2571 	src = ipha->ipha_src;
2572 	dst = ipha->ipha_dst;
2573 
2574 	for (optval = ipoptp_first(&opts, ipha);
2575 	    optval != IPOPT_EOL;
2576 	    optval = ipoptp_next(&opts)) {
2577 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2578 		opt = opts.ipoptp_cur;
2579 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2580 		    optval, opts.ipoptp_len));
2581 		switch (optval) {
2582 			int off1, off2;
2583 		case IPOPT_SSRR:
2584 		case IPOPT_LSRR:
2585 			/*
2586 			 * Reverse the source route.  The first entry
2587 			 * should be the next to last one in the current
2588 			 * source route (the last entry is our address).
2589 			 * The last entry should be the final destination.
2590 			 */
2591 			off1 = IPOPT_MINOFF_SR - 1;
2592 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2593 			if (off2 < 0) {
2594 				/* No entries in source route */
2595 				ip1dbg((
2596 				    "icmp_options_update: bad src route\n"));
2597 				break;
2598 			}
2599 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2600 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2601 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2602 			off2 -= IP_ADDR_LEN;
2603 
2604 			while (off1 < off2) {
2605 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2606 				bcopy((char *)opt + off2, (char *)opt + off1,
2607 				    IP_ADDR_LEN);
2608 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2609 				off1 += IP_ADDR_LEN;
2610 				off2 -= IP_ADDR_LEN;
2611 			}
2612 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2613 			break;
2614 		}
2615 	}
2616 }
2617 
2618 /*
2619  * Process received ICMP Redirect messages.
2620  * Assumes the caller has verified that the headers are in the pulled up mblk.
2621  * Consumes mp.
2622  */
2623 static void
2624 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2625 {
2626 	ire_t		*ire, *nire;
2627 	ire_t		*prev_ire;
2628 	ipaddr_t  	src, dst, gateway;
2629 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2630 	ipha_t		*inner_ipha;	/* Inner IP header */
2631 
2632 	/* Caller already pulled up everything. */
2633 	inner_ipha = (ipha_t *)&icmph[1];
2634 	src = ipha->ipha_src;
2635 	dst = inner_ipha->ipha_dst;
2636 	gateway = icmph->icmph_rd_gateway;
2637 	/* Make sure the new gateway is reachable somehow. */
2638 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2639 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2640 	/*
2641 	 * Make sure we had a route for the dest in question and that
2642 	 * that route was pointing to the old gateway (the source of the
2643 	 * redirect packet.)
2644 	 * We do longest match and then compare ire_gateway_addr below.
2645 	 */
2646 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2647 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2648 	/*
2649 	 * Check that
2650 	 *	the redirect was not from ourselves
2651 	 *	the new gateway and the old gateway are directly reachable
2652 	 */
2653 	if (prev_ire == NULL || ire == NULL ||
2654 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2655 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2656 	    !(ire->ire_type & IRE_IF_ALL) ||
2657 	    prev_ire->ire_gateway_addr != src) {
2658 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2659 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2660 		freemsg(mp);
2661 		if (ire != NULL)
2662 			ire_refrele(ire);
2663 		if (prev_ire != NULL)
2664 			ire_refrele(prev_ire);
2665 		return;
2666 	}
2667 
2668 	ire_refrele(prev_ire);
2669 	ire_refrele(ire);
2670 
2671 	/*
2672 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2673 	 * require TOS routing
2674 	 */
2675 	switch (icmph->icmph_code) {
2676 	case 0:
2677 	case 1:
2678 		/* TODO: TOS specificity for cases 2 and 3 */
2679 	case 2:
2680 	case 3:
2681 		break;
2682 	default:
2683 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2684 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2685 		freemsg(mp);
2686 		return;
2687 	}
2688 	/*
2689 	 * Create a Route Association.  This will allow us to remember that
2690 	 * someone we believe told us to use the particular gateway.
2691 	 */
2692 	ire = ire_create(
2693 	    (uchar_t *)&dst,			/* dest addr */
2694 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2695 	    (uchar_t *)&gateway,		/* gateway addr */
2696 	    IRE_HOST,
2697 	    NULL,				/* ill */
2698 	    ALL_ZONES,
2699 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2700 	    NULL,				/* tsol_gc_t */
2701 	    ipst);
2702 
2703 	if (ire == NULL) {
2704 		freemsg(mp);
2705 		return;
2706 	}
2707 	nire = ire_add(ire);
2708 	/* Check if it was a duplicate entry */
2709 	if (nire != NULL && nire != ire) {
2710 		ASSERT(nire->ire_identical_ref > 1);
2711 		ire_delete(nire);
2712 		ire_refrele(nire);
2713 		nire = NULL;
2714 	}
2715 	ire = nire;
2716 	if (ire != NULL) {
2717 		ire_refrele(ire);		/* Held in ire_add */
2718 
2719 		/* tell routing sockets that we received a redirect */
2720 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2721 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2722 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2723 	}
2724 
2725 	/*
2726 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2727 	 * This together with the added IRE has the effect of
2728 	 * modifying an existing redirect.
2729 	 */
2730 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2731 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2732 	if (prev_ire != NULL) {
2733 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2734 			ire_delete(prev_ire);
2735 		ire_refrele(prev_ire);
2736 	}
2737 
2738 	freemsg(mp);
2739 }
2740 
2741 /*
2742  * Generate an ICMP parameter problem message.
2743  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2744  * constructed by the caller.
2745  */
2746 static void
2747 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2748 {
2749 	icmph_t	icmph;
2750 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2751 
2752 	mp = icmp_pkt_err_ok(mp, ira);
2753 	if (mp == NULL)
2754 		return;
2755 
2756 	bzero(&icmph, sizeof (icmph_t));
2757 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2758 	icmph.icmph_pp_ptr = ptr;
2759 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2760 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2761 }
2762 
2763 /*
2764  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2765  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2766  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2767  * an icmp error packet can be sent.
2768  * Assigns an appropriate source address to the packet. If ipha_dst is
2769  * one of our addresses use it for source. Otherwise let ip_output_simple
2770  * pick the source address.
2771  */
2772 static void
2773 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2774 {
2775 	ipaddr_t dst;
2776 	icmph_t	*icmph;
2777 	ipha_t	*ipha;
2778 	uint_t	len_needed;
2779 	size_t	msg_len;
2780 	mblk_t	*mp1;
2781 	ipaddr_t src;
2782 	ire_t	*ire;
2783 	ip_xmit_attr_t ixas;
2784 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2785 
2786 	ipha = (ipha_t *)mp->b_rptr;
2787 
2788 	bzero(&ixas, sizeof (ixas));
2789 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2790 	ixas.ixa_zoneid = ira->ira_zoneid;
2791 	ixas.ixa_ifindex = 0;
2792 	ixas.ixa_ipst = ipst;
2793 	ixas.ixa_cred = kcred;
2794 	ixas.ixa_cpid = NOPID;
2795 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2796 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2797 
2798 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2799 		/*
2800 		 * Apply IPsec based on how IPsec was applied to
2801 		 * the packet that had the error.
2802 		 *
2803 		 * If it was an outbound packet that caused the ICMP
2804 		 * error, then the caller will have setup the IRA
2805 		 * appropriately.
2806 		 */
2807 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2808 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2809 			/* Note: mp already consumed and ip_drop_packet done */
2810 			return;
2811 		}
2812 	} else {
2813 		/*
2814 		 * This is in clear. The icmp message we are building
2815 		 * here should go out in clear, independent of our policy.
2816 		 */
2817 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2818 	}
2819 
2820 	/* Remember our eventual destination */
2821 	dst = ipha->ipha_src;
2822 
2823 	/*
2824 	 * If the packet was for one of our unicast addresses, make
2825 	 * sure we respond with that as the source. Otherwise
2826 	 * have ip_output_simple pick the source address.
2827 	 */
2828 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2829 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2830 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2831 	if (ire != NULL) {
2832 		ire_refrele(ire);
2833 		src = ipha->ipha_dst;
2834 	} else {
2835 		src = INADDR_ANY;
2836 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2837 	}
2838 
2839 	/*
2840 	 * Check if we can send back more then 8 bytes in addition to
2841 	 * the IP header.  We try to send 64 bytes of data and the internal
2842 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2843 	 */
2844 	len_needed = IPH_HDR_LENGTH(ipha);
2845 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2846 	    ipha->ipha_protocol == IPPROTO_IPV6) {
2847 		if (!pullupmsg(mp, -1)) {
2848 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2849 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2850 			freemsg(mp);
2851 			return;
2852 		}
2853 		ipha = (ipha_t *)mp->b_rptr;
2854 
2855 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2856 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2857 			    len_needed));
2858 		} else {
2859 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2860 
2861 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2862 			len_needed += ip_hdr_length_v6(mp, ip6h);
2863 		}
2864 	}
2865 	len_needed += ipst->ips_ip_icmp_return;
2866 	msg_len = msgdsize(mp);
2867 	if (msg_len > len_needed) {
2868 		(void) adjmsg(mp, len_needed - msg_len);
2869 		msg_len = len_needed;
2870 	}
2871 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2872 	if (mp1 == NULL) {
2873 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2874 		freemsg(mp);
2875 		return;
2876 	}
2877 	mp1->b_cont = mp;
2878 	mp = mp1;
2879 
2880 	/*
2881 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2882 	 * node generates be accepted in peace by all on-host destinations.
2883 	 * If we do NOT assume that all on-host destinations trust
2884 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2885 	 * (Look for IXAF_TRUSTED_ICMP).
2886 	 */
2887 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2888 
2889 	ipha = (ipha_t *)mp->b_rptr;
2890 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2891 	*ipha = icmp_ipha;
2892 	ipha->ipha_src = src;
2893 	ipha->ipha_dst = dst;
2894 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2895 	msg_len += sizeof (icmp_ipha) + len;
2896 	if (msg_len > IP_MAXPACKET) {
2897 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
2898 		msg_len = IP_MAXPACKET;
2899 	}
2900 	ipha->ipha_length = htons((uint16_t)msg_len);
2901 	icmph = (icmph_t *)&ipha[1];
2902 	bcopy(stuff, icmph, len);
2903 	icmph->icmph_checksum = 0;
2904 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2905 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2906 
2907 	(void) ip_output_simple(mp, &ixas);
2908 	ixa_cleanup(&ixas);
2909 }
2910 
2911 /*
2912  * Determine if an ICMP error packet can be sent given the rate limit.
2913  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2914  * in milliseconds) and a burst size. Burst size number of packets can
2915  * be sent arbitrarely closely spaced.
2916  * The state is tracked using two variables to implement an approximate
2917  * token bucket filter:
2918  *	icmp_pkt_err_last - lbolt value when the last burst started
2919  *	icmp_pkt_err_sent - number of packets sent in current burst
2920  */
2921 boolean_t
2922 icmp_err_rate_limit(ip_stack_t *ipst)
2923 {
2924 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2925 	uint_t refilled; /* Number of packets refilled in tbf since last */
2926 	/* Guard against changes by loading into local variable */
2927 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2928 
2929 	if (err_interval == 0)
2930 		return (B_FALSE);
2931 
2932 	if (ipst->ips_icmp_pkt_err_last > now) {
2933 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2934 		ipst->ips_icmp_pkt_err_last = 0;
2935 		ipst->ips_icmp_pkt_err_sent = 0;
2936 	}
2937 	/*
2938 	 * If we are in a burst update the token bucket filter.
2939 	 * Update the "last" time to be close to "now" but make sure
2940 	 * we don't loose precision.
2941 	 */
2942 	if (ipst->ips_icmp_pkt_err_sent != 0) {
2943 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2944 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
2945 			ipst->ips_icmp_pkt_err_sent = 0;
2946 		} else {
2947 			ipst->ips_icmp_pkt_err_sent -= refilled;
2948 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2949 		}
2950 	}
2951 	if (ipst->ips_icmp_pkt_err_sent == 0) {
2952 		/* Start of new burst */
2953 		ipst->ips_icmp_pkt_err_last = now;
2954 	}
2955 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2956 		ipst->ips_icmp_pkt_err_sent++;
2957 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2958 		    ipst->ips_icmp_pkt_err_sent));
2959 		return (B_FALSE);
2960 	}
2961 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
2962 	return (B_TRUE);
2963 }
2964 
2965 /*
2966  * Check if it is ok to send an IPv4 ICMP error packet in
2967  * response to the IPv4 packet in mp.
2968  * Free the message and return null if no
2969  * ICMP error packet should be sent.
2970  */
2971 static mblk_t *
2972 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2973 {
2974 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2975 	icmph_t	*icmph;
2976 	ipha_t	*ipha;
2977 	uint_t	len_needed;
2978 
2979 	if (!mp)
2980 		return (NULL);
2981 	ipha = (ipha_t *)mp->b_rptr;
2982 	if (ip_csum_hdr(ipha)) {
2983 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2984 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2985 		freemsg(mp);
2986 		return (NULL);
2987 	}
2988 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2989 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2990 	    CLASSD(ipha->ipha_dst) ||
2991 	    CLASSD(ipha->ipha_src) ||
2992 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2993 		/* Note: only errors to the fragment with offset 0 */
2994 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2995 		freemsg(mp);
2996 		return (NULL);
2997 	}
2998 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
2999 		/*
3000 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3001 		 * errors in response to any ICMP errors.
3002 		 */
3003 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3004 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3005 			if (!pullupmsg(mp, len_needed)) {
3006 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3007 				freemsg(mp);
3008 				return (NULL);
3009 			}
3010 			ipha = (ipha_t *)mp->b_rptr;
3011 		}
3012 		icmph = (icmph_t *)
3013 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3014 		switch (icmph->icmph_type) {
3015 		case ICMP_DEST_UNREACHABLE:
3016 		case ICMP_SOURCE_QUENCH:
3017 		case ICMP_TIME_EXCEEDED:
3018 		case ICMP_PARAM_PROBLEM:
3019 		case ICMP_REDIRECT:
3020 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3021 			freemsg(mp);
3022 			return (NULL);
3023 		default:
3024 			break;
3025 		}
3026 	}
3027 	/*
3028 	 * If this is a labeled system, then check to see if we're allowed to
3029 	 * send a response to this particular sender.  If not, then just drop.
3030 	 */
3031 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3032 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3033 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3034 		freemsg(mp);
3035 		return (NULL);
3036 	}
3037 	if (icmp_err_rate_limit(ipst)) {
3038 		/*
3039 		 * Only send ICMP error packets every so often.
3040 		 * This should be done on a per port/source basis,
3041 		 * but for now this will suffice.
3042 		 */
3043 		freemsg(mp);
3044 		return (NULL);
3045 	}
3046 	return (mp);
3047 }
3048 
3049 /*
3050  * Called when a packet was sent out the same link that it arrived on.
3051  * Check if it is ok to send a redirect and then send it.
3052  */
3053 void
3054 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3055     ip_recv_attr_t *ira)
3056 {
3057 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3058 	ipaddr_t	src, nhop;
3059 	mblk_t		*mp1;
3060 	ire_t		*nhop_ire;
3061 
3062 	/*
3063 	 * Check the source address to see if it originated
3064 	 * on the same logical subnet it is going back out on.
3065 	 * If so, we should be able to send it a redirect.
3066 	 * Avoid sending a redirect if the destination
3067 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3068 	 * or if the packet was source routed out this interface.
3069 	 *
3070 	 * We avoid sending a redirect if the
3071 	 * destination is directly connected
3072 	 * because it is possible that multiple
3073 	 * IP subnets may have been configured on
3074 	 * the link, and the source may not
3075 	 * be on the same subnet as ip destination,
3076 	 * even though they are on the same
3077 	 * physical link.
3078 	 */
3079 	if ((ire->ire_type & IRE_ONLINK) ||
3080 	    ip_source_routed(ipha, ipst))
3081 		return;
3082 
3083 	nhop_ire = ire_nexthop(ire);
3084 	if (nhop_ire == NULL)
3085 		return;
3086 
3087 	nhop = nhop_ire->ire_addr;
3088 
3089 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3090 		ire_t	*ire2;
3091 
3092 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3093 		mutex_enter(&nhop_ire->ire_lock);
3094 		ire2 = nhop_ire->ire_dep_parent;
3095 		if (ire2 != NULL)
3096 			ire_refhold(ire2);
3097 		mutex_exit(&nhop_ire->ire_lock);
3098 		ire_refrele(nhop_ire);
3099 		nhop_ire = ire2;
3100 	}
3101 	if (nhop_ire == NULL)
3102 		return;
3103 
3104 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3105 
3106 	src = ipha->ipha_src;
3107 
3108 	/*
3109 	 * We look at the interface ire for the nexthop,
3110 	 * to see if ipha_src is in the same subnet
3111 	 * as the nexthop.
3112 	 */
3113 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3114 		/*
3115 		 * The source is directly connected.
3116 		 */
3117 		mp1 = copymsg(mp);
3118 		if (mp1 != NULL) {
3119 			icmp_send_redirect(mp1, nhop, ira);
3120 		}
3121 	}
3122 	ire_refrele(nhop_ire);
3123 }
3124 
3125 /*
3126  * Generate an ICMP redirect message.
3127  */
3128 static void
3129 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3130 {
3131 	icmph_t	icmph;
3132 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3133 
3134 	mp = icmp_pkt_err_ok(mp, ira);
3135 	if (mp == NULL)
3136 		return;
3137 
3138 	bzero(&icmph, sizeof (icmph_t));
3139 	icmph.icmph_type = ICMP_REDIRECT;
3140 	icmph.icmph_code = 1;
3141 	icmph.icmph_rd_gateway = gateway;
3142 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3143 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3144 }
3145 
3146 /*
3147  * Generate an ICMP time exceeded message.
3148  */
3149 void
3150 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3151 {
3152 	icmph_t	icmph;
3153 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3154 
3155 	mp = icmp_pkt_err_ok(mp, ira);
3156 	if (mp == NULL)
3157 		return;
3158 
3159 	bzero(&icmph, sizeof (icmph_t));
3160 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3161 	icmph.icmph_code = code;
3162 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3163 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3164 }
3165 
3166 /*
3167  * Generate an ICMP unreachable message.
3168  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3169  * constructed by the caller.
3170  */
3171 void
3172 icmp_unreachable(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_DEST_UNREACHABLE;
3183 	icmph.icmph_code = code;
3184 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3185 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3186 }
3187 
3188 /*
3189  * Latch in the IPsec state for a stream based the policy in the listener
3190  * and the actions in the ip_recv_attr_t.
3191  * Called directly from TCP and SCTP.
3192  */
3193 boolean_t
3194 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3195 {
3196 	ASSERT(lconnp->conn_policy != NULL);
3197 	ASSERT(connp->conn_policy == NULL);
3198 
3199 	IPPH_REFHOLD(lconnp->conn_policy);
3200 	connp->conn_policy = lconnp->conn_policy;
3201 
3202 	if (ira->ira_ipsec_action != NULL) {
3203 		if (connp->conn_latch == NULL) {
3204 			connp->conn_latch = iplatch_create();
3205 			if (connp->conn_latch == NULL)
3206 				return (B_FALSE);
3207 		}
3208 		ipsec_latch_inbound(connp, ira);
3209 	}
3210 	return (B_TRUE);
3211 }
3212 
3213 /*
3214  * Verify whether or not the IP address is a valid local address.
3215  * Could be a unicast, including one for a down interface.
3216  * If allow_mcbc then a multicast or broadcast address is also
3217  * acceptable.
3218  *
3219  * In the case of a broadcast/multicast address, however, the
3220  * upper protocol is expected to reset the src address
3221  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3222  * no packets are emitted with broadcast/multicast address as
3223  * source address (that violates hosts requirements RFC 1122)
3224  * The addresses valid for bind are:
3225  *	(1) - INADDR_ANY (0)
3226  *	(2) - IP address of an UP interface
3227  *	(3) - IP address of a DOWN interface
3228  *	(4) - valid local IP broadcast addresses. In this case
3229  *	the conn will only receive packets destined to
3230  *	the specified broadcast address.
3231  *	(5) - a multicast address. In this case
3232  *	the conn will only receive packets destined to
3233  *	the specified multicast address. Note: the
3234  *	application still has to issue an
3235  *	IP_ADD_MEMBERSHIP socket option.
3236  *
3237  * In all the above cases, the bound address must be valid in the current zone.
3238  * When the address is loopback, multicast or broadcast, there might be many
3239  * matching IREs so bind has to look up based on the zone.
3240  */
3241 ip_laddr_t
3242 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3243     ip_stack_t *ipst, boolean_t allow_mcbc)
3244 {
3245 	ire_t *src_ire;
3246 
3247 	ASSERT(src_addr != INADDR_ANY);
3248 
3249 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3250 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3251 
3252 	/*
3253 	 * If an address other than in6addr_any is requested,
3254 	 * we verify that it is a valid address for bind
3255 	 * Note: Following code is in if-else-if form for
3256 	 * readability compared to a condition check.
3257 	 */
3258 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3259 		/*
3260 		 * (2) Bind to address of local UP interface
3261 		 */
3262 		ire_refrele(src_ire);
3263 		return (IPVL_UNICAST_UP);
3264 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3265 		/*
3266 		 * (4) Bind to broadcast address
3267 		 */
3268 		ire_refrele(src_ire);
3269 		if (allow_mcbc)
3270 			return (IPVL_BCAST);
3271 		else
3272 			return (IPVL_BAD);
3273 	} else if (CLASSD(src_addr)) {
3274 		/* (5) bind to multicast address. */
3275 		if (src_ire != NULL)
3276 			ire_refrele(src_ire);
3277 
3278 		if (allow_mcbc)
3279 			return (IPVL_MCAST);
3280 		else
3281 			return (IPVL_BAD);
3282 	} else {
3283 		ipif_t *ipif;
3284 
3285 		/*
3286 		 * (3) Bind to address of local DOWN interface?
3287 		 * (ipif_lookup_addr() looks up all interfaces
3288 		 * but we do not get here for UP interfaces
3289 		 * - case (2) above)
3290 		 */
3291 		if (src_ire != NULL)
3292 			ire_refrele(src_ire);
3293 
3294 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3295 		if (ipif == NULL)
3296 			return (IPVL_BAD);
3297 
3298 		/* Not a useful source? */
3299 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3300 			ipif_refrele(ipif);
3301 			return (IPVL_BAD);
3302 		}
3303 		ipif_refrele(ipif);
3304 		return (IPVL_UNICAST_DOWN);
3305 	}
3306 }
3307 
3308 /*
3309  * Insert in the bind fanout for IPv4 and IPv6.
3310  * The caller should already have used ip_laddr_verify_v*() before calling
3311  * this.
3312  */
3313 int
3314 ip_laddr_fanout_insert(conn_t *connp)
3315 {
3316 	int		error;
3317 
3318 	/*
3319 	 * Allow setting new policies. For example, disconnects result
3320 	 * in us being called. As we would have set conn_policy_cached
3321 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3322 	 * can change after the disconnect.
3323 	 */
3324 	connp->conn_policy_cached = B_FALSE;
3325 
3326 	error = ipcl_bind_insert(connp);
3327 	if (error != 0) {
3328 		if (connp->conn_anon_port) {
3329 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3330 			    connp->conn_mlp_type, connp->conn_proto,
3331 			    ntohs(connp->conn_lport), B_FALSE);
3332 		}
3333 		connp->conn_mlp_type = mlptSingle;
3334 	}
3335 	return (error);
3336 }
3337 
3338 /*
3339  * Verify that both the source and destination addresses are valid. If
3340  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3341  * i.e. have no route to it.  Protocols like TCP want to verify destination
3342  * reachability, while tunnels do not.
3343  *
3344  * Determine the route, the interface, and (optionally) the source address
3345  * to use to reach a given destination.
3346  * Note that we allow connect to broadcast and multicast addresses when
3347  * IPDF_ALLOW_MCBC is set.
3348  * first_hop and dst_addr are normally the same, but if source routing
3349  * they will differ; in that case the first_hop is what we'll use for the
3350  * routing lookup but the dce and label checks will be done on dst_addr,
3351  *
3352  * If uinfo is set, then we fill in the best available information
3353  * we have for the destination. This is based on (in priority order) any
3354  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3355  * ill_mtu.
3356  *
3357  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3358  * always do the label check on dst_addr.
3359  */
3360 int
3361 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3362     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3363 {
3364 	ire_t		*ire = NULL;
3365 	int		error = 0;
3366 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3367 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3368 	ip_stack_t	*ipst = ixa->ixa_ipst;
3369 	dce_t		*dce;
3370 	uint_t		pmtu;
3371 	uint_t		generation;
3372 	nce_t		*nce;
3373 	ill_t		*ill = NULL;
3374 	boolean_t	multirt = B_FALSE;
3375 
3376 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3377 
3378 	/*
3379 	 * We never send to zero; the ULPs map it to the loopback address.
3380 	 * We can't allow it since we use zero to mean unitialized in some
3381 	 * places.
3382 	 */
3383 	ASSERT(dst_addr != INADDR_ANY);
3384 
3385 	if (is_system_labeled()) {
3386 		ts_label_t *tsl = NULL;
3387 
3388 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3389 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3390 		if (error != 0)
3391 			return (error);
3392 		if (tsl != NULL) {
3393 			/* Update the label */
3394 			ip_xmit_attr_replace_tsl(ixa, tsl);
3395 		}
3396 	}
3397 
3398 	setsrc = INADDR_ANY;
3399 	/*
3400 	 * Select a route; For IPMP interfaces, we would only select
3401 	 * a "hidden" route (i.e., going through a specific under_ill)
3402 	 * if ixa_ifindex has been specified.
3403 	 */
3404 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3405 	    &generation, &setsrc, &error, &multirt);
3406 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3407 	if (error != 0)
3408 		goto bad_addr;
3409 
3410 	/*
3411 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3412 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3413 	 * Otherwise the destination needn't be reachable.
3414 	 *
3415 	 * If we match on a reject or black hole, then we've got a
3416 	 * local failure.  May as well fail out the connect() attempt,
3417 	 * since it's never going to succeed.
3418 	 */
3419 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3420 		/*
3421 		 * If we're verifying destination reachability, we always want
3422 		 * to complain here.
3423 		 *
3424 		 * If we're not verifying destination reachability but the
3425 		 * destination has a route, we still want to fail on the
3426 		 * temporary address and broadcast address tests.
3427 		 *
3428 		 * In both cases do we let the code continue so some reasonable
3429 		 * information is returned to the caller. That enables the
3430 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3431 		 * use the generation mismatch path to check for the unreachable
3432 		 * case thereby avoiding any specific check in the main path.
3433 		 */
3434 		ASSERT(generation == IRE_GENERATION_VERIFY);
3435 		if (flags & IPDF_VERIFY_DST) {
3436 			/*
3437 			 * Set errno but continue to set up ixa_ire to be
3438 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3439 			 * That allows callers to use ip_output to get an
3440 			 * ICMP error back.
3441 			 */
3442 			if (!(ire->ire_type & IRE_HOST))
3443 				error = ENETUNREACH;
3444 			else
3445 				error = EHOSTUNREACH;
3446 		}
3447 	}
3448 
3449 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3450 	    !(flags & IPDF_ALLOW_MCBC)) {
3451 		ire_refrele(ire);
3452 		ire = ire_reject(ipst, B_FALSE);
3453 		generation = IRE_GENERATION_VERIFY;
3454 		error = ENETUNREACH;
3455 	}
3456 
3457 	/* Cache things */
3458 	if (ixa->ixa_ire != NULL)
3459 		ire_refrele_notr(ixa->ixa_ire);
3460 #ifdef DEBUG
3461 	ire_refhold_notr(ire);
3462 	ire_refrele(ire);
3463 #endif
3464 	ixa->ixa_ire = ire;
3465 	ixa->ixa_ire_generation = generation;
3466 
3467 	/*
3468 	 * Ensure that ixa_dce is always set any time that ixa_ire is set,
3469 	 * since some callers will send a packet to conn_ip_output() even if
3470 	 * there's an error.
3471 	 */
3472 	if (flags & IPDF_UNIQUE_DCE) {
3473 		/* Fallback to the default dce if allocation fails */
3474 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3475 		if (dce != NULL)
3476 			generation = dce->dce_generation;
3477 		else
3478 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3479 	} else {
3480 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3481 	}
3482 	ASSERT(dce != NULL);
3483 	if (ixa->ixa_dce != NULL)
3484 		dce_refrele_notr(ixa->ixa_dce);
3485 #ifdef DEBUG
3486 	dce_refhold_notr(dce);
3487 	dce_refrele(dce);
3488 #endif
3489 	ixa->ixa_dce = dce;
3490 	ixa->ixa_dce_generation = generation;
3491 
3492 	/*
3493 	 * For multicast with multirt we have a flag passed back from
3494 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3495 	 * possible multicast address.
3496 	 * We also need a flag for multicast since we can't check
3497 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3498 	 */
3499 	if (multirt) {
3500 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3501 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3502 	} else {
3503 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3504 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3505 	}
3506 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3507 		/* Get an nce to cache. */
3508 		nce = ire_to_nce(ire, firsthop, NULL);
3509 		if (nce == NULL) {
3510 			/* Allocation failure? */
3511 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3512 		} else {
3513 			if (ixa->ixa_nce != NULL)
3514 				nce_refrele(ixa->ixa_nce);
3515 			ixa->ixa_nce = nce;
3516 		}
3517 	}
3518 
3519 	/*
3520 	 * If the source address is a loopback address, the
3521 	 * destination had best be local or multicast.
3522 	 * If we are sending to an IRE_LOCAL using a loopback source then
3523 	 * it had better be the same zoneid.
3524 	 */
3525 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3526 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3527 			ire = NULL;	/* Stored in ixa_ire */
3528 			error = EADDRNOTAVAIL;
3529 			goto bad_addr;
3530 		}
3531 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3532 			ire = NULL;	/* Stored in ixa_ire */
3533 			error = EADDRNOTAVAIL;
3534 			goto bad_addr;
3535 		}
3536 	}
3537 	if (ire->ire_type & IRE_BROADCAST) {
3538 		/*
3539 		 * If the ULP didn't have a specified source, then we
3540 		 * make sure we reselect the source when sending
3541 		 * broadcasts out different interfaces.
3542 		 */
3543 		if (flags & IPDF_SELECT_SRC)
3544 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3545 		else
3546 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3547 	}
3548 
3549 	/*
3550 	 * Does the caller want us to pick a source address?
3551 	 */
3552 	if (flags & IPDF_SELECT_SRC) {
3553 		ipaddr_t	src_addr;
3554 
3555 		/*
3556 		 * We use use ire_nexthop_ill to avoid the under ipmp
3557 		 * interface for source address selection. Note that for ipmp
3558 		 * probe packets, ixa_ifindex would have been specified, and
3559 		 * the ip_select_route() invocation would have picked an ire
3560 		 * will ire_ill pointing at an under interface.
3561 		 */
3562 		ill = ire_nexthop_ill(ire);
3563 
3564 		/* If unreachable we have no ill but need some source */
3565 		if (ill == NULL) {
3566 			src_addr = htonl(INADDR_LOOPBACK);
3567 			/* Make sure we look for a better source address */
3568 			generation = SRC_GENERATION_VERIFY;
3569 		} else {
3570 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3571 			    ixa->ixa_multicast_ifaddr, zoneid,
3572 			    ipst, &src_addr, &generation, NULL);
3573 			if (error != 0) {
3574 				ire = NULL;	/* Stored in ixa_ire */
3575 				goto bad_addr;
3576 			}
3577 		}
3578 
3579 		/*
3580 		 * We allow the source address to to down.
3581 		 * However, we check that we don't use the loopback address
3582 		 * as a source when sending out on the wire.
3583 		 */
3584 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3585 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3586 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3587 			ire = NULL;	/* Stored in ixa_ire */
3588 			error = EADDRNOTAVAIL;
3589 			goto bad_addr;
3590 		}
3591 
3592 		*src_addrp = src_addr;
3593 		ixa->ixa_src_generation = generation;
3594 	}
3595 
3596 	/*
3597 	 * Make sure we don't leave an unreachable ixa_nce in place
3598 	 * since ip_select_route is used when we unplumb i.e., remove
3599 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3600 	 */
3601 	nce = ixa->ixa_nce;
3602 	if (nce != NULL && nce->nce_is_condemned) {
3603 		nce_refrele(nce);
3604 		ixa->ixa_nce = NULL;
3605 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3606 	}
3607 
3608 	/*
3609 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3610 	 * However, we can't do it for IPv4 multicast or broadcast.
3611 	 */
3612 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3613 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3614 
3615 	/*
3616 	 * Set initial value for fragmentation limit. Either conn_ip_output
3617 	 * or ULP might updates it when there are routing changes.
3618 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3619 	 */
3620 	pmtu = ip_get_pmtu(ixa);
3621 	ixa->ixa_fragsize = pmtu;
3622 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3623 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3624 		ixa->ixa_pmtu = pmtu;
3625 
3626 	/*
3627 	 * Extract information useful for some transports.
3628 	 * First we look for DCE metrics. Then we take what we have in
3629 	 * the metrics in the route, where the offlink is used if we have
3630 	 * one.
3631 	 */
3632 	if (uinfo != NULL) {
3633 		bzero(uinfo, sizeof (*uinfo));
3634 
3635 		if (dce->dce_flags & DCEF_UINFO)
3636 			*uinfo = dce->dce_uinfo;
3637 
3638 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3639 
3640 		/* Allow ire_metrics to decrease the path MTU from above */
3641 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3642 			uinfo->iulp_mtu = pmtu;
3643 
3644 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3645 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3646 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3647 	}
3648 
3649 	if (ill != NULL)
3650 		ill_refrele(ill);
3651 
3652 	return (error);
3653 
3654 bad_addr:
3655 	if (ire != NULL)
3656 		ire_refrele(ire);
3657 
3658 	if (ill != NULL)
3659 		ill_refrele(ill);
3660 
3661 	/*
3662 	 * Make sure we don't leave an unreachable ixa_nce in place
3663 	 * since ip_select_route is used when we unplumb i.e., remove
3664 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3665 	 */
3666 	nce = ixa->ixa_nce;
3667 	if (nce != NULL && nce->nce_is_condemned) {
3668 		nce_refrele(nce);
3669 		ixa->ixa_nce = NULL;
3670 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3671 	}
3672 
3673 	return (error);
3674 }
3675 
3676 
3677 /*
3678  * Get the base MTU for the case when path MTU discovery is not used.
3679  * Takes the MTU of the IRE into account.
3680  */
3681 uint_t
3682 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3683 {
3684 	uint_t mtu = ill->ill_mtu;
3685 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3686 
3687 	if (iremtu != 0 && iremtu < mtu)
3688 		mtu = iremtu;
3689 
3690 	return (mtu);
3691 }
3692 
3693 /*
3694  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3695  * Assumes that ixa_ire, dce, and nce have already been set up.
3696  *
3697  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3698  * We avoid path MTU discovery if it is disabled with ndd.
3699  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3700  *
3701  * NOTE: We also used to turn it off for source routed packets. That
3702  * is no longer required since the dce is per final destination.
3703  */
3704 uint_t
3705 ip_get_pmtu(ip_xmit_attr_t *ixa)
3706 {
3707 	ip_stack_t	*ipst = ixa->ixa_ipst;
3708 	dce_t		*dce;
3709 	nce_t		*nce;
3710 	ire_t		*ire;
3711 	uint_t		pmtu;
3712 
3713 	ire = ixa->ixa_ire;
3714 	dce = ixa->ixa_dce;
3715 	nce = ixa->ixa_nce;
3716 
3717 	/*
3718 	 * If path MTU discovery has been turned off by ndd, then we ignore
3719 	 * any dce_pmtu and for IPv4 we will not set DF.
3720 	 */
3721 	if (!ipst->ips_ip_path_mtu_discovery)
3722 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3723 
3724 	pmtu = IP_MAXPACKET;
3725 	/*
3726 	 * Decide whether whether IPv4 sets DF
3727 	 * For IPv6 "no DF" means to use the 1280 mtu
3728 	 */
3729 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3730 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3731 	} else {
3732 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3733 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3734 			pmtu = IPV6_MIN_MTU;
3735 	}
3736 
3737 	/* Check if the PMTU is to old before we use it */
3738 	if ((dce->dce_flags & DCEF_PMTU) &&
3739 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3740 	    ipst->ips_ip_pathmtu_interval) {
3741 		/*
3742 		 * Older than 20 minutes. Drop the path MTU information.
3743 		 */
3744 		mutex_enter(&dce->dce_lock);
3745 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3746 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3747 		mutex_exit(&dce->dce_lock);
3748 		dce_increment_generation(dce);
3749 	}
3750 
3751 	/* The metrics on the route can lower the path MTU */
3752 	if (ire->ire_metrics.iulp_mtu != 0 &&
3753 	    ire->ire_metrics.iulp_mtu < pmtu)
3754 		pmtu = ire->ire_metrics.iulp_mtu;
3755 
3756 	/*
3757 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3758 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3759 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3760 	 */
3761 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3762 		if (dce->dce_flags & DCEF_PMTU) {
3763 			if (dce->dce_pmtu < pmtu)
3764 				pmtu = dce->dce_pmtu;
3765 
3766 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3767 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3768 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3769 			} else {
3770 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3771 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3772 			}
3773 		} else {
3774 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3775 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3776 		}
3777 	}
3778 
3779 	/*
3780 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3781 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3782 	 * mtu as IRE_LOOPBACK.
3783 	 */
3784 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3785 		uint_t loopback_mtu;
3786 
3787 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3788 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3789 
3790 		if (loopback_mtu < pmtu)
3791 			pmtu = loopback_mtu;
3792 	} else if (nce != NULL) {
3793 		/*
3794 		 * Make sure we don't exceed the interface MTU.
3795 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3796 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3797 		 * to tell the transport something larger than zero.
3798 		 */
3799 		if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3800 			pmtu = nce->nce_common->ncec_ill->ill_mtu;
3801 		if (nce->nce_common->ncec_ill != nce->nce_ill &&
3802 		    nce->nce_ill->ill_mtu < pmtu) {
3803 			/*
3804 			 * for interfaces in an IPMP group, the mtu of
3805 			 * the nce_ill (under_ill) could be different
3806 			 * from the mtu of the ncec_ill, so we take the
3807 			 * min of the two.
3808 			 */
3809 			pmtu = nce->nce_ill->ill_mtu;
3810 		}
3811 	}
3812 
3813 	/*
3814 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3815 	 * Only applies to IPv6.
3816 	 */
3817 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3818 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3819 			switch (ixa->ixa_use_min_mtu) {
3820 			case IPV6_USE_MIN_MTU_MULTICAST:
3821 				if (ire->ire_type & IRE_MULTICAST)
3822 					pmtu = IPV6_MIN_MTU;
3823 				break;
3824 			case IPV6_USE_MIN_MTU_ALWAYS:
3825 				pmtu = IPV6_MIN_MTU;
3826 				break;
3827 			case IPV6_USE_MIN_MTU_NEVER:
3828 				break;
3829 			}
3830 		} else {
3831 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3832 			if (ire->ire_type & IRE_MULTICAST)
3833 				pmtu = IPV6_MIN_MTU;
3834 		}
3835 	}
3836 
3837 	/*
3838 	 * After receiving an ICMPv6 "packet too big" message with a
3839 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3840 	 * will insert a 8-byte fragment header in every packet. We compensate
3841 	 * for those cases by returning a smaller path MTU to the ULP.
3842 	 *
3843 	 * In the case of CGTP then ip_output will add a fragment header.
3844 	 * Make sure there is room for it by telling a smaller number
3845 	 * to the transport.
3846 	 *
3847 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3848 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3849 	 * which is the size of the packets it can send.
3850 	 */
3851 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3852 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
3853 		    (ire->ire_flags & RTF_MULTIRT) ||
3854 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3855 			pmtu -= sizeof (ip6_frag_t);
3856 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3857 		}
3858 	}
3859 
3860 	return (pmtu);
3861 }
3862 
3863 /*
3864  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3865  * the final piece where we don't.  Return a pointer to the first mblk in the
3866  * result, and update the pointer to the next mblk to chew on.  If anything
3867  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3868  * NULL pointer.
3869  */
3870 mblk_t *
3871 ip_carve_mp(mblk_t **mpp, ssize_t len)
3872 {
3873 	mblk_t	*mp0;
3874 	mblk_t	*mp1;
3875 	mblk_t	*mp2;
3876 
3877 	if (!len || !mpp || !(mp0 = *mpp))
3878 		return (NULL);
3879 	/* If we aren't going to consume the first mblk, we need a dup. */
3880 	if (mp0->b_wptr - mp0->b_rptr > len) {
3881 		mp1 = dupb(mp0);
3882 		if (mp1) {
3883 			/* Partition the data between the two mblks. */
3884 			mp1->b_wptr = mp1->b_rptr + len;
3885 			mp0->b_rptr = mp1->b_wptr;
3886 			/*
3887 			 * after adjustments if mblk not consumed is now
3888 			 * unaligned, try to align it. If this fails free
3889 			 * all messages and let upper layer recover.
3890 			 */
3891 			if (!OK_32PTR(mp0->b_rptr)) {
3892 				if (!pullupmsg(mp0, -1)) {
3893 					freemsg(mp0);
3894 					freemsg(mp1);
3895 					*mpp = NULL;
3896 					return (NULL);
3897 				}
3898 			}
3899 		}
3900 		return (mp1);
3901 	}
3902 	/* Eat through as many mblks as we need to get len bytes. */
3903 	len -= mp0->b_wptr - mp0->b_rptr;
3904 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3905 		if (mp2->b_wptr - mp2->b_rptr > len) {
3906 			/*
3907 			 * We won't consume the entire last mblk.  Like
3908 			 * above, dup and partition it.
3909 			 */
3910 			mp1->b_cont = dupb(mp2);
3911 			mp1 = mp1->b_cont;
3912 			if (!mp1) {
3913 				/*
3914 				 * Trouble.  Rather than go to a lot of
3915 				 * trouble to clean up, we free the messages.
3916 				 * This won't be any worse than losing it on
3917 				 * the wire.
3918 				 */
3919 				freemsg(mp0);
3920 				freemsg(mp2);
3921 				*mpp = NULL;
3922 				return (NULL);
3923 			}
3924 			mp1->b_wptr = mp1->b_rptr + len;
3925 			mp2->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(mp2->b_rptr)) {
3932 				if (!pullupmsg(mp2, -1)) {
3933 					freemsg(mp0);
3934 					freemsg(mp2);
3935 					*mpp = NULL;
3936 					return (NULL);
3937 				}
3938 			}
3939 			*mpp = mp2;
3940 			return (mp0);
3941 		}
3942 		/* Decrement len by the amount we just got. */
3943 		len -= mp2->b_wptr - mp2->b_rptr;
3944 	}
3945 	/*
3946 	 * len should be reduced to zero now.  If not our caller has
3947 	 * screwed up.
3948 	 */
3949 	if (len) {
3950 		/* Shouldn't happen! */
3951 		freemsg(mp0);
3952 		*mpp = NULL;
3953 		return (NULL);
3954 	}
3955 	/*
3956 	 * We consumed up to exactly the end of an mblk.  Detach the part
3957 	 * we are returning from the rest of the chain.
3958 	 */
3959 	mp1->b_cont = NULL;
3960 	*mpp = mp2;
3961 	return (mp0);
3962 }
3963 
3964 /* The ill stream is being unplumbed. Called from ip_close */
3965 int
3966 ip_modclose(ill_t *ill)
3967 {
3968 	boolean_t success;
3969 	ipsq_t	*ipsq;
3970 	ipif_t	*ipif;
3971 	queue_t	*q = ill->ill_rq;
3972 	ip_stack_t	*ipst = ill->ill_ipst;
3973 	int	i;
3974 	arl_ill_common_t *ai = ill->ill_common;
3975 
3976 	/*
3977 	 * The punlink prior to this may have initiated a capability
3978 	 * negotiation. But ipsq_enter will block until that finishes or
3979 	 * times out.
3980 	 */
3981 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
3982 
3983 	/*
3984 	 * Open/close/push/pop is guaranteed to be single threaded
3985 	 * per stream by STREAMS. FS guarantees that all references
3986 	 * from top are gone before close is called. So there can't
3987 	 * be another close thread that has set CONDEMNED on this ill.
3988 	 * and cause ipsq_enter to return failure.
3989 	 */
3990 	ASSERT(success);
3991 	ipsq = ill->ill_phyint->phyint_ipsq;
3992 
3993 	/*
3994 	 * Mark it condemned. No new reference will be made to this ill.
3995 	 * Lookup functions will return an error. Threads that try to
3996 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
3997 	 * that the refcnt will drop down to zero.
3998 	 */
3999 	mutex_enter(&ill->ill_lock);
4000 	ill->ill_state_flags |= ILL_CONDEMNED;
4001 	for (ipif = ill->ill_ipif; ipif != NULL;
4002 	    ipif = ipif->ipif_next) {
4003 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4004 	}
4005 	/*
4006 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4007 	 * returns  error if ILL_CONDEMNED is set
4008 	 */
4009 	cv_broadcast(&ill->ill_cv);
4010 	mutex_exit(&ill->ill_lock);
4011 
4012 	/*
4013 	 * Send all the deferred DLPI messages downstream which came in
4014 	 * during the small window right before ipsq_enter(). We do this
4015 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4016 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4017 	 */
4018 	ill_dlpi_send_deferred(ill);
4019 
4020 	/*
4021 	 * Shut down fragmentation reassembly.
4022 	 * ill_frag_timer won't start a timer again.
4023 	 * Now cancel any existing timer
4024 	 */
4025 	(void) untimeout(ill->ill_frag_timer_id);
4026 	(void) ill_frag_timeout(ill, 0);
4027 
4028 	/*
4029 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4030 	 * this ill. Then wait for the refcnts to drop to zero.
4031 	 * ill_is_freeable checks whether the ill is really quiescent.
4032 	 * Then make sure that threads that are waiting to enter the
4033 	 * ipsq have seen the error returned by ipsq_enter and have
4034 	 * gone away. Then we call ill_delete_tail which does the
4035 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4036 	 */
4037 	ill_delete(ill);
4038 	mutex_enter(&ill->ill_lock);
4039 	while (!ill_is_freeable(ill))
4040 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4041 
4042 	while (ill->ill_waiters)
4043 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4044 
4045 	mutex_exit(&ill->ill_lock);
4046 
4047 	/*
4048 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4049 	 * it held until the end of the function since the cleanup
4050 	 * below needs to be able to use the ip_stack_t.
4051 	 */
4052 	netstack_hold(ipst->ips_netstack);
4053 
4054 	/* qprocsoff is done via ill_delete_tail */
4055 	ill_delete_tail(ill);
4056 	/*
4057 	 * synchronously wait for arp stream to unbind. After this, we
4058 	 * cannot get any data packets up from the driver.
4059 	 */
4060 	arp_unbind_complete(ill);
4061 	ASSERT(ill->ill_ipst == NULL);
4062 
4063 	/*
4064 	 * Walk through all conns and qenable those that have queued data.
4065 	 * Close synchronization needs this to
4066 	 * be done to ensure that all upper layers blocked
4067 	 * due to flow control to the closing device
4068 	 * get unblocked.
4069 	 */
4070 	ip1dbg(("ip_wsrv: walking\n"));
4071 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4072 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4073 	}
4074 
4075 	/*
4076 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4077 	 * stream is being torn down before ARP was plumbed (e.g.,
4078 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4079 	 * an error
4080 	 */
4081 	if (ai != NULL) {
4082 		ASSERT(!ill->ill_isv6);
4083 		mutex_enter(&ai->ai_lock);
4084 		ai->ai_ill = NULL;
4085 		if (ai->ai_arl == NULL) {
4086 			mutex_destroy(&ai->ai_lock);
4087 			kmem_free(ai, sizeof (*ai));
4088 		} else {
4089 			cv_signal(&ai->ai_ill_unplumb_done);
4090 			mutex_exit(&ai->ai_lock);
4091 		}
4092 	}
4093 
4094 	mutex_enter(&ipst->ips_ip_mi_lock);
4095 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4096 	mutex_exit(&ipst->ips_ip_mi_lock);
4097 
4098 	/*
4099 	 * credp could be null if the open didn't succeed and ip_modopen
4100 	 * itself calls ip_close.
4101 	 */
4102 	if (ill->ill_credp != NULL)
4103 		crfree(ill->ill_credp);
4104 
4105 	mutex_destroy(&ill->ill_saved_ire_lock);
4106 	mutex_destroy(&ill->ill_lock);
4107 	rw_destroy(&ill->ill_mcast_lock);
4108 	mutex_destroy(&ill->ill_mcast_serializer);
4109 	list_destroy(&ill->ill_nce);
4110 
4111 	/*
4112 	 * Now we are done with the module close pieces that
4113 	 * need the netstack_t.
4114 	 */
4115 	netstack_rele(ipst->ips_netstack);
4116 
4117 	mi_close_free((IDP)ill);
4118 	q->q_ptr = WR(q)->q_ptr = NULL;
4119 
4120 	ipsq_exit(ipsq);
4121 
4122 	return (0);
4123 }
4124 
4125 /*
4126  * This is called as part of close() for IP, UDP, ICMP, and RTS
4127  * in order to quiesce the conn.
4128  */
4129 void
4130 ip_quiesce_conn(conn_t *connp)
4131 {
4132 	boolean_t	drain_cleanup_reqd = B_FALSE;
4133 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4134 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4135 	ip_stack_t	*ipst;
4136 
4137 	ASSERT(!IPCL_IS_TCP(connp));
4138 	ipst = connp->conn_netstack->netstack_ip;
4139 
4140 	/*
4141 	 * Mark the conn as closing, and this conn must not be
4142 	 * inserted in future into any list. Eg. conn_drain_insert(),
4143 	 * won't insert this conn into the conn_drain_list.
4144 	 *
4145 	 * conn_idl, and conn_ilg cannot get set henceforth.
4146 	 */
4147 	mutex_enter(&connp->conn_lock);
4148 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4149 	connp->conn_state_flags |= CONN_CLOSING;
4150 	if (connp->conn_idl != NULL)
4151 		drain_cleanup_reqd = B_TRUE;
4152 	if (connp->conn_oper_pending_ill != NULL)
4153 		conn_ioctl_cleanup_reqd = B_TRUE;
4154 	if (connp->conn_dhcpinit_ill != NULL) {
4155 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4156 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4157 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4158 		connp->conn_dhcpinit_ill = NULL;
4159 	}
4160 	if (connp->conn_ilg != NULL)
4161 		ilg_cleanup_reqd = B_TRUE;
4162 	mutex_exit(&connp->conn_lock);
4163 
4164 	if (conn_ioctl_cleanup_reqd)
4165 		conn_ioctl_cleanup(connp);
4166 
4167 	if (is_system_labeled() && connp->conn_anon_port) {
4168 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4169 		    connp->conn_mlp_type, connp->conn_proto,
4170 		    ntohs(connp->conn_lport), B_FALSE);
4171 		connp->conn_anon_port = 0;
4172 	}
4173 	connp->conn_mlp_type = mlptSingle;
4174 
4175 	/*
4176 	 * Remove this conn from any fanout list it is on.
4177 	 * and then wait for any threads currently operating
4178 	 * on this endpoint to finish
4179 	 */
4180 	ipcl_hash_remove(connp);
4181 
4182 	/*
4183 	 * Remove this conn from the drain list, and do any other cleanup that
4184 	 * may be required.  (TCP conns are never flow controlled, and
4185 	 * conn_idl will be NULL.)
4186 	 */
4187 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4188 		idl_t *idl = connp->conn_idl;
4189 
4190 		mutex_enter(&idl->idl_lock);
4191 		conn_drain(connp, B_TRUE);
4192 		mutex_exit(&idl->idl_lock);
4193 	}
4194 
4195 	if (connp == ipst->ips_ip_g_mrouter)
4196 		(void) ip_mrouter_done(ipst);
4197 
4198 	if (ilg_cleanup_reqd)
4199 		ilg_delete_all(connp);
4200 
4201 	/*
4202 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4203 	 * callers from write side can't be there now because close
4204 	 * is in progress. The only other caller is ipcl_walk
4205 	 * which checks for the condemned flag.
4206 	 */
4207 	mutex_enter(&connp->conn_lock);
4208 	connp->conn_state_flags |= CONN_CONDEMNED;
4209 	while (connp->conn_ref != 1)
4210 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4211 	connp->conn_state_flags |= CONN_QUIESCED;
4212 	mutex_exit(&connp->conn_lock);
4213 }
4214 
4215 /* ARGSUSED */
4216 int
4217 ip_close(queue_t *q, int flags)
4218 {
4219 	conn_t		*connp;
4220 
4221 	/*
4222 	 * Call the appropriate delete routine depending on whether this is
4223 	 * a module or device.
4224 	 */
4225 	if (WR(q)->q_next != NULL) {
4226 		/* This is a module close */
4227 		return (ip_modclose((ill_t *)q->q_ptr));
4228 	}
4229 
4230 	connp = q->q_ptr;
4231 	ip_quiesce_conn(connp);
4232 
4233 	qprocsoff(q);
4234 
4235 	/*
4236 	 * Now we are truly single threaded on this stream, and can
4237 	 * delete the things hanging off the connp, and finally the connp.
4238 	 * We removed this connp from the fanout list, it cannot be
4239 	 * accessed thru the fanouts, and we already waited for the
4240 	 * conn_ref to drop to 0. We are already in close, so
4241 	 * there cannot be any other thread from the top. qprocsoff
4242 	 * has completed, and service has completed or won't run in
4243 	 * future.
4244 	 */
4245 	ASSERT(connp->conn_ref == 1);
4246 
4247 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4248 
4249 	connp->conn_ref--;
4250 	ipcl_conn_destroy(connp);
4251 
4252 	q->q_ptr = WR(q)->q_ptr = NULL;
4253 	return (0);
4254 }
4255 
4256 /*
4257  * Wapper around putnext() so that ip_rts_request can merely use
4258  * conn_recv.
4259  */
4260 /*ARGSUSED2*/
4261 static void
4262 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4263 {
4264 	conn_t *connp = (conn_t *)arg1;
4265 
4266 	putnext(connp->conn_rq, mp);
4267 }
4268 
4269 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4270 /* ARGSUSED */
4271 static void
4272 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4273 {
4274 	freemsg(mp);
4275 }
4276 
4277 /*
4278  * Called when the module is about to be unloaded
4279  */
4280 void
4281 ip_ddi_destroy(void)
4282 {
4283 	/* This needs to be called before destroying any transports. */
4284 	mutex_enter(&cpu_lock);
4285 	unregister_cpu_setup_func(ip_tp_cpu_update, NULL);
4286 	mutex_exit(&cpu_lock);
4287 
4288 	tnet_fini();
4289 
4290 	icmp_ddi_g_destroy();
4291 	rts_ddi_g_destroy();
4292 	udp_ddi_g_destroy();
4293 	sctp_ddi_g_destroy();
4294 	tcp_ddi_g_destroy();
4295 	ilb_ddi_g_destroy();
4296 	dce_g_destroy();
4297 	ipsec_policy_g_destroy();
4298 	ipcl_g_destroy();
4299 	ip_net_g_destroy();
4300 	ip_ire_g_fini();
4301 	inet_minor_destroy(ip_minor_arena_sa);
4302 #if defined(_LP64)
4303 	inet_minor_destroy(ip_minor_arena_la);
4304 #endif
4305 
4306 #ifdef DEBUG
4307 	list_destroy(&ip_thread_list);
4308 	rw_destroy(&ip_thread_rwlock);
4309 	tsd_destroy(&ip_thread_data);
4310 #endif
4311 
4312 	netstack_unregister(NS_IP);
4313 }
4314 
4315 /*
4316  * First step in cleanup.
4317  */
4318 /* ARGSUSED */
4319 static void
4320 ip_stack_shutdown(netstackid_t stackid, void *arg)
4321 {
4322 	ip_stack_t *ipst = (ip_stack_t *)arg;
4323 
4324 #ifdef NS_DEBUG
4325 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4326 #endif
4327 
4328 	/*
4329 	 * Perform cleanup for special interfaces (loopback and IPMP).
4330 	 */
4331 	ip_interface_cleanup(ipst);
4332 
4333 	/*
4334 	 * The *_hook_shutdown()s start the process of notifying any
4335 	 * consumers that things are going away.... nothing is destroyed.
4336 	 */
4337 	ipv4_hook_shutdown(ipst);
4338 	ipv6_hook_shutdown(ipst);
4339 	arp_hook_shutdown(ipst);
4340 
4341 	mutex_enter(&ipst->ips_capab_taskq_lock);
4342 	ipst->ips_capab_taskq_quit = B_TRUE;
4343 	cv_signal(&ipst->ips_capab_taskq_cv);
4344 	mutex_exit(&ipst->ips_capab_taskq_lock);
4345 }
4346 
4347 /*
4348  * Free the IP stack instance.
4349  */
4350 static void
4351 ip_stack_fini(netstackid_t stackid, void *arg)
4352 {
4353 	ip_stack_t *ipst = (ip_stack_t *)arg;
4354 	int ret;
4355 
4356 #ifdef NS_DEBUG
4357 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4358 #endif
4359 	/*
4360 	 * At this point, all of the notifications that the events and
4361 	 * protocols are going away have been run, meaning that we can
4362 	 * now set about starting to clean things up.
4363 	 */
4364 	ipobs_fini(ipst);
4365 	ipv4_hook_destroy(ipst);
4366 	ipv6_hook_destroy(ipst);
4367 	arp_hook_destroy(ipst);
4368 	ip_net_destroy(ipst);
4369 
4370 	ipmp_destroy(ipst);
4371 
4372 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4373 	ipst->ips_ip_mibkp = NULL;
4374 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4375 	ipst->ips_icmp_mibkp = NULL;
4376 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4377 	ipst->ips_ip_kstat = NULL;
4378 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4379 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4380 	ipst->ips_ip6_kstat = NULL;
4381 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4382 
4383 	kmem_free(ipst->ips_propinfo_tbl,
4384 	    ip_propinfo_count * sizeof (mod_prop_info_t));
4385 	ipst->ips_propinfo_tbl = NULL;
4386 
4387 	dce_stack_destroy(ipst);
4388 	ip_mrouter_stack_destroy(ipst);
4389 
4390 	ret = untimeout(ipst->ips_igmp_timeout_id);
4391 	if (ret == -1) {
4392 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4393 	} else {
4394 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4395 		ipst->ips_igmp_timeout_id = 0;
4396 	}
4397 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4398 	if (ret == -1) {
4399 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4400 	} else {
4401 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4402 		ipst->ips_igmp_slowtimeout_id = 0;
4403 	}
4404 	ret = untimeout(ipst->ips_mld_timeout_id);
4405 	if (ret == -1) {
4406 		ASSERT(ipst->ips_mld_timeout_id == 0);
4407 	} else {
4408 		ASSERT(ipst->ips_mld_timeout_id != 0);
4409 		ipst->ips_mld_timeout_id = 0;
4410 	}
4411 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4412 	if (ret == -1) {
4413 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4414 	} else {
4415 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4416 		ipst->ips_mld_slowtimeout_id = 0;
4417 	}
4418 
4419 	ip_ire_fini(ipst);
4420 	ip6_asp_free(ipst);
4421 	conn_drain_fini(ipst);
4422 	ipcl_destroy(ipst);
4423 
4424 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4425 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4426 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4427 	ipst->ips_ndp4 = NULL;
4428 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4429 	ipst->ips_ndp6 = NULL;
4430 
4431 	if (ipst->ips_loopback_ksp != NULL) {
4432 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4433 		ipst->ips_loopback_ksp = NULL;
4434 	}
4435 
4436 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4437 	cv_destroy(&ipst->ips_capab_taskq_cv);
4438 
4439 	rw_destroy(&ipst->ips_srcid_lock);
4440 
4441 	mutex_destroy(&ipst->ips_ip_mi_lock);
4442 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4443 
4444 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4445 	mutex_destroy(&ipst->ips_mld_timer_lock);
4446 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4447 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4448 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4449 	rw_destroy(&ipst->ips_ill_g_lock);
4450 
4451 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4452 	ipst->ips_phyint_g_list = NULL;
4453 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4454 	ipst->ips_ill_g_heads = NULL;
4455 
4456 	ldi_ident_release(ipst->ips_ldi_ident);
4457 	kmem_free(ipst, sizeof (*ipst));
4458 }
4459 
4460 /*
4461  * This function is called from the TSD destructor, and is used to debug
4462  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4463  * details.
4464  */
4465 static void
4466 ip_thread_exit(void *phash)
4467 {
4468 	th_hash_t *thh = phash;
4469 
4470 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4471 	list_remove(&ip_thread_list, thh);
4472 	rw_exit(&ip_thread_rwlock);
4473 	mod_hash_destroy_hash(thh->thh_hash);
4474 	kmem_free(thh, sizeof (*thh));
4475 }
4476 
4477 /*
4478  * Called when the IP kernel module is loaded into the kernel
4479  */
4480 void
4481 ip_ddi_init(void)
4482 {
4483 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4484 
4485 	/*
4486 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4487 	 * initial devices: ip, ip6, tcp, tcp6.
4488 	 */
4489 	/*
4490 	 * If this is a 64-bit kernel, then create two separate arenas -
4491 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4492 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4493 	 */
4494 	ip_minor_arena_la = NULL;
4495 	ip_minor_arena_sa = NULL;
4496 #if defined(_LP64)
4497 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4498 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4499 		cmn_err(CE_PANIC,
4500 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4501 	}
4502 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4503 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4504 		cmn_err(CE_PANIC,
4505 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4506 	}
4507 #else
4508 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4509 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4510 		cmn_err(CE_PANIC,
4511 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4512 	}
4513 #endif
4514 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4515 
4516 	ipcl_g_init();
4517 	ip_ire_g_init();
4518 	ip_net_g_init();
4519 
4520 #ifdef DEBUG
4521 	tsd_create(&ip_thread_data, ip_thread_exit);
4522 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4523 	list_create(&ip_thread_list, sizeof (th_hash_t),
4524 	    offsetof(th_hash_t, thh_link));
4525 #endif
4526 	ipsec_policy_g_init();
4527 	tcp_ddi_g_init();
4528 	sctp_ddi_g_init();
4529 	dce_g_init();
4530 
4531 	/*
4532 	 * We want to be informed each time a stack is created or
4533 	 * destroyed in the kernel, so we can maintain the
4534 	 * set of udp_stack_t's.
4535 	 */
4536 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4537 	    ip_stack_fini);
4538 
4539 	tnet_init();
4540 
4541 	udp_ddi_g_init();
4542 	rts_ddi_g_init();
4543 	icmp_ddi_g_init();
4544 	ilb_ddi_g_init();
4545 
4546 	/* This needs to be called after all transports are initialized. */
4547 	mutex_enter(&cpu_lock);
4548 	register_cpu_setup_func(ip_tp_cpu_update, NULL);
4549 	mutex_exit(&cpu_lock);
4550 }
4551 
4552 /*
4553  * Initialize the IP stack instance.
4554  */
4555 static void *
4556 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4557 {
4558 	ip_stack_t	*ipst;
4559 	size_t		arrsz;
4560 	major_t		major;
4561 
4562 #ifdef NS_DEBUG
4563 	printf("ip_stack_init(stack %d)\n", stackid);
4564 #endif
4565 
4566 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4567 	ipst->ips_netstack = ns;
4568 
4569 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4570 	    KM_SLEEP);
4571 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4572 	    KM_SLEEP);
4573 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4574 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4575 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4576 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4577 
4578 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4579 	ipst->ips_igmp_deferred_next = INFINITY;
4580 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4581 	ipst->ips_mld_deferred_next = INFINITY;
4582 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4583 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4584 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4585 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4586 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4587 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4588 
4589 	ipcl_init(ipst);
4590 	ip_ire_init(ipst);
4591 	ip6_asp_init(ipst);
4592 	ipif_init(ipst);
4593 	conn_drain_init(ipst);
4594 	ip_mrouter_stack_init(ipst);
4595 	dce_stack_init(ipst);
4596 
4597 	ipst->ips_ip_multirt_log_interval = 1000;
4598 
4599 	ipst->ips_ill_index = 1;
4600 
4601 	ipst->ips_saved_ip_forwarding = -1;
4602 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4603 
4604 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4605 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4606 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4607 
4608 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4609 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4610 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4611 	ipst->ips_ip6_kstat =
4612 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4613 
4614 	ipst->ips_ip_src_id = 1;
4615 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4616 
4617 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4618 
4619 	ip_net_init(ipst, ns);
4620 	ipv4_hook_init(ipst);
4621 	ipv6_hook_init(ipst);
4622 	arp_hook_init(ipst);
4623 	ipmp_init(ipst);
4624 	ipobs_init(ipst);
4625 
4626 	/*
4627 	 * Create the taskq dispatcher thread and initialize related stuff.
4628 	 */
4629 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4630 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4631 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4632 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4633 
4634 	major = mod_name_to_major(INET_NAME);
4635 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4636 	return (ipst);
4637 }
4638 
4639 /*
4640  * Allocate and initialize a DLPI template of the specified length.  (May be
4641  * called as writer.)
4642  */
4643 mblk_t *
4644 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4645 {
4646 	mblk_t	*mp;
4647 
4648 	mp = allocb(len, BPRI_MED);
4649 	if (!mp)
4650 		return (NULL);
4651 
4652 	/*
4653 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4654 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4655 	 * that other DLPI are M_PROTO.
4656 	 */
4657 	if (prim == DL_INFO_REQ) {
4658 		mp->b_datap->db_type = M_PCPROTO;
4659 	} else {
4660 		mp->b_datap->db_type = M_PROTO;
4661 	}
4662 
4663 	mp->b_wptr = mp->b_rptr + len;
4664 	bzero(mp->b_rptr, len);
4665 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4666 	return (mp);
4667 }
4668 
4669 /*
4670  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4671  */
4672 mblk_t *
4673 ip_dlnotify_alloc(uint_t notification, uint_t data)
4674 {
4675 	dl_notify_ind_t	*notifyp;
4676 	mblk_t		*mp;
4677 
4678 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4679 		return (NULL);
4680 
4681 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4682 	notifyp->dl_notification = notification;
4683 	notifyp->dl_data = data;
4684 	return (mp);
4685 }
4686 
4687 /*
4688  * Debug formatting routine.  Returns a character string representation of the
4689  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4690  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4691  *
4692  * Once the ndd table-printing interfaces are removed, this can be changed to
4693  * standard dotted-decimal form.
4694  */
4695 char *
4696 ip_dot_addr(ipaddr_t addr, char *buf)
4697 {
4698 	uint8_t *ap = (uint8_t *)&addr;
4699 
4700 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4701 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4702 	return (buf);
4703 }
4704 
4705 /*
4706  * Write the given MAC address as a printable string in the usual colon-
4707  * separated format.
4708  */
4709 const char *
4710 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4711 {
4712 	char *bp;
4713 
4714 	if (alen == 0 || buflen < 4)
4715 		return ("?");
4716 	bp = buf;
4717 	for (;;) {
4718 		/*
4719 		 * If there are more MAC address bytes available, but we won't
4720 		 * have any room to print them, then add "..." to the string
4721 		 * instead.  See below for the 'magic number' explanation.
4722 		 */
4723 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4724 			(void) strcpy(bp, "...");
4725 			break;
4726 		}
4727 		(void) sprintf(bp, "%02x", *addr++);
4728 		bp += 2;
4729 		if (--alen == 0)
4730 			break;
4731 		*bp++ = ':';
4732 		buflen -= 3;
4733 		/*
4734 		 * At this point, based on the first 'if' statement above,
4735 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4736 		 * buflen >= 4.  The first case leaves room for the final "xx"
4737 		 * number and trailing NUL byte.  The second leaves room for at
4738 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4739 		 * that statement.
4740 		 */
4741 	}
4742 	return (buf);
4743 }
4744 
4745 /*
4746  * Called when it is conceptually a ULP that would sent the packet
4747  * e.g., port unreachable and protocol unreachable. Check that the packet
4748  * would have passed the IPsec global policy before sending the error.
4749  *
4750  * Send an ICMP error after patching up the packet appropriately.
4751  * Uses ip_drop_input and bumps the appropriate MIB.
4752  */
4753 void
4754 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4755     ip_recv_attr_t *ira)
4756 {
4757 	ipha_t		*ipha;
4758 	boolean_t	secure;
4759 	ill_t		*ill = ira->ira_ill;
4760 	ip_stack_t	*ipst = ill->ill_ipst;
4761 	netstack_t	*ns = ipst->ips_netstack;
4762 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4763 
4764 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4765 
4766 	/*
4767 	 * We are generating an icmp error for some inbound packet.
4768 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4769 	 * Before we generate an error, check with global policy
4770 	 * to see whether this is allowed to enter the system. As
4771 	 * there is no "conn", we are checking with global policy.
4772 	 */
4773 	ipha = (ipha_t *)mp->b_rptr;
4774 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4775 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4776 		if (mp == NULL)
4777 			return;
4778 	}
4779 
4780 	/* We never send errors for protocols that we do implement */
4781 	if (ira->ira_protocol == IPPROTO_ICMP ||
4782 	    ira->ira_protocol == IPPROTO_IGMP) {
4783 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4784 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4785 		freemsg(mp);
4786 		return;
4787 	}
4788 	/*
4789 	 * Have to correct checksum since
4790 	 * the packet might have been
4791 	 * fragmented and the reassembly code in ip_rput
4792 	 * does not restore the IP checksum.
4793 	 */
4794 	ipha->ipha_hdr_checksum = 0;
4795 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4796 
4797 	switch (icmp_type) {
4798 	case ICMP_DEST_UNREACHABLE:
4799 		switch (icmp_code) {
4800 		case ICMP_PROTOCOL_UNREACHABLE:
4801 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4802 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4803 			break;
4804 		case ICMP_PORT_UNREACHABLE:
4805 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4806 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4807 			break;
4808 		}
4809 
4810 		icmp_unreachable(mp, icmp_code, ira);
4811 		break;
4812 	default:
4813 #ifdef DEBUG
4814 		panic("ip_fanout_send_icmp_v4: wrong type");
4815 		/*NOTREACHED*/
4816 #else
4817 		freemsg(mp);
4818 		break;
4819 #endif
4820 	}
4821 }
4822 
4823 /*
4824  * Used to send an ICMP error message when a packet is received for
4825  * a protocol that is not supported. The mblk passed as argument
4826  * is consumed by this function.
4827  */
4828 void
4829 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4830 {
4831 	ipha_t		*ipha;
4832 
4833 	ipha = (ipha_t *)mp->b_rptr;
4834 	if (ira->ira_flags & IRAF_IS_IPV4) {
4835 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4836 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4837 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4838 	} else {
4839 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4840 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4841 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4842 	}
4843 }
4844 
4845 /*
4846  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4847  * Handles IPv4 and IPv6.
4848  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4849  * Caller is responsible for dropping references to the conn.
4850  */
4851 void
4852 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4853     ip_recv_attr_t *ira)
4854 {
4855 	ill_t		*ill = ira->ira_ill;
4856 	ip_stack_t	*ipst = ill->ill_ipst;
4857 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4858 	boolean_t	secure;
4859 	uint_t		protocol = ira->ira_protocol;
4860 	iaflags_t	iraflags = ira->ira_flags;
4861 	queue_t		*rq;
4862 
4863 	secure = iraflags & IRAF_IPSEC_SECURE;
4864 
4865 	rq = connp->conn_rq;
4866 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4867 		switch (protocol) {
4868 		case IPPROTO_ICMPV6:
4869 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4870 			break;
4871 		case IPPROTO_ICMP:
4872 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4873 			break;
4874 		default:
4875 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4876 			break;
4877 		}
4878 		freemsg(mp);
4879 		return;
4880 	}
4881 
4882 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4883 
4884 	if (((iraflags & IRAF_IS_IPV4) ?
4885 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4886 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4887 	    secure) {
4888 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4889 		    ip6h, ira);
4890 		if (mp == NULL) {
4891 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4892 			/* Note that mp is NULL */
4893 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4894 			return;
4895 		}
4896 	}
4897 
4898 	if (iraflags & IRAF_ICMP_ERROR) {
4899 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4900 	} else {
4901 		ill_t *rill = ira->ira_rill;
4902 
4903 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4904 		ira->ira_ill = ira->ira_rill = NULL;
4905 		/* Send it upstream */
4906 		(connp->conn_recv)(connp, mp, NULL, ira);
4907 		ira->ira_ill = ill;
4908 		ira->ira_rill = rill;
4909 	}
4910 }
4911 
4912 /*
4913  * Handle protocols with which IP is less intimate.  There
4914  * can be more than one stream bound to a particular
4915  * protocol.  When this is the case, normally each one gets a copy
4916  * of any incoming packets.
4917  *
4918  * IPsec NOTE :
4919  *
4920  * Don't allow a secure packet going up a non-secure connection.
4921  * We don't allow this because
4922  *
4923  * 1) Reply might go out in clear which will be dropped at
4924  *    the sending side.
4925  * 2) If the reply goes out in clear it will give the
4926  *    adversary enough information for getting the key in
4927  *    most of the cases.
4928  *
4929  * Moreover getting a secure packet when we expect clear
4930  * implies that SA's were added without checking for
4931  * policy on both ends. This should not happen once ISAKMP
4932  * is used to negotiate SAs as SAs will be added only after
4933  * verifying the policy.
4934  *
4935  * Zones notes:
4936  * Earlier in ip_input on a system with multiple shared-IP zones we
4937  * duplicate the multicast and broadcast packets and send them up
4938  * with each explicit zoneid that exists on that ill.
4939  * This means that here we can match the zoneid with SO_ALLZONES being special.
4940  */
4941 void
4942 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
4943 {
4944 	mblk_t		*mp1;
4945 	ipaddr_t	laddr;
4946 	conn_t		*connp, *first_connp, *next_connp;
4947 	connf_t		*connfp;
4948 	ill_t		*ill = ira->ira_ill;
4949 	ip_stack_t	*ipst = ill->ill_ipst;
4950 
4951 	laddr = ipha->ipha_dst;
4952 
4953 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
4954 	mutex_enter(&connfp->connf_lock);
4955 	connp = connfp->connf_head;
4956 	for (connp = connfp->connf_head; connp != NULL;
4957 	    connp = connp->conn_next) {
4958 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4959 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4960 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4961 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
4962 			break;
4963 		}
4964 	}
4965 
4966 	if (connp == NULL) {
4967 		/*
4968 		 * No one bound to these addresses.  Is
4969 		 * there a client that wants all
4970 		 * unclaimed datagrams?
4971 		 */
4972 		mutex_exit(&connfp->connf_lock);
4973 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4974 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4975 		return;
4976 	}
4977 
4978 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
4979 
4980 	CONN_INC_REF(connp);
4981 	first_connp = connp;
4982 	connp = connp->conn_next;
4983 
4984 	for (;;) {
4985 		while (connp != NULL) {
4986 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
4987 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
4988 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
4989 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
4990 			    ira, connp)))
4991 				break;
4992 			connp = connp->conn_next;
4993 		}
4994 
4995 		if (connp == NULL) {
4996 			/* No more interested clients */
4997 			connp = first_connp;
4998 			break;
4999 		}
5000 		if (((mp1 = dupmsg(mp)) == NULL) &&
5001 		    ((mp1 = copymsg(mp)) == NULL)) {
5002 			/* Memory allocation failed */
5003 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5004 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5005 			connp = first_connp;
5006 			break;
5007 		}
5008 
5009 		CONN_INC_REF(connp);
5010 		mutex_exit(&connfp->connf_lock);
5011 
5012 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5013 		    ira);
5014 
5015 		mutex_enter(&connfp->connf_lock);
5016 		/* Follow the next pointer before releasing the conn. */
5017 		next_connp = connp->conn_next;
5018 		CONN_DEC_REF(connp);
5019 		connp = next_connp;
5020 	}
5021 
5022 	/* Last one.  Send it upstream. */
5023 	mutex_exit(&connfp->connf_lock);
5024 
5025 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5026 
5027 	CONN_DEC_REF(connp);
5028 }
5029 
5030 /*
5031  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5032  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5033  * is not consumed.
5034  *
5035  * One of three things can happen, all of which affect the passed-in mblk:
5036  *
5037  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5038  *
5039  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5040  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5041  *
5042  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5043  */
5044 mblk_t *
5045 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5046 {
5047 	int shift, plen, iph_len;
5048 	ipha_t *ipha;
5049 	udpha_t *udpha;
5050 	uint32_t *spi;
5051 	uint32_t esp_ports;
5052 	uint8_t *orptr;
5053 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5054 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5055 
5056 	ipha = (ipha_t *)mp->b_rptr;
5057 	iph_len = ira->ira_ip_hdr_length;
5058 	plen = ira->ira_pktlen;
5059 
5060 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5061 		/*
5062 		 * Most likely a keepalive for the benefit of an intervening
5063 		 * NAT.  These aren't for us, per se, so drop it.
5064 		 *
5065 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5066 		 * byte packets (keepalives are 1-byte), but we'll drop them
5067 		 * also.
5068 		 */
5069 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5070 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5071 		return (NULL);
5072 	}
5073 
5074 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5075 		/* might as well pull it all up - it might be ESP. */
5076 		if (!pullupmsg(mp, -1)) {
5077 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5078 			    DROPPER(ipss, ipds_esp_nomem),
5079 			    &ipss->ipsec_dropper);
5080 			return (NULL);
5081 		}
5082 
5083 		ipha = (ipha_t *)mp->b_rptr;
5084 	}
5085 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5086 	if (*spi == 0) {
5087 		/* UDP packet - remove 0-spi. */
5088 		shift = sizeof (uint32_t);
5089 	} else {
5090 		/* ESP-in-UDP packet - reduce to ESP. */
5091 		ipha->ipha_protocol = IPPROTO_ESP;
5092 		shift = sizeof (udpha_t);
5093 	}
5094 
5095 	/* Fix IP header */
5096 	ira->ira_pktlen = (plen - shift);
5097 	ipha->ipha_length = htons(ira->ira_pktlen);
5098 	ipha->ipha_hdr_checksum = 0;
5099 
5100 	orptr = mp->b_rptr;
5101 	mp->b_rptr += shift;
5102 
5103 	udpha = (udpha_t *)(orptr + iph_len);
5104 	if (*spi == 0) {
5105 		ASSERT((uint8_t *)ipha == orptr);
5106 		udpha->uha_length = htons(plen - shift - iph_len);
5107 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5108 		esp_ports = 0;
5109 	} else {
5110 		esp_ports = *((uint32_t *)udpha);
5111 		ASSERT(esp_ports != 0);
5112 	}
5113 	ovbcopy(orptr, orptr + shift, iph_len);
5114 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5115 		ipha = (ipha_t *)(orptr + shift);
5116 
5117 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5118 		ira->ira_esp_udp_ports = esp_ports;
5119 		ip_fanout_v4(mp, ipha, ira);
5120 		return (NULL);
5121 	}
5122 	return (mp);
5123 }
5124 
5125 /*
5126  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5127  * Handles IPv4 and IPv6.
5128  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5129  * Caller is responsible for dropping references to the conn.
5130  */
5131 void
5132 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5133     ip_recv_attr_t *ira)
5134 {
5135 	ill_t		*ill = ira->ira_ill;
5136 	ip_stack_t	*ipst = ill->ill_ipst;
5137 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5138 	boolean_t	secure;
5139 	iaflags_t	iraflags = ira->ira_flags;
5140 
5141 	secure = iraflags & IRAF_IPSEC_SECURE;
5142 
5143 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5144 	    !canputnext(connp->conn_rq)) {
5145 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5146 		freemsg(mp);
5147 		return;
5148 	}
5149 
5150 	if (((iraflags & IRAF_IS_IPV4) ?
5151 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5152 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5153 	    secure) {
5154 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5155 		    ip6h, ira);
5156 		if (mp == NULL) {
5157 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5158 			/* Note that mp is NULL */
5159 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5160 			return;
5161 		}
5162 	}
5163 
5164 	/*
5165 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5166 	 * check. Only ip_fanout_v4 has that check.
5167 	 */
5168 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5169 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5170 	} else {
5171 		ill_t *rill = ira->ira_rill;
5172 
5173 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5174 		ira->ira_ill = ira->ira_rill = NULL;
5175 		/* Send it upstream */
5176 		(connp->conn_recv)(connp, mp, NULL, ira);
5177 		ira->ira_ill = ill;
5178 		ira->ira_rill = rill;
5179 	}
5180 }
5181 
5182 /*
5183  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5184  * (Unicast fanout is handled in ip_input_v4.)
5185  *
5186  * If SO_REUSEADDR is set all multicast and broadcast packets
5187  * will be delivered to all conns bound to the same port.
5188  *
5189  * If there is at least one matching AF_INET receiver, then we will
5190  * ignore any AF_INET6 receivers.
5191  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5192  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5193  * packets.
5194  *
5195  * Zones notes:
5196  * Earlier in ip_input on a system with multiple shared-IP zones we
5197  * duplicate the multicast and broadcast packets and send them up
5198  * with each explicit zoneid that exists on that ill.
5199  * This means that here we can match the zoneid with SO_ALLZONES being special.
5200  */
5201 void
5202 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5203     ip_recv_attr_t *ira)
5204 {
5205 	ipaddr_t	laddr;
5206 	in6_addr_t	v6faddr;
5207 	conn_t		*connp;
5208 	connf_t		*connfp;
5209 	ipaddr_t	faddr;
5210 	ill_t		*ill = ira->ira_ill;
5211 	ip_stack_t	*ipst = ill->ill_ipst;
5212 
5213 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5214 
5215 	laddr = ipha->ipha_dst;
5216 	faddr = ipha->ipha_src;
5217 
5218 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5219 	mutex_enter(&connfp->connf_lock);
5220 	connp = connfp->connf_head;
5221 
5222 	/*
5223 	 * If SO_REUSEADDR has been set on the first we send the
5224 	 * packet to all clients that have joined the group and
5225 	 * match the port.
5226 	 */
5227 	while (connp != NULL) {
5228 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5229 		    conn_wantpacket(connp, ira, ipha) &&
5230 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5231 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5232 			break;
5233 		connp = connp->conn_next;
5234 	}
5235 
5236 	if (connp == NULL)
5237 		goto notfound;
5238 
5239 	CONN_INC_REF(connp);
5240 
5241 	if (connp->conn_reuseaddr) {
5242 		conn_t		*first_connp = connp;
5243 		conn_t		*next_connp;
5244 		mblk_t		*mp1;
5245 
5246 		connp = connp->conn_next;
5247 		for (;;) {
5248 			while (connp != NULL) {
5249 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5250 				    fport, faddr) &&
5251 				    conn_wantpacket(connp, ira, ipha) &&
5252 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5253 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5254 				    ira, connp)))
5255 					break;
5256 				connp = connp->conn_next;
5257 			}
5258 			if (connp == NULL) {
5259 				/* No more interested clients */
5260 				connp = first_connp;
5261 				break;
5262 			}
5263 			if (((mp1 = dupmsg(mp)) == NULL) &&
5264 			    ((mp1 = copymsg(mp)) == NULL)) {
5265 				/* Memory allocation failed */
5266 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5267 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5268 				connp = first_connp;
5269 				break;
5270 			}
5271 			CONN_INC_REF(connp);
5272 			mutex_exit(&connfp->connf_lock);
5273 
5274 			IP_STAT(ipst, ip_udp_fanmb);
5275 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5276 			    NULL, ira);
5277 			mutex_enter(&connfp->connf_lock);
5278 			/* Follow the next pointer before releasing the conn */
5279 			next_connp = connp->conn_next;
5280 			CONN_DEC_REF(connp);
5281 			connp = next_connp;
5282 		}
5283 	}
5284 
5285 	/* Last one.  Send it upstream. */
5286 	mutex_exit(&connfp->connf_lock);
5287 	IP_STAT(ipst, ip_udp_fanmb);
5288 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5289 	CONN_DEC_REF(connp);
5290 	return;
5291 
5292 notfound:
5293 	mutex_exit(&connfp->connf_lock);
5294 	/*
5295 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5296 	 * have already been matched above, since they live in the IPv4
5297 	 * fanout tables. This implies we only need to
5298 	 * check for IPv6 in6addr_any endpoints here.
5299 	 * Thus we compare using ipv6_all_zeros instead of the destination
5300 	 * address, except for the multicast group membership lookup which
5301 	 * uses the IPv4 destination.
5302 	 */
5303 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5304 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5305 	mutex_enter(&connfp->connf_lock);
5306 	connp = connfp->connf_head;
5307 	/*
5308 	 * IPv4 multicast packet being delivered to an AF_INET6
5309 	 * in6addr_any endpoint.
5310 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5311 	 * and not conn_wantpacket_v6() since any multicast membership is
5312 	 * for an IPv4-mapped multicast address.
5313 	 */
5314 	while (connp != NULL) {
5315 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5316 		    fport, v6faddr) &&
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 		/*
5326 		 * No one bound to this port.  Is
5327 		 * there a client that wants all
5328 		 * unclaimed datagrams?
5329 		 */
5330 		mutex_exit(&connfp->connf_lock);
5331 
5332 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5333 		    NULL) {
5334 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5335 			ip_fanout_proto_v4(mp, ipha, ira);
5336 		} else {
5337 			/*
5338 			 * We used to attempt to send an icmp error here, but
5339 			 * since this is known to be a multicast packet
5340 			 * and we don't send icmp errors in response to
5341 			 * multicast, just drop the packet and give up sooner.
5342 			 */
5343 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5344 			freemsg(mp);
5345 		}
5346 		return;
5347 	}
5348 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5349 
5350 	/*
5351 	 * If SO_REUSEADDR has been set on the first we send the
5352 	 * packet to all clients that have joined the group and
5353 	 * match the port.
5354 	 */
5355 	if (connp->conn_reuseaddr) {
5356 		conn_t		*first_connp = connp;
5357 		conn_t		*next_connp;
5358 		mblk_t		*mp1;
5359 
5360 		CONN_INC_REF(connp);
5361 		connp = connp->conn_next;
5362 		for (;;) {
5363 			while (connp != NULL) {
5364 				if (IPCL_UDP_MATCH_V6(connp, lport,
5365 				    ipv6_all_zeros, fport, v6faddr) &&
5366 				    conn_wantpacket(connp, ira, ipha) &&
5367 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5368 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5369 				    ira, connp)))
5370 					break;
5371 				connp = connp->conn_next;
5372 			}
5373 			if (connp == NULL) {
5374 				/* No more interested clients */
5375 				connp = first_connp;
5376 				break;
5377 			}
5378 			if (((mp1 = dupmsg(mp)) == NULL) &&
5379 			    ((mp1 = copymsg(mp)) == NULL)) {
5380 				/* Memory allocation failed */
5381 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5382 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5383 				connp = first_connp;
5384 				break;
5385 			}
5386 			CONN_INC_REF(connp);
5387 			mutex_exit(&connfp->connf_lock);
5388 
5389 			IP_STAT(ipst, ip_udp_fanmb);
5390 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5391 			    NULL, ira);
5392 			mutex_enter(&connfp->connf_lock);
5393 			/* Follow the next pointer before releasing the conn */
5394 			next_connp = connp->conn_next;
5395 			CONN_DEC_REF(connp);
5396 			connp = next_connp;
5397 		}
5398 	}
5399 
5400 	/* Last one.  Send it upstream. */
5401 	mutex_exit(&connfp->connf_lock);
5402 	IP_STAT(ipst, ip_udp_fanmb);
5403 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5404 	CONN_DEC_REF(connp);
5405 }
5406 
5407 /*
5408  * Split an incoming packet's IPv4 options into the label and the other options.
5409  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5410  * clearing out any leftover label or options.
5411  * Otherwise it just makes ipp point into the packet.
5412  *
5413  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5414  */
5415 int
5416 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5417 {
5418 	uchar_t		*opt;
5419 	uint32_t	totallen;
5420 	uint32_t	optval;
5421 	uint32_t	optlen;
5422 
5423 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5424 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5425 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5426 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5427 
5428 	/*
5429 	 * Get length (in 4 byte octets) of IP header options.
5430 	 */
5431 	totallen = ipha->ipha_version_and_hdr_length -
5432 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5433 
5434 	if (totallen == 0) {
5435 		if (!allocate)
5436 			return (0);
5437 
5438 		/* Clear out anything from a previous packet */
5439 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5440 			kmem_free(ipp->ipp_ipv4_options,
5441 			    ipp->ipp_ipv4_options_len);
5442 			ipp->ipp_ipv4_options = NULL;
5443 			ipp->ipp_ipv4_options_len = 0;
5444 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5445 		}
5446 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5447 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5448 			ipp->ipp_label_v4 = NULL;
5449 			ipp->ipp_label_len_v4 = 0;
5450 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5451 		}
5452 		return (0);
5453 	}
5454 
5455 	totallen <<= 2;
5456 	opt = (uchar_t *)&ipha[1];
5457 	if (!is_system_labeled()) {
5458 
5459 	copyall:
5460 		if (!allocate) {
5461 			if (totallen != 0) {
5462 				ipp->ipp_ipv4_options = opt;
5463 				ipp->ipp_ipv4_options_len = totallen;
5464 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5465 			}
5466 			return (0);
5467 		}
5468 		/* Just copy all of options */
5469 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5470 			if (totallen == ipp->ipp_ipv4_options_len) {
5471 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5472 				return (0);
5473 			}
5474 			kmem_free(ipp->ipp_ipv4_options,
5475 			    ipp->ipp_ipv4_options_len);
5476 			ipp->ipp_ipv4_options = NULL;
5477 			ipp->ipp_ipv4_options_len = 0;
5478 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5479 		}
5480 		if (totallen == 0)
5481 			return (0);
5482 
5483 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5484 		if (ipp->ipp_ipv4_options == NULL)
5485 			return (ENOMEM);
5486 		ipp->ipp_ipv4_options_len = totallen;
5487 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5488 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5489 		return (0);
5490 	}
5491 
5492 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5493 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5494 		ipp->ipp_label_v4 = NULL;
5495 		ipp->ipp_label_len_v4 = 0;
5496 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5497 	}
5498 
5499 	/*
5500 	 * Search for CIPSO option.
5501 	 * We assume CIPSO is first in options if it is present.
5502 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5503 	 * prior to the CIPSO option.
5504 	 */
5505 	while (totallen != 0) {
5506 		switch (optval = opt[IPOPT_OPTVAL]) {
5507 		case IPOPT_EOL:
5508 			return (0);
5509 		case IPOPT_NOP:
5510 			optlen = 1;
5511 			break;
5512 		default:
5513 			if (totallen <= IPOPT_OLEN)
5514 				return (EINVAL);
5515 			optlen = opt[IPOPT_OLEN];
5516 			if (optlen < 2)
5517 				return (EINVAL);
5518 		}
5519 		if (optlen > totallen)
5520 			return (EINVAL);
5521 
5522 		switch (optval) {
5523 		case IPOPT_COMSEC:
5524 			if (!allocate) {
5525 				ipp->ipp_label_v4 = opt;
5526 				ipp->ipp_label_len_v4 = optlen;
5527 				ipp->ipp_fields |= IPPF_LABEL_V4;
5528 			} else {
5529 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5530 				    KM_NOSLEEP);
5531 				if (ipp->ipp_label_v4 == NULL)
5532 					return (ENOMEM);
5533 				ipp->ipp_label_len_v4 = optlen;
5534 				ipp->ipp_fields |= IPPF_LABEL_V4;
5535 				bcopy(opt, ipp->ipp_label_v4, optlen);
5536 			}
5537 			totallen -= optlen;
5538 			opt += optlen;
5539 
5540 			/* Skip padding bytes until we get to a multiple of 4 */
5541 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5542 				totallen--;
5543 				opt++;
5544 			}
5545 			/* Remaining as ipp_ipv4_options */
5546 			goto copyall;
5547 		}
5548 		totallen -= optlen;
5549 		opt += optlen;
5550 	}
5551 	/* No CIPSO found; return everything as ipp_ipv4_options */
5552 	totallen = ipha->ipha_version_and_hdr_length -
5553 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5554 	totallen <<= 2;
5555 	opt = (uchar_t *)&ipha[1];
5556 	goto copyall;
5557 }
5558 
5559 /*
5560  * Efficient versions of lookup for an IRE when we only
5561  * match the address.
5562  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5563  * Does not handle multicast addresses.
5564  */
5565 uint_t
5566 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5567 {
5568 	ire_t *ire;
5569 	uint_t result;
5570 
5571 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5572 	ASSERT(ire != NULL);
5573 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5574 		result = IRE_NOROUTE;
5575 	else
5576 		result = ire->ire_type;
5577 	ire_refrele(ire);
5578 	return (result);
5579 }
5580 
5581 /*
5582  * Efficient versions of lookup for an IRE when we only
5583  * match the address.
5584  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5585  * Does not handle multicast addresses.
5586  */
5587 uint_t
5588 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5589 {
5590 	ire_t *ire;
5591 	uint_t result;
5592 
5593 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5594 	ASSERT(ire != NULL);
5595 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5596 		result = IRE_NOROUTE;
5597 	else
5598 		result = ire->ire_type;
5599 	ire_refrele(ire);
5600 	return (result);
5601 }
5602 
5603 /*
5604  * Nobody should be sending
5605  * packets up this stream
5606  */
5607 static void
5608 ip_lrput(queue_t *q, mblk_t *mp)
5609 {
5610 	switch (mp->b_datap->db_type) {
5611 	case M_FLUSH:
5612 		/* Turn around */
5613 		if (*mp->b_rptr & FLUSHW) {
5614 			*mp->b_rptr &= ~FLUSHR;
5615 			qreply(q, mp);
5616 			return;
5617 		}
5618 		break;
5619 	}
5620 	freemsg(mp);
5621 }
5622 
5623 /* Nobody should be sending packets down this stream */
5624 /* ARGSUSED */
5625 void
5626 ip_lwput(queue_t *q, mblk_t *mp)
5627 {
5628 	freemsg(mp);
5629 }
5630 
5631 /*
5632  * Move the first hop in any source route to ipha_dst and remove that part of
5633  * the source route.  Called by other protocols.  Errors in option formatting
5634  * are ignored - will be handled by ip_output_options. Return the final
5635  * destination (either ipha_dst or the last entry in a source route.)
5636  */
5637 ipaddr_t
5638 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5639 {
5640 	ipoptp_t	opts;
5641 	uchar_t		*opt;
5642 	uint8_t		optval;
5643 	uint8_t		optlen;
5644 	ipaddr_t	dst;
5645 	int		i;
5646 	ip_stack_t	*ipst = ns->netstack_ip;
5647 
5648 	ip2dbg(("ip_massage_options\n"));
5649 	dst = ipha->ipha_dst;
5650 	for (optval = ipoptp_first(&opts, ipha);
5651 	    optval != IPOPT_EOL;
5652 	    optval = ipoptp_next(&opts)) {
5653 		opt = opts.ipoptp_cur;
5654 		switch (optval) {
5655 			uint8_t off;
5656 		case IPOPT_SSRR:
5657 		case IPOPT_LSRR:
5658 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5659 				ip1dbg(("ip_massage_options: bad src route\n"));
5660 				break;
5661 			}
5662 			optlen = opts.ipoptp_len;
5663 			off = opt[IPOPT_OFFSET];
5664 			off--;
5665 		redo_srr:
5666 			if (optlen < IP_ADDR_LEN ||
5667 			    off > optlen - IP_ADDR_LEN) {
5668 				/* End of source route */
5669 				ip1dbg(("ip_massage_options: end of SR\n"));
5670 				break;
5671 			}
5672 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5673 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5674 			    ntohl(dst)));
5675 			/*
5676 			 * Check if our address is present more than
5677 			 * once as consecutive hops in source route.
5678 			 * XXX verify per-interface ip_forwarding
5679 			 * for source route?
5680 			 */
5681 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5682 				off += IP_ADDR_LEN;
5683 				goto redo_srr;
5684 			}
5685 			if (dst == htonl(INADDR_LOOPBACK)) {
5686 				ip1dbg(("ip_massage_options: loopback addr in "
5687 				    "source route!\n"));
5688 				break;
5689 			}
5690 			/*
5691 			 * Update ipha_dst to be the first hop and remove the
5692 			 * first hop from the source route (by overwriting
5693 			 * part of the option with NOP options).
5694 			 */
5695 			ipha->ipha_dst = dst;
5696 			/* Put the last entry in dst */
5697 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5698 			    3;
5699 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5700 
5701 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5702 			    ntohl(dst)));
5703 			/* Move down and overwrite */
5704 			opt[IP_ADDR_LEN] = opt[0];
5705 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5706 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5707 			for (i = 0; i < IP_ADDR_LEN; i++)
5708 				opt[i] = IPOPT_NOP;
5709 			break;
5710 		}
5711 	}
5712 	return (dst);
5713 }
5714 
5715 /*
5716  * Return the network mask
5717  * associated with the specified address.
5718  */
5719 ipaddr_t
5720 ip_net_mask(ipaddr_t addr)
5721 {
5722 	uchar_t	*up = (uchar_t *)&addr;
5723 	ipaddr_t mask = 0;
5724 	uchar_t	*maskp = (uchar_t *)&mask;
5725 
5726 #if defined(__i386) || defined(__amd64)
5727 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5728 #endif
5729 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5730 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5731 #endif
5732 	if (CLASSD(addr)) {
5733 		maskp[0] = 0xF0;
5734 		return (mask);
5735 	}
5736 
5737 	/* We assume Class E default netmask to be 32 */
5738 	if (CLASSE(addr))
5739 		return (0xffffffffU);
5740 
5741 	if (addr == 0)
5742 		return (0);
5743 	maskp[0] = 0xFF;
5744 	if ((up[0] & 0x80) == 0)
5745 		return (mask);
5746 
5747 	maskp[1] = 0xFF;
5748 	if ((up[0] & 0xC0) == 0x80)
5749 		return (mask);
5750 
5751 	maskp[2] = 0xFF;
5752 	if ((up[0] & 0xE0) == 0xC0)
5753 		return (mask);
5754 
5755 	/* Otherwise return no mask */
5756 	return ((ipaddr_t)0);
5757 }
5758 
5759 /* Name/Value Table Lookup Routine */
5760 char *
5761 ip_nv_lookup(nv_t *nv, int value)
5762 {
5763 	if (!nv)
5764 		return (NULL);
5765 	for (; nv->nv_name; nv++) {
5766 		if (nv->nv_value == value)
5767 			return (nv->nv_name);
5768 	}
5769 	return ("unknown");
5770 }
5771 
5772 static int
5773 ip_wait_for_info_ack(ill_t *ill)
5774 {
5775 	int err;
5776 
5777 	mutex_enter(&ill->ill_lock);
5778 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5779 		/*
5780 		 * Return value of 0 indicates a pending signal.
5781 		 */
5782 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5783 		if (err == 0) {
5784 			mutex_exit(&ill->ill_lock);
5785 			return (EINTR);
5786 		}
5787 	}
5788 	mutex_exit(&ill->ill_lock);
5789 	/*
5790 	 * ip_rput_other could have set an error  in ill_error on
5791 	 * receipt of M_ERROR.
5792 	 */
5793 	return (ill->ill_error);
5794 }
5795 
5796 /*
5797  * This is a module open, i.e. this is a control stream for access
5798  * to a DLPI device.  We allocate an ill_t as the instance data in
5799  * this case.
5800  */
5801 static int
5802 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5803 {
5804 	ill_t	*ill;
5805 	int	err;
5806 	zoneid_t zoneid;
5807 	netstack_t *ns;
5808 	ip_stack_t *ipst;
5809 
5810 	/*
5811 	 * Prevent unprivileged processes from pushing IP so that
5812 	 * they can't send raw IP.
5813 	 */
5814 	if (secpolicy_net_rawaccess(credp) != 0)
5815 		return (EPERM);
5816 
5817 	ns = netstack_find_by_cred(credp);
5818 	ASSERT(ns != NULL);
5819 	ipst = ns->netstack_ip;
5820 	ASSERT(ipst != NULL);
5821 
5822 	/*
5823 	 * For exclusive stacks we set the zoneid to zero
5824 	 * to make IP operate as if in the global zone.
5825 	 */
5826 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5827 		zoneid = GLOBAL_ZONEID;
5828 	else
5829 		zoneid = crgetzoneid(credp);
5830 
5831 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5832 	q->q_ptr = WR(q)->q_ptr = ill;
5833 	ill->ill_ipst = ipst;
5834 	ill->ill_zoneid = zoneid;
5835 
5836 	/*
5837 	 * ill_init initializes the ill fields and then sends down
5838 	 * down a DL_INFO_REQ after calling qprocson.
5839 	 */
5840 	err = ill_init(q, ill);
5841 
5842 	if (err != 0) {
5843 		mi_free(ill);
5844 		netstack_rele(ipst->ips_netstack);
5845 		q->q_ptr = NULL;
5846 		WR(q)->q_ptr = NULL;
5847 		return (err);
5848 	}
5849 
5850 	/*
5851 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5852 	 *
5853 	 * ill_init initializes the ipsq marking this thread as
5854 	 * writer
5855 	 */
5856 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5857 	err = ip_wait_for_info_ack(ill);
5858 	if (err == 0)
5859 		ill->ill_credp = credp;
5860 	else
5861 		goto fail;
5862 
5863 	crhold(credp);
5864 
5865 	mutex_enter(&ipst->ips_ip_mi_lock);
5866 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5867 	    sflag, credp);
5868 	mutex_exit(&ipst->ips_ip_mi_lock);
5869 fail:
5870 	if (err) {
5871 		(void) ip_close(q, 0);
5872 		return (err);
5873 	}
5874 	return (0);
5875 }
5876 
5877 /* For /dev/ip aka AF_INET open */
5878 int
5879 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5880 {
5881 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5882 }
5883 
5884 /* For /dev/ip6 aka AF_INET6 open */
5885 int
5886 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5887 {
5888 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5889 }
5890 
5891 /* IP open routine. */
5892 int
5893 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5894     boolean_t isv6)
5895 {
5896 	conn_t 		*connp;
5897 	major_t		maj;
5898 	zoneid_t	zoneid;
5899 	netstack_t	*ns;
5900 	ip_stack_t	*ipst;
5901 
5902 	/* Allow reopen. */
5903 	if (q->q_ptr != NULL)
5904 		return (0);
5905 
5906 	if (sflag & MODOPEN) {
5907 		/* This is a module open */
5908 		return (ip_modopen(q, devp, flag, sflag, credp));
5909 	}
5910 
5911 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5912 		/*
5913 		 * Non streams based socket looking for a stream
5914 		 * to access IP
5915 		 */
5916 		return (ip_helper_stream_setup(q, devp, flag, sflag,
5917 		    credp, isv6));
5918 	}
5919 
5920 	ns = netstack_find_by_cred(credp);
5921 	ASSERT(ns != NULL);
5922 	ipst = ns->netstack_ip;
5923 	ASSERT(ipst != NULL);
5924 
5925 	/*
5926 	 * For exclusive stacks we set the zoneid to zero
5927 	 * to make IP operate as if in the global zone.
5928 	 */
5929 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5930 		zoneid = GLOBAL_ZONEID;
5931 	else
5932 		zoneid = crgetzoneid(credp);
5933 
5934 	/*
5935 	 * We are opening as a device. This is an IP client stream, and we
5936 	 * allocate an conn_t as the instance data.
5937 	 */
5938 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
5939 
5940 	/*
5941 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
5942 	 * done by netstack_find_by_cred()
5943 	 */
5944 	netstack_rele(ipst->ips_netstack);
5945 
5946 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
5947 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
5948 	connp->conn_ixa->ixa_zoneid = zoneid;
5949 	connp->conn_zoneid = zoneid;
5950 
5951 	connp->conn_rq = q;
5952 	q->q_ptr = WR(q)->q_ptr = connp;
5953 
5954 	/* Minor tells us which /dev entry was opened */
5955 	if (isv6) {
5956 		connp->conn_family = AF_INET6;
5957 		connp->conn_ipversion = IPV6_VERSION;
5958 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
5959 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
5960 	} else {
5961 		connp->conn_family = AF_INET;
5962 		connp->conn_ipversion = IPV4_VERSION;
5963 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
5964 	}
5965 
5966 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
5967 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
5968 		connp->conn_minor_arena = ip_minor_arena_la;
5969 	} else {
5970 		/*
5971 		 * Either minor numbers in the large arena were exhausted
5972 		 * or a non socket application is doing the open.
5973 		 * Try to allocate from the small arena.
5974 		 */
5975 		if ((connp->conn_dev =
5976 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
5977 			/* CONN_DEC_REF takes care of netstack_rele() */
5978 			q->q_ptr = WR(q)->q_ptr = NULL;
5979 			CONN_DEC_REF(connp);
5980 			return (EBUSY);
5981 		}
5982 		connp->conn_minor_arena = ip_minor_arena_sa;
5983 	}
5984 
5985 	maj = getemajor(*devp);
5986 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
5987 
5988 	/*
5989 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
5990 	 */
5991 	connp->conn_cred = credp;
5992 	connp->conn_cpid = curproc->p_pid;
5993 	/* Cache things in ixa without an extra refhold */
5994 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
5995 	connp->conn_ixa->ixa_cred = connp->conn_cred;
5996 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
5997 	if (is_system_labeled())
5998 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
5999 
6000 	/*
6001 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6002 	 */
6003 	connp->conn_recv = ip_conn_input;
6004 	connp->conn_recvicmp = ip_conn_input_icmp;
6005 
6006 	crhold(connp->conn_cred);
6007 
6008 	/*
6009 	 * If the caller has the process-wide flag set, then default to MAC
6010 	 * exempt mode.  This allows read-down to unlabeled hosts.
6011 	 */
6012 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6013 		connp->conn_mac_mode = CONN_MAC_AWARE;
6014 
6015 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6016 
6017 	connp->conn_rq = q;
6018 	connp->conn_wq = WR(q);
6019 
6020 	/* Non-zero default values */
6021 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6022 
6023 	/*
6024 	 * Make the conn globally visible to walkers
6025 	 */
6026 	ASSERT(connp->conn_ref == 1);
6027 	mutex_enter(&connp->conn_lock);
6028 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6029 	mutex_exit(&connp->conn_lock);
6030 
6031 	qprocson(q);
6032 
6033 	return (0);
6034 }
6035 
6036 /*
6037  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6038  * all of them are copied to the conn_t. If the req is "zero", the policy is
6039  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6040  * fields.
6041  * We keep only the latest setting of the policy and thus policy setting
6042  * is not incremental/cumulative.
6043  *
6044  * Requests to set policies with multiple alternative actions will
6045  * go through a different API.
6046  */
6047 int
6048 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6049 {
6050 	uint_t ah_req = 0;
6051 	uint_t esp_req = 0;
6052 	uint_t se_req = 0;
6053 	ipsec_act_t *actp = NULL;
6054 	uint_t nact;
6055 	ipsec_policy_head_t *ph;
6056 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6057 	int error = 0;
6058 	netstack_t	*ns = connp->conn_netstack;
6059 	ip_stack_t	*ipst = ns->netstack_ip;
6060 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6061 
6062 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6063 
6064 	/*
6065 	 * The IP_SEC_OPT option does not allow variable length parameters,
6066 	 * hence a request cannot be NULL.
6067 	 */
6068 	if (req == NULL)
6069 		return (EINVAL);
6070 
6071 	ah_req = req->ipsr_ah_req;
6072 	esp_req = req->ipsr_esp_req;
6073 	se_req = req->ipsr_self_encap_req;
6074 
6075 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6076 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6077 		return (EINVAL);
6078 
6079 	/*
6080 	 * Are we dealing with a request to reset the policy (i.e.
6081 	 * zero requests).
6082 	 */
6083 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6084 	    (esp_req & REQ_MASK) == 0 &&
6085 	    (se_req & REQ_MASK) == 0);
6086 
6087 	if (!is_pol_reset) {
6088 		/*
6089 		 * If we couldn't load IPsec, fail with "protocol
6090 		 * not supported".
6091 		 * IPsec may not have been loaded for a request with zero
6092 		 * policies, so we don't fail in this case.
6093 		 */
6094 		mutex_enter(&ipss->ipsec_loader_lock);
6095 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6096 			mutex_exit(&ipss->ipsec_loader_lock);
6097 			return (EPROTONOSUPPORT);
6098 		}
6099 		mutex_exit(&ipss->ipsec_loader_lock);
6100 
6101 		/*
6102 		 * Test for valid requests. Invalid algorithms
6103 		 * need to be tested by IPsec code because new
6104 		 * algorithms can be added dynamically.
6105 		 */
6106 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6107 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6108 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6109 			return (EINVAL);
6110 		}
6111 
6112 		/*
6113 		 * Only privileged users can issue these
6114 		 * requests.
6115 		 */
6116 		if (((ah_req & IPSEC_PREF_NEVER) ||
6117 		    (esp_req & IPSEC_PREF_NEVER) ||
6118 		    (se_req & IPSEC_PREF_NEVER)) &&
6119 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6120 			return (EPERM);
6121 		}
6122 
6123 		/*
6124 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6125 		 * are mutually exclusive.
6126 		 */
6127 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6128 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6129 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6130 			/* Both of them are set */
6131 			return (EINVAL);
6132 		}
6133 	}
6134 
6135 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6136 
6137 	/*
6138 	 * If we have already cached policies in conn_connect(), don't
6139 	 * let them change now. We cache policies for connections
6140 	 * whose src,dst [addr, port] is known.
6141 	 */
6142 	if (connp->conn_policy_cached) {
6143 		return (EINVAL);
6144 	}
6145 
6146 	/*
6147 	 * We have a zero policies, reset the connection policy if already
6148 	 * set. This will cause the connection to inherit the
6149 	 * global policy, if any.
6150 	 */
6151 	if (is_pol_reset) {
6152 		if (connp->conn_policy != NULL) {
6153 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6154 			connp->conn_policy = NULL;
6155 		}
6156 		connp->conn_in_enforce_policy = B_FALSE;
6157 		connp->conn_out_enforce_policy = B_FALSE;
6158 		return (0);
6159 	}
6160 
6161 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6162 	    ipst->ips_netstack);
6163 	if (ph == NULL)
6164 		goto enomem;
6165 
6166 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6167 	if (actp == NULL)
6168 		goto enomem;
6169 
6170 	/*
6171 	 * Always insert IPv4 policy entries, since they can also apply to
6172 	 * ipv6 sockets being used in ipv4-compat mode.
6173 	 */
6174 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6175 	    IPSEC_TYPE_INBOUND, ns))
6176 		goto enomem;
6177 	is_pol_inserted = B_TRUE;
6178 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6179 	    IPSEC_TYPE_OUTBOUND, ns))
6180 		goto enomem;
6181 
6182 	/*
6183 	 * We're looking at a v6 socket, also insert the v6-specific
6184 	 * entries.
6185 	 */
6186 	if (connp->conn_family == AF_INET6) {
6187 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6188 		    IPSEC_TYPE_INBOUND, ns))
6189 			goto enomem;
6190 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6191 		    IPSEC_TYPE_OUTBOUND, ns))
6192 			goto enomem;
6193 	}
6194 
6195 	ipsec_actvec_free(actp, nact);
6196 
6197 	/*
6198 	 * If the requests need security, set enforce_policy.
6199 	 * If the requests are IPSEC_PREF_NEVER, one should
6200 	 * still set conn_out_enforce_policy so that ip_set_destination
6201 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6202 	 * for connections that we don't cache policy in at connect time,
6203 	 * if global policy matches in ip_output_attach_policy, we
6204 	 * don't wrongly inherit global policy. Similarly, we need
6205 	 * to set conn_in_enforce_policy also so that we don't verify
6206 	 * policy wrongly.
6207 	 */
6208 	if ((ah_req & REQ_MASK) != 0 ||
6209 	    (esp_req & REQ_MASK) != 0 ||
6210 	    (se_req & REQ_MASK) != 0) {
6211 		connp->conn_in_enforce_policy = B_TRUE;
6212 		connp->conn_out_enforce_policy = B_TRUE;
6213 	}
6214 
6215 	return (error);
6216 #undef REQ_MASK
6217 
6218 	/*
6219 	 * Common memory-allocation-failure exit path.
6220 	 */
6221 enomem:
6222 	if (actp != NULL)
6223 		ipsec_actvec_free(actp, nact);
6224 	if (is_pol_inserted)
6225 		ipsec_polhead_flush(ph, ns);
6226 	return (ENOMEM);
6227 }
6228 
6229 /*
6230  * Set socket options for joining and leaving multicast groups.
6231  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6232  * The caller has already check that the option name is consistent with
6233  * the address family of the socket.
6234  */
6235 int
6236 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6237     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6238 {
6239 	int		*i1 = (int *)invalp;
6240 	int		error = 0;
6241 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6242 	struct ip_mreq	*v4_mreqp;
6243 	struct ipv6_mreq *v6_mreqp;
6244 	struct group_req *greqp;
6245 	ire_t *ire;
6246 	boolean_t done = B_FALSE;
6247 	ipaddr_t ifaddr;
6248 	in6_addr_t v6group;
6249 	uint_t ifindex;
6250 	boolean_t mcast_opt = B_TRUE;
6251 	mcast_record_t fmode;
6252 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6253 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6254 
6255 	switch (name) {
6256 	case IP_ADD_MEMBERSHIP:
6257 	case IPV6_JOIN_GROUP:
6258 		mcast_opt = B_FALSE;
6259 		/* FALLTHRU */
6260 	case MCAST_JOIN_GROUP:
6261 		fmode = MODE_IS_EXCLUDE;
6262 		optfn = ip_opt_add_group;
6263 		break;
6264 
6265 	case IP_DROP_MEMBERSHIP:
6266 	case IPV6_LEAVE_GROUP:
6267 		mcast_opt = B_FALSE;
6268 		/* FALLTHRU */
6269 	case MCAST_LEAVE_GROUP:
6270 		fmode = MODE_IS_INCLUDE;
6271 		optfn = ip_opt_delete_group;
6272 		break;
6273 	default:
6274 		ASSERT(0);
6275 	}
6276 
6277 	if (mcast_opt) {
6278 		struct sockaddr_in *sin;
6279 		struct sockaddr_in6 *sin6;
6280 
6281 		greqp = (struct group_req *)i1;
6282 		if (greqp->gr_group.ss_family == AF_INET) {
6283 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6284 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6285 		} else {
6286 			if (!inet6)
6287 				return (EINVAL);	/* Not on INET socket */
6288 
6289 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6290 			v6group = sin6->sin6_addr;
6291 		}
6292 		ifaddr = INADDR_ANY;
6293 		ifindex = greqp->gr_interface;
6294 	} else if (inet6) {
6295 		v6_mreqp = (struct ipv6_mreq *)i1;
6296 		v6group = v6_mreqp->ipv6mr_multiaddr;
6297 		ifaddr = INADDR_ANY;
6298 		ifindex = v6_mreqp->ipv6mr_interface;
6299 	} else {
6300 		v4_mreqp = (struct ip_mreq *)i1;
6301 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6302 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6303 		ifindex = 0;
6304 	}
6305 
6306 	/*
6307 	 * In the multirouting case, we need to replicate
6308 	 * the request on all interfaces that will take part
6309 	 * in replication.  We do so because multirouting is
6310 	 * reflective, thus we will probably receive multi-
6311 	 * casts on those interfaces.
6312 	 * The ip_multirt_apply_membership() succeeds if
6313 	 * the operation succeeds on at least one interface.
6314 	 */
6315 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6316 		ipaddr_t group;
6317 
6318 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6319 
6320 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6321 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6322 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6323 	} else {
6324 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6325 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6326 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6327 	}
6328 	if (ire != NULL) {
6329 		if (ire->ire_flags & RTF_MULTIRT) {
6330 			error = ip_multirt_apply_membership(optfn, ire, connp,
6331 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6332 			done = B_TRUE;
6333 		}
6334 		ire_refrele(ire);
6335 	}
6336 
6337 	if (!done) {
6338 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6339 		    fmode, &ipv6_all_zeros);
6340 	}
6341 	return (error);
6342 }
6343 
6344 /*
6345  * Set socket options for joining and leaving multicast groups
6346  * for specific sources.
6347  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6348  * The caller has already check that the option name is consistent with
6349  * the address family of the socket.
6350  */
6351 int
6352 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6353     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6354 {
6355 	int		*i1 = (int *)invalp;
6356 	int		error = 0;
6357 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6358 	struct ip_mreq_source *imreqp;
6359 	struct group_source_req *gsreqp;
6360 	in6_addr_t v6group, v6src;
6361 	uint32_t ifindex;
6362 	ipaddr_t ifaddr;
6363 	boolean_t mcast_opt = B_TRUE;
6364 	mcast_record_t fmode;
6365 	ire_t *ire;
6366 	boolean_t done = B_FALSE;
6367 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6368 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6369 
6370 	switch (name) {
6371 	case IP_BLOCK_SOURCE:
6372 		mcast_opt = B_FALSE;
6373 		/* FALLTHRU */
6374 	case MCAST_BLOCK_SOURCE:
6375 		fmode = MODE_IS_EXCLUDE;
6376 		optfn = ip_opt_add_group;
6377 		break;
6378 
6379 	case IP_UNBLOCK_SOURCE:
6380 		mcast_opt = B_FALSE;
6381 		/* FALLTHRU */
6382 	case MCAST_UNBLOCK_SOURCE:
6383 		fmode = MODE_IS_EXCLUDE;
6384 		optfn = ip_opt_delete_group;
6385 		break;
6386 
6387 	case IP_ADD_SOURCE_MEMBERSHIP:
6388 		mcast_opt = B_FALSE;
6389 		/* FALLTHRU */
6390 	case MCAST_JOIN_SOURCE_GROUP:
6391 		fmode = MODE_IS_INCLUDE;
6392 		optfn = ip_opt_add_group;
6393 		break;
6394 
6395 	case IP_DROP_SOURCE_MEMBERSHIP:
6396 		mcast_opt = B_FALSE;
6397 		/* FALLTHRU */
6398 	case MCAST_LEAVE_SOURCE_GROUP:
6399 		fmode = MODE_IS_INCLUDE;
6400 		optfn = ip_opt_delete_group;
6401 		break;
6402 	default:
6403 		ASSERT(0);
6404 	}
6405 
6406 	if (mcast_opt) {
6407 		gsreqp = (struct group_source_req *)i1;
6408 		ifindex = gsreqp->gsr_interface;
6409 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6410 			struct sockaddr_in *s;
6411 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6412 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6413 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6414 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6415 		} else {
6416 			struct sockaddr_in6 *s6;
6417 
6418 			if (!inet6)
6419 				return (EINVAL);	/* Not on INET socket */
6420 
6421 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6422 			v6group = s6->sin6_addr;
6423 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6424 			v6src = s6->sin6_addr;
6425 		}
6426 		ifaddr = INADDR_ANY;
6427 	} else {
6428 		imreqp = (struct ip_mreq_source *)i1;
6429 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6430 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6431 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6432 		ifindex = 0;
6433 	}
6434 
6435 	/*
6436 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6437 	 */
6438 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6439 		v6src = ipv6_all_zeros;
6440 
6441 	/*
6442 	 * In the multirouting case, we need to replicate
6443 	 * the request as noted in the mcast cases above.
6444 	 */
6445 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6446 		ipaddr_t group;
6447 
6448 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6449 
6450 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6451 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6452 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6453 	} else {
6454 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6455 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6456 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6457 	}
6458 	if (ire != NULL) {
6459 		if (ire->ire_flags & RTF_MULTIRT) {
6460 			error = ip_multirt_apply_membership(optfn, ire, connp,
6461 			    checkonly, &v6group, fmode, &v6src);
6462 			done = B_TRUE;
6463 		}
6464 		ire_refrele(ire);
6465 	}
6466 	if (!done) {
6467 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6468 		    fmode, &v6src);
6469 	}
6470 	return (error);
6471 }
6472 
6473 /*
6474  * Given a destination address and a pointer to where to put the information
6475  * this routine fills in the mtuinfo.
6476  * The socket must be connected.
6477  * For sctp conn_faddr is the primary address.
6478  */
6479 int
6480 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6481 {
6482 	uint32_t	pmtu = IP_MAXPACKET;
6483 	uint_t		scopeid;
6484 
6485 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6486 		return (-1);
6487 
6488 	/* In case we never sent or called ip_set_destination_v4/v6 */
6489 	if (ixa->ixa_ire != NULL)
6490 		pmtu = ip_get_pmtu(ixa);
6491 
6492 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6493 		scopeid = ixa->ixa_scopeid;
6494 	else
6495 		scopeid = 0;
6496 
6497 	bzero(mtuinfo, sizeof (*mtuinfo));
6498 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6499 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6500 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6501 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6502 	mtuinfo->ip6m_mtu = pmtu;
6503 
6504 	return (sizeof (struct ip6_mtuinfo));
6505 }
6506 
6507 /*
6508  * When the src multihoming is changed from weak to [strong, preferred]
6509  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6510  * and identify routes that were created by user-applications in the
6511  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6512  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6513  * is selected by finding an interface route for the gateway.
6514  */
6515 /* ARGSUSED */
6516 void
6517 ip_ire_rebind_walker(ire_t *ire, void *notused)
6518 {
6519 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6520 		return;
6521 	ire_rebind(ire);
6522 	ire_delete(ire);
6523 }
6524 
6525 /*
6526  * When the src multihoming is changed from  [strong, preferred] to weak,
6527  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6528  * set any entries that were created by user-applications in the unbound state
6529  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6530  */
6531 /* ARGSUSED */
6532 void
6533 ip_ire_unbind_walker(ire_t *ire, void *notused)
6534 {
6535 	ire_t *new_ire;
6536 
6537 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6538 		return;
6539 	if (ire->ire_ipversion == IPV6_VERSION) {
6540 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6541 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6542 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6543 	} else {
6544 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6545 		    (uchar_t *)&ire->ire_mask,
6546 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6547 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6548 	}
6549 	if (new_ire == NULL)
6550 		return;
6551 	new_ire->ire_unbound = B_TRUE;
6552 	/*
6553 	 * The bound ire must first be deleted so that we don't return
6554 	 * the existing one on the attempt to add the unbound new_ire.
6555 	 */
6556 	ire_delete(ire);
6557 	new_ire = ire_add(new_ire);
6558 	if (new_ire != NULL)
6559 		ire_refrele(new_ire);
6560 }
6561 
6562 /*
6563  * When the settings of ip*_strict_src_multihoming tunables are changed,
6564  * all cached routes need to be recomputed. This recomputation needs to be
6565  * done when going from weaker to stronger modes so that the cached ire
6566  * for the connection does not violate the current ip*_strict_src_multihoming
6567  * setting. It also needs to be done when going from stronger to weaker modes,
6568  * so that we fall back to matching on the longest-matching-route (as opposed
6569  * to a shorter match that may have been selected in the strong mode
6570  * to satisfy src_multihoming settings).
6571  *
6572  * The cached ixa_ire entires for all conn_t entries are marked as
6573  * "verify" so that they will be recomputed for the next packet.
6574  */
6575 void
6576 conn_ire_revalidate(conn_t *connp, void *arg)
6577 {
6578 	boolean_t isv6 = (boolean_t)arg;
6579 
6580 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6581 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6582 		return;
6583 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6584 }
6585 
6586 /*
6587  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6588  * When an ipf is passed here for the first time, if
6589  * we already have in-order fragments on the queue, we convert from the fast-
6590  * path reassembly scheme to the hard-case scheme.  From then on, additional
6591  * fragments are reassembled here.  We keep track of the start and end offsets
6592  * of each piece, and the number of holes in the chain.  When the hole count
6593  * goes to zero, we are done!
6594  *
6595  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6596  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6597  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6598  * after the call to ip_reassemble().
6599  */
6600 int
6601 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6602     size_t msg_len)
6603 {
6604 	uint_t	end;
6605 	mblk_t	*next_mp;
6606 	mblk_t	*mp1;
6607 	uint_t	offset;
6608 	boolean_t incr_dups = B_TRUE;
6609 	boolean_t offset_zero_seen = B_FALSE;
6610 	boolean_t pkt_boundary_checked = B_FALSE;
6611 
6612 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6613 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6614 
6615 	/* Add in byte count */
6616 	ipf->ipf_count += msg_len;
6617 	if (ipf->ipf_end) {
6618 		/*
6619 		 * We were part way through in-order reassembly, but now there
6620 		 * is a hole.  We walk through messages already queued, and
6621 		 * mark them for hard case reassembly.  We know that up till
6622 		 * now they were in order starting from offset zero.
6623 		 */
6624 		offset = 0;
6625 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6626 			IP_REASS_SET_START(mp1, offset);
6627 			if (offset == 0) {
6628 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6629 				offset = -ipf->ipf_nf_hdr_len;
6630 			}
6631 			offset += mp1->b_wptr - mp1->b_rptr;
6632 			IP_REASS_SET_END(mp1, offset);
6633 		}
6634 		/* One hole at the end. */
6635 		ipf->ipf_hole_cnt = 1;
6636 		/* Brand it as a hard case, forever. */
6637 		ipf->ipf_end = 0;
6638 	}
6639 	/* Walk through all the new pieces. */
6640 	do {
6641 		end = start + (mp->b_wptr - mp->b_rptr);
6642 		/*
6643 		 * If start is 0, decrease 'end' only for the first mblk of
6644 		 * the fragment. Otherwise 'end' can get wrong value in the
6645 		 * second pass of the loop if first mblk is exactly the
6646 		 * size of ipf_nf_hdr_len.
6647 		 */
6648 		if (start == 0 && !offset_zero_seen) {
6649 			/* First segment */
6650 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6651 			end -= ipf->ipf_nf_hdr_len;
6652 			offset_zero_seen = B_TRUE;
6653 		}
6654 		next_mp = mp->b_cont;
6655 		/*
6656 		 * We are checking to see if there is any interesing data
6657 		 * to process.  If there isn't and the mblk isn't the
6658 		 * one which carries the unfragmentable header then we
6659 		 * drop it.  It's possible to have just the unfragmentable
6660 		 * header come through without any data.  That needs to be
6661 		 * saved.
6662 		 *
6663 		 * If the assert at the top of this function holds then the
6664 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6665 		 * is infrequently traveled enough that the test is left in
6666 		 * to protect against future code changes which break that
6667 		 * invariant.
6668 		 */
6669 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6670 			/* Empty.  Blast it. */
6671 			IP_REASS_SET_START(mp, 0);
6672 			IP_REASS_SET_END(mp, 0);
6673 			/*
6674 			 * If the ipf points to the mblk we are about to free,
6675 			 * update ipf to point to the next mblk (or NULL
6676 			 * if none).
6677 			 */
6678 			if (ipf->ipf_mp->b_cont == mp)
6679 				ipf->ipf_mp->b_cont = next_mp;
6680 			freeb(mp);
6681 			continue;
6682 		}
6683 		mp->b_cont = NULL;
6684 		IP_REASS_SET_START(mp, start);
6685 		IP_REASS_SET_END(mp, end);
6686 		if (!ipf->ipf_tail_mp) {
6687 			ipf->ipf_tail_mp = mp;
6688 			ipf->ipf_mp->b_cont = mp;
6689 			if (start == 0 || !more) {
6690 				ipf->ipf_hole_cnt = 1;
6691 				/*
6692 				 * if the first fragment comes in more than one
6693 				 * mblk, this loop will be executed for each
6694 				 * mblk. Need to adjust hole count so exiting
6695 				 * this routine will leave hole count at 1.
6696 				 */
6697 				if (next_mp)
6698 					ipf->ipf_hole_cnt++;
6699 			} else
6700 				ipf->ipf_hole_cnt = 2;
6701 			continue;
6702 		} else if (ipf->ipf_last_frag_seen && !more &&
6703 		    !pkt_boundary_checked) {
6704 			/*
6705 			 * We check datagram boundary only if this fragment
6706 			 * claims to be the last fragment and we have seen a
6707 			 * last fragment in the past too. We do this only
6708 			 * once for a given fragment.
6709 			 *
6710 			 * start cannot be 0 here as fragments with start=0
6711 			 * and MF=0 gets handled as a complete packet. These
6712 			 * fragments should not reach here.
6713 			 */
6714 
6715 			if (start + msgdsize(mp) !=
6716 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6717 				/*
6718 				 * We have two fragments both of which claim
6719 				 * to be the last fragment but gives conflicting
6720 				 * information about the whole datagram size.
6721 				 * Something fishy is going on. Drop the
6722 				 * fragment and free up the reassembly list.
6723 				 */
6724 				return (IP_REASS_FAILED);
6725 			}
6726 
6727 			/*
6728 			 * We shouldn't come to this code block again for this
6729 			 * particular fragment.
6730 			 */
6731 			pkt_boundary_checked = B_TRUE;
6732 		}
6733 
6734 		/* New stuff at or beyond tail? */
6735 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6736 		if (start >= offset) {
6737 			if (ipf->ipf_last_frag_seen) {
6738 				/* current fragment is beyond last fragment */
6739 				return (IP_REASS_FAILED);
6740 			}
6741 			/* Link it on end. */
6742 			ipf->ipf_tail_mp->b_cont = mp;
6743 			ipf->ipf_tail_mp = mp;
6744 			if (more) {
6745 				if (start != offset)
6746 					ipf->ipf_hole_cnt++;
6747 			} else if (start == offset && next_mp == NULL)
6748 					ipf->ipf_hole_cnt--;
6749 			continue;
6750 		}
6751 		mp1 = ipf->ipf_mp->b_cont;
6752 		offset = IP_REASS_START(mp1);
6753 		/* New stuff at the front? */
6754 		if (start < offset) {
6755 			if (start == 0) {
6756 				if (end >= offset) {
6757 					/* Nailed the hole at the begining. */
6758 					ipf->ipf_hole_cnt--;
6759 				}
6760 			} else if (end < offset) {
6761 				/*
6762 				 * A hole, stuff, and a hole where there used
6763 				 * to be just a hole.
6764 				 */
6765 				ipf->ipf_hole_cnt++;
6766 			}
6767 			mp->b_cont = mp1;
6768 			/* Check for overlap. */
6769 			while (end > offset) {
6770 				if (end < IP_REASS_END(mp1)) {
6771 					mp->b_wptr -= end - offset;
6772 					IP_REASS_SET_END(mp, offset);
6773 					BUMP_MIB(ill->ill_ip_mib,
6774 					    ipIfStatsReasmPartDups);
6775 					break;
6776 				}
6777 				/* Did we cover another hole? */
6778 				if ((mp1->b_cont &&
6779 				    IP_REASS_END(mp1) !=
6780 				    IP_REASS_START(mp1->b_cont) &&
6781 				    end >= IP_REASS_START(mp1->b_cont)) ||
6782 				    (!ipf->ipf_last_frag_seen && !more)) {
6783 					ipf->ipf_hole_cnt--;
6784 				}
6785 				/* Clip out mp1. */
6786 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6787 					/*
6788 					 * After clipping out mp1, this guy
6789 					 * is now hanging off the end.
6790 					 */
6791 					ipf->ipf_tail_mp = mp;
6792 				}
6793 				IP_REASS_SET_START(mp1, 0);
6794 				IP_REASS_SET_END(mp1, 0);
6795 				/* Subtract byte count */
6796 				ipf->ipf_count -= mp1->b_datap->db_lim -
6797 				    mp1->b_datap->db_base;
6798 				freeb(mp1);
6799 				BUMP_MIB(ill->ill_ip_mib,
6800 				    ipIfStatsReasmPartDups);
6801 				mp1 = mp->b_cont;
6802 				if (!mp1)
6803 					break;
6804 				offset = IP_REASS_START(mp1);
6805 			}
6806 			ipf->ipf_mp->b_cont = mp;
6807 			continue;
6808 		}
6809 		/*
6810 		 * The new piece starts somewhere between the start of the head
6811 		 * and before the end of the tail.
6812 		 */
6813 		for (; mp1; mp1 = mp1->b_cont) {
6814 			offset = IP_REASS_END(mp1);
6815 			if (start < offset) {
6816 				if (end <= offset) {
6817 					/* Nothing new. */
6818 					IP_REASS_SET_START(mp, 0);
6819 					IP_REASS_SET_END(mp, 0);
6820 					/* Subtract byte count */
6821 					ipf->ipf_count -= mp->b_datap->db_lim -
6822 					    mp->b_datap->db_base;
6823 					if (incr_dups) {
6824 						ipf->ipf_num_dups++;
6825 						incr_dups = B_FALSE;
6826 					}
6827 					freeb(mp);
6828 					BUMP_MIB(ill->ill_ip_mib,
6829 					    ipIfStatsReasmDuplicates);
6830 					break;
6831 				}
6832 				/*
6833 				 * Trim redundant stuff off beginning of new
6834 				 * piece.
6835 				 */
6836 				IP_REASS_SET_START(mp, offset);
6837 				mp->b_rptr += offset - start;
6838 				BUMP_MIB(ill->ill_ip_mib,
6839 				    ipIfStatsReasmPartDups);
6840 				start = offset;
6841 				if (!mp1->b_cont) {
6842 					/*
6843 					 * After trimming, this guy is now
6844 					 * hanging off the end.
6845 					 */
6846 					mp1->b_cont = mp;
6847 					ipf->ipf_tail_mp = mp;
6848 					if (!more) {
6849 						ipf->ipf_hole_cnt--;
6850 					}
6851 					break;
6852 				}
6853 			}
6854 			if (start >= IP_REASS_START(mp1->b_cont))
6855 				continue;
6856 			/* Fill a hole */
6857 			if (start > offset)
6858 				ipf->ipf_hole_cnt++;
6859 			mp->b_cont = mp1->b_cont;
6860 			mp1->b_cont = mp;
6861 			mp1 = mp->b_cont;
6862 			offset = IP_REASS_START(mp1);
6863 			if (end >= offset) {
6864 				ipf->ipf_hole_cnt--;
6865 				/* Check for overlap. */
6866 				while (end > offset) {
6867 					if (end < IP_REASS_END(mp1)) {
6868 						mp->b_wptr -= end - offset;
6869 						IP_REASS_SET_END(mp, offset);
6870 						/*
6871 						 * TODO we might bump
6872 						 * this up twice if there is
6873 						 * overlap at both ends.
6874 						 */
6875 						BUMP_MIB(ill->ill_ip_mib,
6876 						    ipIfStatsReasmPartDups);
6877 						break;
6878 					}
6879 					/* Did we cover another hole? */
6880 					if ((mp1->b_cont &&
6881 					    IP_REASS_END(mp1)
6882 					    != IP_REASS_START(mp1->b_cont) &&
6883 					    end >=
6884 					    IP_REASS_START(mp1->b_cont)) ||
6885 					    (!ipf->ipf_last_frag_seen &&
6886 					    !more)) {
6887 						ipf->ipf_hole_cnt--;
6888 					}
6889 					/* Clip out mp1. */
6890 					if ((mp->b_cont = mp1->b_cont) ==
6891 					    NULL) {
6892 						/*
6893 						 * After clipping out mp1,
6894 						 * this guy is now hanging
6895 						 * off the end.
6896 						 */
6897 						ipf->ipf_tail_mp = mp;
6898 					}
6899 					IP_REASS_SET_START(mp1, 0);
6900 					IP_REASS_SET_END(mp1, 0);
6901 					/* Subtract byte count */
6902 					ipf->ipf_count -=
6903 					    mp1->b_datap->db_lim -
6904 					    mp1->b_datap->db_base;
6905 					freeb(mp1);
6906 					BUMP_MIB(ill->ill_ip_mib,
6907 					    ipIfStatsReasmPartDups);
6908 					mp1 = mp->b_cont;
6909 					if (!mp1)
6910 						break;
6911 					offset = IP_REASS_START(mp1);
6912 				}
6913 			}
6914 			break;
6915 		}
6916 	} while (start = end, mp = next_mp);
6917 
6918 	/* Fragment just processed could be the last one. Remember this fact */
6919 	if (!more)
6920 		ipf->ipf_last_frag_seen = B_TRUE;
6921 
6922 	/* Still got holes? */
6923 	if (ipf->ipf_hole_cnt)
6924 		return (IP_REASS_PARTIAL);
6925 	/* Clean up overloaded fields to avoid upstream disasters. */
6926 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6927 		IP_REASS_SET_START(mp1, 0);
6928 		IP_REASS_SET_END(mp1, 0);
6929 	}
6930 	return (IP_REASS_COMPLETE);
6931 }
6932 
6933 /*
6934  * Fragmentation reassembly.  Each ILL has a hash table for
6935  * queuing packets undergoing reassembly for all IPIFs
6936  * associated with the ILL.  The hash is based on the packet
6937  * IP ident field.  The ILL frag hash table was allocated
6938  * as a timer block at the time the ILL was created.  Whenever
6939  * there is anything on the reassembly queue, the timer will
6940  * be running.  Returns the reassembled packet if reassembly completes.
6941  */
6942 mblk_t *
6943 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
6944 {
6945 	uint32_t	frag_offset_flags;
6946 	mblk_t		*t_mp;
6947 	ipaddr_t	dst;
6948 	uint8_t		proto = ipha->ipha_protocol;
6949 	uint32_t	sum_val;
6950 	uint16_t	sum_flags;
6951 	ipf_t		*ipf;
6952 	ipf_t		**ipfp;
6953 	ipfb_t		*ipfb;
6954 	uint16_t	ident;
6955 	uint32_t	offset;
6956 	ipaddr_t	src;
6957 	uint_t		hdr_length;
6958 	uint32_t	end;
6959 	mblk_t		*mp1;
6960 	mblk_t		*tail_mp;
6961 	size_t		count;
6962 	size_t		msg_len;
6963 	uint8_t		ecn_info = 0;
6964 	uint32_t	packet_size;
6965 	boolean_t	pruned = B_FALSE;
6966 	ill_t		*ill = ira->ira_ill;
6967 	ip_stack_t	*ipst = ill->ill_ipst;
6968 
6969 	/*
6970 	 * Drop the fragmented as early as possible, if
6971 	 * we don't have resource(s) to re-assemble.
6972 	 */
6973 	if (ipst->ips_ip_reass_queue_bytes == 0) {
6974 		freemsg(mp);
6975 		return (NULL);
6976 	}
6977 
6978 	/* Check for fragmentation offset; return if there's none */
6979 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
6980 	    (IPH_MF | IPH_OFFSET)) == 0)
6981 		return (mp);
6982 
6983 	/*
6984 	 * We utilize hardware computed checksum info only for UDP since
6985 	 * IP fragmentation is a normal occurrence for the protocol.  In
6986 	 * addition, checksum offload support for IP fragments carrying
6987 	 * UDP payload is commonly implemented across network adapters.
6988 	 */
6989 	ASSERT(ira->ira_rill != NULL);
6990 	if (proto == IPPROTO_UDP && dohwcksum &&
6991 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
6992 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
6993 		mblk_t *mp1 = mp->b_cont;
6994 		int32_t len;
6995 
6996 		/* Record checksum information from the packet */
6997 		sum_val = (uint32_t)DB_CKSUM16(mp);
6998 		sum_flags = DB_CKSUMFLAGS(mp);
6999 
7000 		/* IP payload offset from beginning of mblk */
7001 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7002 
7003 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7004 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7005 		    offset >= DB_CKSUMSTART(mp) &&
7006 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7007 			uint32_t adj;
7008 			/*
7009 			 * Partial checksum has been calculated by hardware
7010 			 * and attached to the packet; in addition, any
7011 			 * prepended extraneous data is even byte aligned.
7012 			 * If any such data exists, we adjust the checksum;
7013 			 * this would also handle any postpended data.
7014 			 */
7015 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7016 			    mp, mp1, len, adj);
7017 
7018 			/* One's complement subtract extraneous checksum */
7019 			if (adj >= sum_val)
7020 				sum_val = ~(adj - sum_val) & 0xFFFF;
7021 			else
7022 				sum_val -= adj;
7023 		}
7024 	} else {
7025 		sum_val = 0;
7026 		sum_flags = 0;
7027 	}
7028 
7029 	/* Clear hardware checksumming flag */
7030 	DB_CKSUMFLAGS(mp) = 0;
7031 
7032 	ident = ipha->ipha_ident;
7033 	offset = (frag_offset_flags << 3) & 0xFFFF;
7034 	src = ipha->ipha_src;
7035 	dst = ipha->ipha_dst;
7036 	hdr_length = IPH_HDR_LENGTH(ipha);
7037 	end = ntohs(ipha->ipha_length) - hdr_length;
7038 
7039 	/* If end == 0 then we have a packet with no data, so just free it */
7040 	if (end == 0) {
7041 		freemsg(mp);
7042 		return (NULL);
7043 	}
7044 
7045 	/* Record the ECN field info. */
7046 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7047 	if (offset != 0) {
7048 		/*
7049 		 * If this isn't the first piece, strip the header, and
7050 		 * add the offset to the end value.
7051 		 */
7052 		mp->b_rptr += hdr_length;
7053 		end += offset;
7054 	}
7055 
7056 	/* Handle vnic loopback of fragments */
7057 	if (mp->b_datap->db_ref > 2)
7058 		msg_len = 0;
7059 	else
7060 		msg_len = MBLKSIZE(mp);
7061 
7062 	tail_mp = mp;
7063 	while (tail_mp->b_cont != NULL) {
7064 		tail_mp = tail_mp->b_cont;
7065 		if (tail_mp->b_datap->db_ref <= 2)
7066 			msg_len += MBLKSIZE(tail_mp);
7067 	}
7068 
7069 	/* If the reassembly list for this ILL will get too big, prune it */
7070 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7071 	    ipst->ips_ip_reass_queue_bytes) {
7072 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7073 		    uint_t, ill->ill_frag_count,
7074 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7075 		ill_frag_prune(ill,
7076 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7077 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7078 		pruned = B_TRUE;
7079 	}
7080 
7081 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7082 	mutex_enter(&ipfb->ipfb_lock);
7083 
7084 	ipfp = &ipfb->ipfb_ipf;
7085 	/* Try to find an existing fragment queue for this packet. */
7086 	for (;;) {
7087 		ipf = ipfp[0];
7088 		if (ipf != NULL) {
7089 			/*
7090 			 * It has to match on ident and src/dst address.
7091 			 */
7092 			if (ipf->ipf_ident == ident &&
7093 			    ipf->ipf_src == src &&
7094 			    ipf->ipf_dst == dst &&
7095 			    ipf->ipf_protocol == proto) {
7096 				/*
7097 				 * If we have received too many
7098 				 * duplicate fragments for this packet
7099 				 * free it.
7100 				 */
7101 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7102 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7103 					freemsg(mp);
7104 					mutex_exit(&ipfb->ipfb_lock);
7105 					return (NULL);
7106 				}
7107 				/* Found it. */
7108 				break;
7109 			}
7110 			ipfp = &ipf->ipf_hash_next;
7111 			continue;
7112 		}
7113 
7114 		/*
7115 		 * If we pruned the list, do we want to store this new
7116 		 * fragment?. We apply an optimization here based on the
7117 		 * fact that most fragments will be received in order.
7118 		 * So if the offset of this incoming fragment is zero,
7119 		 * it is the first fragment of a new packet. We will
7120 		 * keep it.  Otherwise drop the fragment, as we have
7121 		 * probably pruned the packet already (since the
7122 		 * packet cannot be found).
7123 		 */
7124 		if (pruned && offset != 0) {
7125 			mutex_exit(&ipfb->ipfb_lock);
7126 			freemsg(mp);
7127 			return (NULL);
7128 		}
7129 
7130 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7131 			/*
7132 			 * Too many fragmented packets in this hash
7133 			 * bucket. Free the oldest.
7134 			 */
7135 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7136 		}
7137 
7138 		/* New guy.  Allocate a frag message. */
7139 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7140 		if (mp1 == NULL) {
7141 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7142 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7143 			freemsg(mp);
7144 reass_done:
7145 			mutex_exit(&ipfb->ipfb_lock);
7146 			return (NULL);
7147 		}
7148 
7149 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7150 		mp1->b_cont = mp;
7151 
7152 		/* Initialize the fragment header. */
7153 		ipf = (ipf_t *)mp1->b_rptr;
7154 		ipf->ipf_mp = mp1;
7155 		ipf->ipf_ptphn = ipfp;
7156 		ipfp[0] = ipf;
7157 		ipf->ipf_hash_next = NULL;
7158 		ipf->ipf_ident = ident;
7159 		ipf->ipf_protocol = proto;
7160 		ipf->ipf_src = src;
7161 		ipf->ipf_dst = dst;
7162 		ipf->ipf_nf_hdr_len = 0;
7163 		/* Record reassembly start time. */
7164 		ipf->ipf_timestamp = gethrestime_sec();
7165 		/* Record ipf generation and account for frag header */
7166 		ipf->ipf_gen = ill->ill_ipf_gen++;
7167 		ipf->ipf_count = MBLKSIZE(mp1);
7168 		ipf->ipf_last_frag_seen = B_FALSE;
7169 		ipf->ipf_ecn = ecn_info;
7170 		ipf->ipf_num_dups = 0;
7171 		ipfb->ipfb_frag_pkts++;
7172 		ipf->ipf_checksum = 0;
7173 		ipf->ipf_checksum_flags = 0;
7174 
7175 		/* Store checksum value in fragment header */
7176 		if (sum_flags != 0) {
7177 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7178 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7179 			ipf->ipf_checksum = sum_val;
7180 			ipf->ipf_checksum_flags = sum_flags;
7181 		}
7182 
7183 		/*
7184 		 * We handle reassembly two ways.  In the easy case,
7185 		 * where all the fragments show up in order, we do
7186 		 * minimal bookkeeping, and just clip new pieces on
7187 		 * the end.  If we ever see a hole, then we go off
7188 		 * to ip_reassemble which has to mark the pieces and
7189 		 * keep track of the number of holes, etc.  Obviously,
7190 		 * the point of having both mechanisms is so we can
7191 		 * handle the easy case as efficiently as possible.
7192 		 */
7193 		if (offset == 0) {
7194 			/* Easy case, in-order reassembly so far. */
7195 			ipf->ipf_count += msg_len;
7196 			ipf->ipf_tail_mp = tail_mp;
7197 			/*
7198 			 * Keep track of next expected offset in
7199 			 * ipf_end.
7200 			 */
7201 			ipf->ipf_end = end;
7202 			ipf->ipf_nf_hdr_len = hdr_length;
7203 		} else {
7204 			/* Hard case, hole at the beginning. */
7205 			ipf->ipf_tail_mp = NULL;
7206 			/*
7207 			 * ipf_end == 0 means that we have given up
7208 			 * on easy reassembly.
7209 			 */
7210 			ipf->ipf_end = 0;
7211 
7212 			/* Forget checksum offload from now on */
7213 			ipf->ipf_checksum_flags = 0;
7214 
7215 			/*
7216 			 * ipf_hole_cnt is set by ip_reassemble.
7217 			 * ipf_count is updated by ip_reassemble.
7218 			 * No need to check for return value here
7219 			 * as we don't expect reassembly to complete
7220 			 * or fail for the first fragment itself.
7221 			 */
7222 			(void) ip_reassemble(mp, ipf,
7223 			    (frag_offset_flags & IPH_OFFSET) << 3,
7224 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7225 		}
7226 		/* Update per ipfb and ill byte counts */
7227 		ipfb->ipfb_count += ipf->ipf_count;
7228 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7229 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7230 		/* If the frag timer wasn't already going, start it. */
7231 		mutex_enter(&ill->ill_lock);
7232 		ill_frag_timer_start(ill);
7233 		mutex_exit(&ill->ill_lock);
7234 		goto reass_done;
7235 	}
7236 
7237 	/*
7238 	 * If the packet's flag has changed (it could be coming up
7239 	 * from an interface different than the previous, therefore
7240 	 * possibly different checksum capability), then forget about
7241 	 * any stored checksum states.  Otherwise add the value to
7242 	 * the existing one stored in the fragment header.
7243 	 */
7244 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7245 		sum_val += ipf->ipf_checksum;
7246 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7247 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7248 		ipf->ipf_checksum = sum_val;
7249 	} else if (ipf->ipf_checksum_flags != 0) {
7250 		/* Forget checksum offload from now on */
7251 		ipf->ipf_checksum_flags = 0;
7252 	}
7253 
7254 	/*
7255 	 * We have a new piece of a datagram which is already being
7256 	 * reassembled.  Update the ECN info if all IP fragments
7257 	 * are ECN capable.  If there is one which is not, clear
7258 	 * all the info.  If there is at least one which has CE
7259 	 * code point, IP needs to report that up to transport.
7260 	 */
7261 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7262 		if (ecn_info == IPH_ECN_CE)
7263 			ipf->ipf_ecn = IPH_ECN_CE;
7264 	} else {
7265 		ipf->ipf_ecn = IPH_ECN_NECT;
7266 	}
7267 	if (offset && ipf->ipf_end == offset) {
7268 		/* The new fragment fits at the end */
7269 		ipf->ipf_tail_mp->b_cont = mp;
7270 		/* Update the byte count */
7271 		ipf->ipf_count += msg_len;
7272 		/* Update per ipfb and ill byte counts */
7273 		ipfb->ipfb_count += msg_len;
7274 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7275 		atomic_add_32(&ill->ill_frag_count, msg_len);
7276 		if (frag_offset_flags & IPH_MF) {
7277 			/* More to come. */
7278 			ipf->ipf_end = end;
7279 			ipf->ipf_tail_mp = tail_mp;
7280 			goto reass_done;
7281 		}
7282 	} else {
7283 		/* Go do the hard cases. */
7284 		int ret;
7285 
7286 		if (offset == 0)
7287 			ipf->ipf_nf_hdr_len = hdr_length;
7288 
7289 		/* Save current byte count */
7290 		count = ipf->ipf_count;
7291 		ret = ip_reassemble(mp, ipf,
7292 		    (frag_offset_flags & IPH_OFFSET) << 3,
7293 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7294 		/* Count of bytes added and subtracted (freeb()ed) */
7295 		count = ipf->ipf_count - count;
7296 		if (count) {
7297 			/* Update per ipfb and ill byte counts */
7298 			ipfb->ipfb_count += count;
7299 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7300 			atomic_add_32(&ill->ill_frag_count, count);
7301 		}
7302 		if (ret == IP_REASS_PARTIAL) {
7303 			goto reass_done;
7304 		} else if (ret == IP_REASS_FAILED) {
7305 			/* Reassembly failed. Free up all resources */
7306 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7307 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7308 				IP_REASS_SET_START(t_mp, 0);
7309 				IP_REASS_SET_END(t_mp, 0);
7310 			}
7311 			freemsg(mp);
7312 			goto reass_done;
7313 		}
7314 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7315 	}
7316 	/*
7317 	 * We have completed reassembly.  Unhook the frag header from
7318 	 * the reassembly list.
7319 	 *
7320 	 * Before we free the frag header, record the ECN info
7321 	 * to report back to the transport.
7322 	 */
7323 	ecn_info = ipf->ipf_ecn;
7324 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7325 	ipfp = ipf->ipf_ptphn;
7326 
7327 	/* We need to supply these to caller */
7328 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7329 		sum_val = ipf->ipf_checksum;
7330 	else
7331 		sum_val = 0;
7332 
7333 	mp1 = ipf->ipf_mp;
7334 	count = ipf->ipf_count;
7335 	ipf = ipf->ipf_hash_next;
7336 	if (ipf != NULL)
7337 		ipf->ipf_ptphn = ipfp;
7338 	ipfp[0] = ipf;
7339 	atomic_add_32(&ill->ill_frag_count, -count);
7340 	ASSERT(ipfb->ipfb_count >= count);
7341 	ipfb->ipfb_count -= count;
7342 	ipfb->ipfb_frag_pkts--;
7343 	mutex_exit(&ipfb->ipfb_lock);
7344 	/* Ditch the frag header. */
7345 	mp = mp1->b_cont;
7346 
7347 	freeb(mp1);
7348 
7349 	/* Restore original IP length in header. */
7350 	packet_size = (uint32_t)msgdsize(mp);
7351 	if (packet_size > IP_MAXPACKET) {
7352 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7353 		ip_drop_input("Reassembled packet too large", mp, ill);
7354 		freemsg(mp);
7355 		return (NULL);
7356 	}
7357 
7358 	if (DB_REF(mp) > 1) {
7359 		mblk_t *mp2 = copymsg(mp);
7360 
7361 		if (mp2 == NULL) {
7362 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7363 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7364 			freemsg(mp);
7365 			return (NULL);
7366 		}
7367 		freemsg(mp);
7368 		mp = mp2;
7369 	}
7370 	ipha = (ipha_t *)mp->b_rptr;
7371 
7372 	ipha->ipha_length = htons((uint16_t)packet_size);
7373 	/* We're now complete, zip the frag state */
7374 	ipha->ipha_fragment_offset_and_flags = 0;
7375 	/* Record the ECN info. */
7376 	ipha->ipha_type_of_service &= 0xFC;
7377 	ipha->ipha_type_of_service |= ecn_info;
7378 
7379 	/* Update the receive attributes */
7380 	ira->ira_pktlen = packet_size;
7381 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7382 
7383 	/* Reassembly is successful; set checksum information in packet */
7384 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7385 	DB_CKSUMFLAGS(mp) = sum_flags;
7386 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7387 
7388 	return (mp);
7389 }
7390 
7391 /*
7392  * Pullup function that should be used for IP input in order to
7393  * ensure we do not loose the L2 source address; we need the l2 source
7394  * address for IP_RECVSLLA and for ndp_input.
7395  *
7396  * We return either NULL or b_rptr.
7397  */
7398 void *
7399 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7400 {
7401 	ill_t		*ill = ira->ira_ill;
7402 
7403 	if (ip_rput_pullups++ == 0) {
7404 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7405 		    "ip_pullup: %s forced us to "
7406 		    " pullup pkt, hdr len %ld, hdr addr %p",
7407 		    ill->ill_name, len, (void *)mp->b_rptr);
7408 	}
7409 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7410 		ip_setl2src(mp, ira, ira->ira_rill);
7411 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7412 	if (!pullupmsg(mp, len))
7413 		return (NULL);
7414 	else
7415 		return (mp->b_rptr);
7416 }
7417 
7418 /*
7419  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7420  * When called from the ULP ira_rill will be NULL hence the caller has to
7421  * pass in the ill.
7422  */
7423 /* ARGSUSED */
7424 void
7425 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7426 {
7427 	const uchar_t *addr;
7428 	int alen;
7429 
7430 	if (ira->ira_flags & IRAF_L2SRC_SET)
7431 		return;
7432 
7433 	ASSERT(ill != NULL);
7434 	alen = ill->ill_phys_addr_length;
7435 	ASSERT(alen <= sizeof (ira->ira_l2src));
7436 	if (ira->ira_mhip != NULL &&
7437 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7438 		bcopy(addr, ira->ira_l2src, alen);
7439 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7440 	    (addr = ill->ill_phys_addr) != NULL) {
7441 		bcopy(addr, ira->ira_l2src, alen);
7442 	} else {
7443 		bzero(ira->ira_l2src, alen);
7444 	}
7445 	ira->ira_flags |= IRAF_L2SRC_SET;
7446 }
7447 
7448 /*
7449  * check ip header length and align it.
7450  */
7451 mblk_t *
7452 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7453 {
7454 	ill_t	*ill = ira->ira_ill;
7455 	ssize_t len;
7456 
7457 	len = MBLKL(mp);
7458 
7459 	if (!OK_32PTR(mp->b_rptr))
7460 		IP_STAT(ill->ill_ipst, ip_notaligned);
7461 	else
7462 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7463 
7464 	/* Guard against bogus device drivers */
7465 	if (len < 0) {
7466 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7467 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7468 		freemsg(mp);
7469 		return (NULL);
7470 	}
7471 
7472 	if (len == 0) {
7473 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7474 		mblk_t *mp1 = mp->b_cont;
7475 
7476 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7477 			ip_setl2src(mp, ira, ira->ira_rill);
7478 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7479 
7480 		freeb(mp);
7481 		mp = mp1;
7482 		if (mp == NULL)
7483 			return (NULL);
7484 
7485 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7486 			return (mp);
7487 	}
7488 	if (ip_pullup(mp, min_size, ira) == NULL) {
7489 		if (msgdsize(mp) < min_size) {
7490 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7491 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7492 		} else {
7493 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7494 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7495 		}
7496 		freemsg(mp);
7497 		return (NULL);
7498 	}
7499 	return (mp);
7500 }
7501 
7502 /*
7503  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7504  */
7505 mblk_t *
7506 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7507     uint_t min_size, ip_recv_attr_t *ira)
7508 {
7509 	ill_t	*ill = ira->ira_ill;
7510 
7511 	/*
7512 	 * Make sure we have data length consistent
7513 	 * with the IP header.
7514 	 */
7515 	if (mp->b_cont == NULL) {
7516 		/* pkt_len is based on ipha_len, not the mblk length */
7517 		if (pkt_len < min_size) {
7518 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7519 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7520 			freemsg(mp);
7521 			return (NULL);
7522 		}
7523 		if (len < 0) {
7524 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7525 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7526 			freemsg(mp);
7527 			return (NULL);
7528 		}
7529 		/* Drop any pad */
7530 		mp->b_wptr = rptr + pkt_len;
7531 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7532 		ASSERT(pkt_len >= min_size);
7533 		if (pkt_len < min_size) {
7534 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7535 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7536 			freemsg(mp);
7537 			return (NULL);
7538 		}
7539 		if (len < 0) {
7540 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7541 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7542 			freemsg(mp);
7543 			return (NULL);
7544 		}
7545 		/* Drop any pad */
7546 		(void) adjmsg(mp, -len);
7547 		/*
7548 		 * adjmsg may have freed an mblk from the chain, hence
7549 		 * invalidate any hw checksum here. This will force IP to
7550 		 * calculate the checksum in sw, but only for this packet.
7551 		 */
7552 		DB_CKSUMFLAGS(mp) = 0;
7553 		IP_STAT(ill->ill_ipst, ip_multimblk);
7554 	}
7555 	return (mp);
7556 }
7557 
7558 /*
7559  * Check that the IPv4 opt_len is consistent with the packet and pullup
7560  * the options.
7561  */
7562 mblk_t *
7563 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7564     ip_recv_attr_t *ira)
7565 {
7566 	ill_t	*ill = ira->ira_ill;
7567 	ssize_t len;
7568 
7569 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7570 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7571 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7572 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7573 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7574 		freemsg(mp);
7575 		return (NULL);
7576 	}
7577 
7578 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7579 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7580 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7581 		freemsg(mp);
7582 		return (NULL);
7583 	}
7584 	/*
7585 	 * Recompute complete header length and make sure we
7586 	 * have access to all of it.
7587 	 */
7588 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7589 	if (len > (mp->b_wptr - mp->b_rptr)) {
7590 		if (len > pkt_len) {
7591 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7592 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7593 			freemsg(mp);
7594 			return (NULL);
7595 		}
7596 		if (ip_pullup(mp, len, ira) == NULL) {
7597 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7598 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7599 			freemsg(mp);
7600 			return (NULL);
7601 		}
7602 	}
7603 	return (mp);
7604 }
7605 
7606 /*
7607  * Returns a new ire, or the same ire, or NULL.
7608  * If a different IRE is returned, then it is held; the caller
7609  * needs to release it.
7610  * In no case is there any hold/release on the ire argument.
7611  */
7612 ire_t *
7613 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7614 {
7615 	ire_t		*new_ire;
7616 	ill_t		*ire_ill;
7617 	uint_t		ifindex;
7618 	ip_stack_t	*ipst = ill->ill_ipst;
7619 	boolean_t	strict_check = B_FALSE;
7620 
7621 	/*
7622 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7623 	 * issue (e.g. packet received on an underlying interface matched an
7624 	 * IRE_LOCAL on its associated group interface).
7625 	 */
7626 	ASSERT(ire->ire_ill != NULL);
7627 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7628 		return (ire);
7629 
7630 	/*
7631 	 * Do another ire lookup here, using the ingress ill, to see if the
7632 	 * interface is in a usesrc group.
7633 	 * As long as the ills belong to the same group, we don't consider
7634 	 * them to be arriving on the wrong interface. Thus, if the switch
7635 	 * is doing inbound load spreading, we won't drop packets when the
7636 	 * ip*_strict_dst_multihoming switch is on.
7637 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7638 	 * where the local address may not be unique. In this case we were
7639 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7640 	 * actually returned. The new lookup, which is more specific, should
7641 	 * only find the IRE_LOCAL associated with the ingress ill if one
7642 	 * exists.
7643 	 */
7644 	if (ire->ire_ipversion == IPV4_VERSION) {
7645 		if (ipst->ips_ip_strict_dst_multihoming)
7646 			strict_check = B_TRUE;
7647 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7648 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7649 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7650 	} else {
7651 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7652 		if (ipst->ips_ipv6_strict_dst_multihoming)
7653 			strict_check = B_TRUE;
7654 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7655 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7656 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7657 	}
7658 	/*
7659 	 * If the same ire that was returned in ip_input() is found then this
7660 	 * is an indication that usesrc groups are in use. The packet
7661 	 * arrived on a different ill in the group than the one associated with
7662 	 * the destination address.  If a different ire was found then the same
7663 	 * IP address must be hosted on multiple ills. This is possible with
7664 	 * unnumbered point2point interfaces. We switch to use this new ire in
7665 	 * order to have accurate interface statistics.
7666 	 */
7667 	if (new_ire != NULL) {
7668 		/* Note: held in one case but not the other? Caller handles */
7669 		if (new_ire != ire)
7670 			return (new_ire);
7671 		/* Unchanged */
7672 		ire_refrele(new_ire);
7673 		return (ire);
7674 	}
7675 
7676 	/*
7677 	 * Chase pointers once and store locally.
7678 	 */
7679 	ASSERT(ire->ire_ill != NULL);
7680 	ire_ill = ire->ire_ill;
7681 	ifindex = ill->ill_usesrc_ifindex;
7682 
7683 	/*
7684 	 * Check if it's a legal address on the 'usesrc' interface.
7685 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7686 	 * can just check phyint_ifindex.
7687 	 */
7688 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7689 		return (ire);
7690 	}
7691 
7692 	/*
7693 	 * If the ip*_strict_dst_multihoming switch is on then we can
7694 	 * only accept this packet if the interface is marked as routing.
7695 	 */
7696 	if (!(strict_check))
7697 		return (ire);
7698 
7699 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7700 		return (ire);
7701 	}
7702 	return (NULL);
7703 }
7704 
7705 /*
7706  * This function is used to construct a mac_header_info_s from a
7707  * DL_UNITDATA_IND message.
7708  * The address fields in the mhi structure points into the message,
7709  * thus the caller can't use those fields after freeing the message.
7710  *
7711  * We determine whether the packet received is a non-unicast packet
7712  * and in doing so, determine whether or not it is broadcast vs multicast.
7713  * For it to be a broadcast packet, we must have the appropriate mblk_t
7714  * hanging off the ill_t.  If this is either not present or doesn't match
7715  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7716  * to be multicast.  Thus NICs that have no broadcast address (or no
7717  * capability for one, such as point to point links) cannot return as
7718  * the packet being broadcast.
7719  */
7720 void
7721 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7722 {
7723 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7724 	mblk_t *bmp;
7725 	uint_t extra_offset;
7726 
7727 	bzero(mhip, sizeof (struct mac_header_info_s));
7728 
7729 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7730 
7731 	if (ill->ill_sap_length < 0)
7732 		extra_offset = 0;
7733 	else
7734 		extra_offset = ill->ill_sap_length;
7735 
7736 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7737 	    extra_offset;
7738 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7739 	    extra_offset;
7740 
7741 	if (!ind->dl_group_address)
7742 		return;
7743 
7744 	/* Multicast or broadcast */
7745 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7746 
7747 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7748 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7749 	    (bmp = ill->ill_bcast_mp) != NULL) {
7750 		dl_unitdata_req_t *dlur;
7751 		uint8_t *bphys_addr;
7752 
7753 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7754 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7755 		    extra_offset;
7756 
7757 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7758 		    ind->dl_dest_addr_length) == 0)
7759 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7760 	}
7761 }
7762 
7763 /*
7764  * This function is used to construct a mac_header_info_s from a
7765  * M_DATA fastpath message from a DLPI driver.
7766  * The address fields in the mhi structure points into the message,
7767  * thus the caller can't use those fields after freeing the message.
7768  *
7769  * We determine whether the packet received is a non-unicast packet
7770  * and in doing so, determine whether or not it is broadcast vs multicast.
7771  * For it to be a broadcast packet, we must have the appropriate mblk_t
7772  * hanging off the ill_t.  If this is either not present or doesn't match
7773  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7774  * to be multicast.  Thus NICs that have no broadcast address (or no
7775  * capability for one, such as point to point links) cannot return as
7776  * the packet being broadcast.
7777  */
7778 void
7779 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7780 {
7781 	mblk_t *bmp;
7782 	struct ether_header *pether;
7783 
7784 	bzero(mhip, sizeof (struct mac_header_info_s));
7785 
7786 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7787 
7788 	pether = (struct ether_header *)((char *)mp->b_rptr
7789 	    - sizeof (struct ether_header));
7790 
7791 	/*
7792 	 * Make sure the interface is an ethernet type, since we don't
7793 	 * know the header format for anything but Ethernet. Also make
7794 	 * sure we are pointing correctly above db_base.
7795 	 */
7796 	if (ill->ill_type != IFT_ETHER)
7797 		return;
7798 
7799 retry:
7800 	if ((uchar_t *)pether < mp->b_datap->db_base)
7801 		return;
7802 
7803 	/* Is there a VLAN tag? */
7804 	if (ill->ill_isv6) {
7805 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7806 			pether = (struct ether_header *)((char *)pether - 4);
7807 			goto retry;
7808 		}
7809 	} else {
7810 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7811 			pether = (struct ether_header *)((char *)pether - 4);
7812 			goto retry;
7813 		}
7814 	}
7815 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7816 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7817 
7818 	if (!(mhip->mhi_daddr[0] & 0x01))
7819 		return;
7820 
7821 	/* Multicast or broadcast */
7822 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7823 
7824 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7825 		dl_unitdata_req_t *dlur;
7826 		uint8_t *bphys_addr;
7827 		uint_t	addrlen;
7828 
7829 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7830 		addrlen = dlur->dl_dest_addr_length;
7831 		if (ill->ill_sap_length < 0) {
7832 			bphys_addr = (uchar_t *)dlur +
7833 			    dlur->dl_dest_addr_offset;
7834 			addrlen += ill->ill_sap_length;
7835 		} else {
7836 			bphys_addr = (uchar_t *)dlur +
7837 			    dlur->dl_dest_addr_offset +
7838 			    ill->ill_sap_length;
7839 			addrlen -= ill->ill_sap_length;
7840 		}
7841 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7842 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7843 	}
7844 }
7845 
7846 /*
7847  * Handle anything but M_DATA messages
7848  * We see the DL_UNITDATA_IND which are part
7849  * of the data path, and also the other messages from the driver.
7850  */
7851 void
7852 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7853 {
7854 	mblk_t		*first_mp;
7855 	struct iocblk   *iocp;
7856 	struct mac_header_info_s mhi;
7857 
7858 	switch (DB_TYPE(mp)) {
7859 	case M_PROTO:
7860 	case M_PCPROTO: {
7861 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7862 		    DL_UNITDATA_IND) {
7863 			/* Go handle anything other than data elsewhere. */
7864 			ip_rput_dlpi(ill, mp);
7865 			return;
7866 		}
7867 
7868 		first_mp = mp;
7869 		mp = first_mp->b_cont;
7870 		first_mp->b_cont = NULL;
7871 
7872 		if (mp == NULL) {
7873 			freeb(first_mp);
7874 			return;
7875 		}
7876 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7877 		if (ill->ill_isv6)
7878 			ip_input_v6(ill, NULL, mp, &mhi);
7879 		else
7880 			ip_input(ill, NULL, mp, &mhi);
7881 
7882 		/* Ditch the DLPI header. */
7883 		freeb(first_mp);
7884 		return;
7885 	}
7886 	case M_IOCACK:
7887 		iocp = (struct iocblk *)mp->b_rptr;
7888 		switch (iocp->ioc_cmd) {
7889 		case DL_IOC_HDR_INFO:
7890 			ill_fastpath_ack(ill, mp);
7891 			return;
7892 		default:
7893 			putnext(ill->ill_rq, mp);
7894 			return;
7895 		}
7896 		/* FALLTHRU */
7897 	case M_ERROR:
7898 	case M_HANGUP:
7899 		mutex_enter(&ill->ill_lock);
7900 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7901 			mutex_exit(&ill->ill_lock);
7902 			freemsg(mp);
7903 			return;
7904 		}
7905 		ill_refhold_locked(ill);
7906 		mutex_exit(&ill->ill_lock);
7907 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7908 		    B_FALSE);
7909 		return;
7910 	case M_CTL:
7911 		putnext(ill->ill_rq, mp);
7912 		return;
7913 	case M_IOCNAK:
7914 		ip1dbg(("got iocnak "));
7915 		iocp = (struct iocblk *)mp->b_rptr;
7916 		switch (iocp->ioc_cmd) {
7917 		case DL_IOC_HDR_INFO:
7918 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7919 			return;
7920 		default:
7921 			break;
7922 		}
7923 		/* FALLTHRU */
7924 	default:
7925 		putnext(ill->ill_rq, mp);
7926 		return;
7927 	}
7928 }
7929 
7930 /* Read side put procedure.  Packets coming from the wire arrive here. */
7931 void
7932 ip_rput(queue_t *q, mblk_t *mp)
7933 {
7934 	ill_t	*ill;
7935 	union DL_primitives *dl;
7936 
7937 	ill = (ill_t *)q->q_ptr;
7938 
7939 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
7940 		/*
7941 		 * If things are opening or closing, only accept high-priority
7942 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
7943 		 * created; on close, things hanging off the ill may have been
7944 		 * freed already.)
7945 		 */
7946 		dl = (union DL_primitives *)mp->b_rptr;
7947 		if (DB_TYPE(mp) != M_PCPROTO ||
7948 		    dl->dl_primitive == DL_UNITDATA_IND) {
7949 			inet_freemsg(mp);
7950 			return;
7951 		}
7952 	}
7953 	if (DB_TYPE(mp) == M_DATA) {
7954 		struct mac_header_info_s mhi;
7955 
7956 		ip_mdata_to_mhi(ill, mp, &mhi);
7957 		ip_input(ill, NULL, mp, &mhi);
7958 	} else {
7959 		ip_rput_notdata(ill, mp);
7960 	}
7961 }
7962 
7963 /*
7964  * Move the information to a copy.
7965  */
7966 mblk_t *
7967 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
7968 {
7969 	mblk_t		*mp1;
7970 	ill_t		*ill = ira->ira_ill;
7971 	ip_stack_t	*ipst = ill->ill_ipst;
7972 
7973 	IP_STAT(ipst, ip_db_ref);
7974 
7975 	/* Make sure we have ira_l2src before we loose the original mblk */
7976 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7977 		ip_setl2src(mp, ira, ira->ira_rill);
7978 
7979 	mp1 = copymsg(mp);
7980 	if (mp1 == NULL) {
7981 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7982 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
7983 		freemsg(mp);
7984 		return (NULL);
7985 	}
7986 	/* preserve the hardware checksum flags and data, if present */
7987 	if (DB_CKSUMFLAGS(mp) != 0) {
7988 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
7989 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
7990 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
7991 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
7992 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
7993 	}
7994 	freemsg(mp);
7995 	return (mp1);
7996 }
7997 
7998 static void
7999 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8000     t_uscalar_t err)
8001 {
8002 	if (dl_err == DL_SYSERR) {
8003 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8004 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8005 		    ill->ill_name, dl_primstr(prim), err);
8006 		return;
8007 	}
8008 
8009 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8010 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8011 	    dl_errstr(dl_err));
8012 }
8013 
8014 /*
8015  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8016  * than DL_UNITDATA_IND messages. If we need to process this message
8017  * exclusively, we call qwriter_ip, in which case we also need to call
8018  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8019  */
8020 void
8021 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8022 {
8023 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8024 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8025 	queue_t		*q = ill->ill_rq;
8026 	t_uscalar_t	prim = dloa->dl_primitive;
8027 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8028 
8029 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8030 	    char *, dl_primstr(prim), ill_t *, ill);
8031 	ip1dbg(("ip_rput_dlpi"));
8032 
8033 	/*
8034 	 * If we received an ACK but didn't send a request for it, then it
8035 	 * can't be part of any pending operation; discard up-front.
8036 	 */
8037 	switch (prim) {
8038 	case DL_ERROR_ACK:
8039 		reqprim = dlea->dl_error_primitive;
8040 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8041 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8042 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8043 		    dlea->dl_unix_errno));
8044 		break;
8045 	case DL_OK_ACK:
8046 		reqprim = dloa->dl_correct_primitive;
8047 		break;
8048 	case DL_INFO_ACK:
8049 		reqprim = DL_INFO_REQ;
8050 		break;
8051 	case DL_BIND_ACK:
8052 		reqprim = DL_BIND_REQ;
8053 		break;
8054 	case DL_PHYS_ADDR_ACK:
8055 		reqprim = DL_PHYS_ADDR_REQ;
8056 		break;
8057 	case DL_NOTIFY_ACK:
8058 		reqprim = DL_NOTIFY_REQ;
8059 		break;
8060 	case DL_CAPABILITY_ACK:
8061 		reqprim = DL_CAPABILITY_REQ;
8062 		break;
8063 	}
8064 
8065 	if (prim != DL_NOTIFY_IND) {
8066 		if (reqprim == DL_PRIM_INVAL ||
8067 		    !ill_dlpi_pending(ill, reqprim)) {
8068 			/* Not a DLPI message we support or expected */
8069 			freemsg(mp);
8070 			return;
8071 		}
8072 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8073 		    dl_primstr(reqprim)));
8074 	}
8075 
8076 	switch (reqprim) {
8077 	case DL_UNBIND_REQ:
8078 		/*
8079 		 * NOTE: we mark the unbind as complete even if we got a
8080 		 * DL_ERROR_ACK, since there's not much else we can do.
8081 		 */
8082 		mutex_enter(&ill->ill_lock);
8083 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8084 		cv_signal(&ill->ill_cv);
8085 		mutex_exit(&ill->ill_lock);
8086 		break;
8087 
8088 	case DL_ENABMULTI_REQ:
8089 		if (prim == DL_OK_ACK) {
8090 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8091 				ill->ill_dlpi_multicast_state = IDS_OK;
8092 		}
8093 		break;
8094 	}
8095 
8096 	/*
8097 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8098 	 * need to become writer to continue to process it.  Because an
8099 	 * exclusive operation doesn't complete until replies to all queued
8100 	 * DLPI messages have been received, we know we're in the middle of an
8101 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8102 	 *
8103 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8104 	 * Since this is on the ill stream we unconditionally bump up the
8105 	 * refcount without doing ILL_CAN_LOOKUP().
8106 	 */
8107 	ill_refhold(ill);
8108 	if (prim == DL_NOTIFY_IND)
8109 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8110 	else
8111 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8112 }
8113 
8114 /*
8115  * Handling of DLPI messages that require exclusive access to the ipsq.
8116  *
8117  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8118  * happen here. (along with mi_copy_done)
8119  */
8120 /* ARGSUSED */
8121 static void
8122 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8123 {
8124 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8125 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8126 	int		err = 0;
8127 	ill_t		*ill = (ill_t *)q->q_ptr;
8128 	ipif_t		*ipif = NULL;
8129 	mblk_t		*mp1 = NULL;
8130 	conn_t		*connp = NULL;
8131 	t_uscalar_t	paddrreq;
8132 	mblk_t		*mp_hw;
8133 	boolean_t	success;
8134 	boolean_t	ioctl_aborted = B_FALSE;
8135 	boolean_t	log = B_TRUE;
8136 
8137 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8138 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8139 
8140 	ip1dbg(("ip_rput_dlpi_writer .."));
8141 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8142 	ASSERT(IAM_WRITER_ILL(ill));
8143 
8144 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8145 	/*
8146 	 * The current ioctl could have been aborted by the user and a new
8147 	 * ioctl to bring up another ill could have started. We could still
8148 	 * get a response from the driver later.
8149 	 */
8150 	if (ipif != NULL && ipif->ipif_ill != ill)
8151 		ioctl_aborted = B_TRUE;
8152 
8153 	switch (dloa->dl_primitive) {
8154 	case DL_ERROR_ACK:
8155 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8156 		    dl_primstr(dlea->dl_error_primitive)));
8157 
8158 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8159 		    char *, dl_primstr(dlea->dl_error_primitive),
8160 		    ill_t *, ill);
8161 
8162 		switch (dlea->dl_error_primitive) {
8163 		case DL_DISABMULTI_REQ:
8164 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8165 			break;
8166 		case DL_PROMISCON_REQ:
8167 		case DL_PROMISCOFF_REQ:
8168 		case DL_UNBIND_REQ:
8169 		case DL_ATTACH_REQ:
8170 		case DL_INFO_REQ:
8171 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8172 			break;
8173 		case DL_NOTIFY_REQ:
8174 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8175 			log = B_FALSE;
8176 			break;
8177 		case DL_PHYS_ADDR_REQ:
8178 			/*
8179 			 * For IPv6 only, there are two additional
8180 			 * phys_addr_req's sent to the driver to get the
8181 			 * IPv6 token and lla. This allows IP to acquire
8182 			 * the hardware address format for a given interface
8183 			 * without having built in knowledge of the hardware
8184 			 * address. ill_phys_addr_pend keeps track of the last
8185 			 * DL_PAR sent so we know which response we are
8186 			 * dealing with. ill_dlpi_done will update
8187 			 * ill_phys_addr_pend when it sends the next req.
8188 			 * We don't complete the IOCTL until all three DL_PARs
8189 			 * have been attempted, so set *_len to 0 and break.
8190 			 */
8191 			paddrreq = ill->ill_phys_addr_pend;
8192 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8193 			if (paddrreq == DL_IPV6_TOKEN) {
8194 				ill->ill_token_length = 0;
8195 				log = B_FALSE;
8196 				break;
8197 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8198 				ill->ill_nd_lla_len = 0;
8199 				log = B_FALSE;
8200 				break;
8201 			}
8202 			/*
8203 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8204 			 * We presumably have an IOCTL hanging out waiting
8205 			 * for completion. Find it and complete the IOCTL
8206 			 * with the error noted.
8207 			 * However, ill_dl_phys was called on an ill queue
8208 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8209 			 * set. But the ioctl is known to be pending on ill_wq.
8210 			 */
8211 			if (!ill->ill_ifname_pending)
8212 				break;
8213 			ill->ill_ifname_pending = 0;
8214 			if (!ioctl_aborted)
8215 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8216 			if (mp1 != NULL) {
8217 				/*
8218 				 * This operation (SIOCSLIFNAME) must have
8219 				 * happened on the ill. Assert there is no conn
8220 				 */
8221 				ASSERT(connp == NULL);
8222 				q = ill->ill_wq;
8223 			}
8224 			break;
8225 		case DL_BIND_REQ:
8226 			ill_dlpi_done(ill, DL_BIND_REQ);
8227 			if (ill->ill_ifname_pending)
8228 				break;
8229 			mutex_enter(&ill->ill_lock);
8230 			ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8231 			mutex_exit(&ill->ill_lock);
8232 			/*
8233 			 * Something went wrong with the bind.  We presumably
8234 			 * have an IOCTL hanging out waiting for completion.
8235 			 * Find it, take down the interface that was coming
8236 			 * up, and complete the IOCTL with the error noted.
8237 			 */
8238 			if (!ioctl_aborted)
8239 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8240 			if (mp1 != NULL) {
8241 				/*
8242 				 * This might be a result of a DL_NOTE_REPLUMB
8243 				 * notification. In that case, connp is NULL.
8244 				 */
8245 				if (connp != NULL)
8246 					q = CONNP_TO_WQ(connp);
8247 
8248 				(void) ipif_down(ipif, NULL, NULL);
8249 				/* error is set below the switch */
8250 			}
8251 			break;
8252 		case DL_ENABMULTI_REQ:
8253 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8254 
8255 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8256 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8257 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8258 
8259 				printf("ip: joining multicasts failed (%d)"
8260 				    " on %s - will use link layer "
8261 				    "broadcasts for multicast\n",
8262 				    dlea->dl_errno, ill->ill_name);
8263 
8264 				/*
8265 				 * Set up for multi_bcast; We are the
8266 				 * writer, so ok to access ill->ill_ipif
8267 				 * without any lock.
8268 				 */
8269 				mutex_enter(&ill->ill_phyint->phyint_lock);
8270 				ill->ill_phyint->phyint_flags |=
8271 				    PHYI_MULTI_BCAST;
8272 				mutex_exit(&ill->ill_phyint->phyint_lock);
8273 
8274 			}
8275 			freemsg(mp);	/* Don't want to pass this up */
8276 			return;
8277 		case DL_CAPABILITY_REQ:
8278 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8279 			    "DL_CAPABILITY REQ\n"));
8280 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8281 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8282 			ill_capability_done(ill);
8283 			freemsg(mp);
8284 			return;
8285 		}
8286 		/*
8287 		 * Note the error for IOCTL completion (mp1 is set when
8288 		 * ready to complete ioctl). If ill_ifname_pending_err is
8289 		 * set, an error occured during plumbing (ill_ifname_pending),
8290 		 * so we want to report that error.
8291 		 *
8292 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8293 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8294 		 * expected to get errack'd if the driver doesn't support
8295 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8296 		 * if these error conditions are encountered.
8297 		 */
8298 		if (mp1 != NULL) {
8299 			if (ill->ill_ifname_pending_err != 0)  {
8300 				err = ill->ill_ifname_pending_err;
8301 				ill->ill_ifname_pending_err = 0;
8302 			} else {
8303 				err = dlea->dl_unix_errno ?
8304 				    dlea->dl_unix_errno : ENXIO;
8305 			}
8306 		/*
8307 		 * If we're plumbing an interface and an error hasn't already
8308 		 * been saved, set ill_ifname_pending_err to the error passed
8309 		 * up. Ignore the error if log is B_FALSE (see comment above).
8310 		 */
8311 		} else if (log && ill->ill_ifname_pending &&
8312 		    ill->ill_ifname_pending_err == 0) {
8313 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8314 			    dlea->dl_unix_errno : ENXIO;
8315 		}
8316 
8317 		if (log)
8318 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8319 			    dlea->dl_errno, dlea->dl_unix_errno);
8320 		break;
8321 	case DL_CAPABILITY_ACK:
8322 		ill_capability_ack(ill, mp);
8323 		/*
8324 		 * The message has been handed off to ill_capability_ack
8325 		 * and must not be freed below
8326 		 */
8327 		mp = NULL;
8328 		break;
8329 
8330 	case DL_INFO_ACK:
8331 		/* Call a routine to handle this one. */
8332 		ill_dlpi_done(ill, DL_INFO_REQ);
8333 		ip_ll_subnet_defaults(ill, mp);
8334 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8335 		return;
8336 	case DL_BIND_ACK:
8337 		/*
8338 		 * We should have an IOCTL waiting on this unless
8339 		 * sent by ill_dl_phys, in which case just return
8340 		 */
8341 		ill_dlpi_done(ill, DL_BIND_REQ);
8342 
8343 		if (ill->ill_ifname_pending) {
8344 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8345 			    ill_t *, ill, mblk_t *, mp);
8346 			break;
8347 		}
8348 		mutex_enter(&ill->ill_lock);
8349 		ill->ill_dl_up = 1;
8350 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8351 		mutex_exit(&ill->ill_lock);
8352 
8353 		if (!ioctl_aborted)
8354 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8355 		if (mp1 == NULL) {
8356 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8357 			break;
8358 		}
8359 		/*
8360 		 * mp1 was added by ill_dl_up(). if that is a result of
8361 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8362 		 */
8363 		if (connp != NULL)
8364 			q = CONNP_TO_WQ(connp);
8365 		/*
8366 		 * We are exclusive. So nothing can change even after
8367 		 * we get the pending mp.
8368 		 */
8369 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8370 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8371 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8372 
8373 		/*
8374 		 * Now bring up the resolver; when that is complete, we'll
8375 		 * create IREs.  Note that we intentionally mirror what
8376 		 * ipif_up() would have done, because we got here by way of
8377 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8378 		 */
8379 		if (ill->ill_isv6) {
8380 			/*
8381 			 * v6 interfaces.
8382 			 * Unlike ARP which has to do another bind
8383 			 * and attach, once we get here we are
8384 			 * done with NDP
8385 			 */
8386 			(void) ipif_resolver_up(ipif, Res_act_initial);
8387 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8388 				err = ipif_up_done_v6(ipif);
8389 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8390 			/*
8391 			 * ARP and other v4 external resolvers.
8392 			 * Leave the pending mblk intact so that
8393 			 * the ioctl completes in ip_rput().
8394 			 */
8395 			if (connp != NULL)
8396 				mutex_enter(&connp->conn_lock);
8397 			mutex_enter(&ill->ill_lock);
8398 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8399 			mutex_exit(&ill->ill_lock);
8400 			if (connp != NULL)
8401 				mutex_exit(&connp->conn_lock);
8402 			if (success) {
8403 				err = ipif_resolver_up(ipif, Res_act_initial);
8404 				if (err == EINPROGRESS) {
8405 					freemsg(mp);
8406 					return;
8407 				}
8408 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8409 			} else {
8410 				/* The conn has started closing */
8411 				err = EINTR;
8412 			}
8413 		} else {
8414 			/*
8415 			 * This one is complete. Reply to pending ioctl.
8416 			 */
8417 			(void) ipif_resolver_up(ipif, Res_act_initial);
8418 			err = ipif_up_done(ipif);
8419 		}
8420 
8421 		if ((err == 0) && (ill->ill_up_ipifs)) {
8422 			err = ill_up_ipifs(ill, q, mp1);
8423 			if (err == EINPROGRESS) {
8424 				freemsg(mp);
8425 				return;
8426 			}
8427 		}
8428 
8429 		/*
8430 		 * If we have a moved ipif to bring up, and everything has
8431 		 * succeeded to this point, bring it up on the IPMP ill.
8432 		 * Otherwise, leave it down -- the admin can try to bring it
8433 		 * up by hand if need be.
8434 		 */
8435 		if (ill->ill_move_ipif != NULL) {
8436 			if (err != 0) {
8437 				ill->ill_move_ipif = NULL;
8438 			} else {
8439 				ipif = ill->ill_move_ipif;
8440 				ill->ill_move_ipif = NULL;
8441 				err = ipif_up(ipif, q, mp1);
8442 				if (err == EINPROGRESS) {
8443 					freemsg(mp);
8444 					return;
8445 				}
8446 			}
8447 		}
8448 		break;
8449 
8450 	case DL_NOTIFY_IND: {
8451 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8452 		uint_t orig_mtu;
8453 
8454 		switch (notify->dl_notification) {
8455 		case DL_NOTE_PHYS_ADDR:
8456 			err = ill_set_phys_addr(ill, mp);
8457 			break;
8458 
8459 		case DL_NOTE_REPLUMB:
8460 			/*
8461 			 * Directly return after calling ill_replumb().
8462 			 * Note that we should not free mp as it is reused
8463 			 * in the ill_replumb() function.
8464 			 */
8465 			err = ill_replumb(ill, mp);
8466 			return;
8467 
8468 		case DL_NOTE_FASTPATH_FLUSH:
8469 			nce_flush(ill, B_FALSE);
8470 			break;
8471 
8472 		case DL_NOTE_SDU_SIZE:
8473 			/*
8474 			 * The dce and fragmentation code can cope with
8475 			 * this changing while packets are being sent.
8476 			 * When packets are sent ip_output will discover
8477 			 * a change.
8478 			 *
8479 			 * Change the MTU size of the interface.
8480 			 */
8481 			mutex_enter(&ill->ill_lock);
8482 			ill->ill_current_frag = (uint_t)notify->dl_data;
8483 			if (ill->ill_current_frag > ill->ill_max_frag)
8484 				ill->ill_max_frag = ill->ill_current_frag;
8485 
8486 			orig_mtu = ill->ill_mtu;
8487 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8488 				ill->ill_mtu = ill->ill_current_frag;
8489 
8490 				/*
8491 				 * If ill_user_mtu was set (via
8492 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8493 				 */
8494 				if (ill->ill_user_mtu != 0 &&
8495 				    ill->ill_user_mtu < ill->ill_mtu)
8496 					ill->ill_mtu = ill->ill_user_mtu;
8497 
8498 				if (ill->ill_isv6) {
8499 					if (ill->ill_mtu < IPV6_MIN_MTU)
8500 						ill->ill_mtu = IPV6_MIN_MTU;
8501 				} else {
8502 					if (ill->ill_mtu < IP_MIN_MTU)
8503 						ill->ill_mtu = IP_MIN_MTU;
8504 				}
8505 			}
8506 			mutex_exit(&ill->ill_lock);
8507 			/*
8508 			 * Make sure all dce_generation checks find out
8509 			 * that ill_mtu has changed.
8510 			 */
8511 			if (orig_mtu != ill->ill_mtu) {
8512 				dce_increment_all_generations(ill->ill_isv6,
8513 				    ill->ill_ipst);
8514 			}
8515 
8516 			/*
8517 			 * Refresh IPMP meta-interface MTU if necessary.
8518 			 */
8519 			if (IS_UNDER_IPMP(ill))
8520 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8521 			break;
8522 
8523 		case DL_NOTE_LINK_UP:
8524 		case DL_NOTE_LINK_DOWN: {
8525 			/*
8526 			 * We are writer. ill / phyint / ipsq assocs stable.
8527 			 * The RUNNING flag reflects the state of the link.
8528 			 */
8529 			phyint_t *phyint = ill->ill_phyint;
8530 			uint64_t new_phyint_flags;
8531 			boolean_t changed = B_FALSE;
8532 			boolean_t went_up;
8533 
8534 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8535 			mutex_enter(&phyint->phyint_lock);
8536 
8537 			new_phyint_flags = went_up ?
8538 			    phyint->phyint_flags | PHYI_RUNNING :
8539 			    phyint->phyint_flags & ~PHYI_RUNNING;
8540 
8541 			if (IS_IPMP(ill)) {
8542 				new_phyint_flags = went_up ?
8543 				    new_phyint_flags & ~PHYI_FAILED :
8544 				    new_phyint_flags | PHYI_FAILED;
8545 			}
8546 
8547 			if (new_phyint_flags != phyint->phyint_flags) {
8548 				phyint->phyint_flags = new_phyint_flags;
8549 				changed = B_TRUE;
8550 			}
8551 			mutex_exit(&phyint->phyint_lock);
8552 			/*
8553 			 * ill_restart_dad handles the DAD restart and routing
8554 			 * socket notification logic.
8555 			 */
8556 			if (changed) {
8557 				ill_restart_dad(phyint->phyint_illv4, went_up);
8558 				ill_restart_dad(phyint->phyint_illv6, went_up);
8559 			}
8560 			break;
8561 		}
8562 		case DL_NOTE_PROMISC_ON_PHYS: {
8563 			phyint_t *phyint = ill->ill_phyint;
8564 
8565 			mutex_enter(&phyint->phyint_lock);
8566 			phyint->phyint_flags |= PHYI_PROMISC;
8567 			mutex_exit(&phyint->phyint_lock);
8568 			break;
8569 		}
8570 		case DL_NOTE_PROMISC_OFF_PHYS: {
8571 			phyint_t *phyint = ill->ill_phyint;
8572 
8573 			mutex_enter(&phyint->phyint_lock);
8574 			phyint->phyint_flags &= ~PHYI_PROMISC;
8575 			mutex_exit(&phyint->phyint_lock);
8576 			break;
8577 		}
8578 		case DL_NOTE_CAPAB_RENEG:
8579 			/*
8580 			 * Something changed on the driver side.
8581 			 * It wants us to renegotiate the capabilities
8582 			 * on this ill. One possible cause is the aggregation
8583 			 * interface under us where a port got added or
8584 			 * went away.
8585 			 *
8586 			 * If the capability negotiation is already done
8587 			 * or is in progress, reset the capabilities and
8588 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8589 			 * so that when the ack comes back, we can start
8590 			 * the renegotiation process.
8591 			 *
8592 			 * Note that if ill_capab_reneg is already B_TRUE
8593 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8594 			 * the capability resetting request has been sent
8595 			 * and the renegotiation has not been started yet;
8596 			 * nothing needs to be done in this case.
8597 			 */
8598 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8599 			ill_capability_reset(ill, B_TRUE);
8600 			ipsq_current_finish(ipsq);
8601 			break;
8602 
8603 		case DL_NOTE_ALLOWED_IPS:
8604 			ill_set_allowed_ips(ill, mp);
8605 			break;
8606 		default:
8607 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8608 			    "type 0x%x for DL_NOTIFY_IND\n",
8609 			    notify->dl_notification));
8610 			break;
8611 		}
8612 
8613 		/*
8614 		 * As this is an asynchronous operation, we
8615 		 * should not call ill_dlpi_done
8616 		 */
8617 		break;
8618 	}
8619 	case DL_NOTIFY_ACK: {
8620 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8621 
8622 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8623 			ill->ill_note_link = 1;
8624 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8625 		break;
8626 	}
8627 	case DL_PHYS_ADDR_ACK: {
8628 		/*
8629 		 * As part of plumbing the interface via SIOCSLIFNAME,
8630 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8631 		 * whose answers we receive here.  As each answer is received,
8632 		 * we call ill_dlpi_done() to dispatch the next request as
8633 		 * we're processing the current one.  Once all answers have
8634 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8635 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8636 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8637 		 * available, but we know the ioctl is pending on ill_wq.)
8638 		 */
8639 		uint_t	paddrlen, paddroff;
8640 		uint8_t	*addr;
8641 
8642 		paddrreq = ill->ill_phys_addr_pend;
8643 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8644 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8645 		addr = mp->b_rptr + paddroff;
8646 
8647 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8648 		if (paddrreq == DL_IPV6_TOKEN) {
8649 			/*
8650 			 * bcopy to low-order bits of ill_token
8651 			 *
8652 			 * XXX Temporary hack - currently, all known tokens
8653 			 * are 64 bits, so I'll cheat for the moment.
8654 			 */
8655 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8656 			ill->ill_token_length = paddrlen;
8657 			break;
8658 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8659 			ASSERT(ill->ill_nd_lla_mp == NULL);
8660 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8661 			mp = NULL;
8662 			break;
8663 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8664 			ASSERT(ill->ill_dest_addr_mp == NULL);
8665 			ill->ill_dest_addr_mp = mp;
8666 			ill->ill_dest_addr = addr;
8667 			mp = NULL;
8668 			if (ill->ill_isv6) {
8669 				ill_setdesttoken(ill);
8670 				ipif_setdestlinklocal(ill->ill_ipif);
8671 			}
8672 			break;
8673 		}
8674 
8675 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8676 		ASSERT(ill->ill_phys_addr_mp == NULL);
8677 		if (!ill->ill_ifname_pending)
8678 			break;
8679 		ill->ill_ifname_pending = 0;
8680 		if (!ioctl_aborted)
8681 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8682 		if (mp1 != NULL) {
8683 			ASSERT(connp == NULL);
8684 			q = ill->ill_wq;
8685 		}
8686 		/*
8687 		 * If any error acks received during the plumbing sequence,
8688 		 * ill_ifname_pending_err will be set. Break out and send up
8689 		 * the error to the pending ioctl.
8690 		 */
8691 		if (ill->ill_ifname_pending_err != 0) {
8692 			err = ill->ill_ifname_pending_err;
8693 			ill->ill_ifname_pending_err = 0;
8694 			break;
8695 		}
8696 
8697 		ill->ill_phys_addr_mp = mp;
8698 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8699 		mp = NULL;
8700 
8701 		/*
8702 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8703 		 * provider doesn't support physical addresses.  We check both
8704 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8705 		 * not have physical addresses, but historically adversises a
8706 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8707 		 * its DL_PHYS_ADDR_ACK.
8708 		 */
8709 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8710 			ill->ill_phys_addr = NULL;
8711 		} else if (paddrlen != ill->ill_phys_addr_length) {
8712 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8713 			    paddrlen, ill->ill_phys_addr_length));
8714 			err = EINVAL;
8715 			break;
8716 		}
8717 
8718 		if (ill->ill_nd_lla_mp == NULL) {
8719 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8720 				err = ENOMEM;
8721 				break;
8722 			}
8723 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8724 		}
8725 
8726 		if (ill->ill_isv6) {
8727 			ill_setdefaulttoken(ill);
8728 			ipif_setlinklocal(ill->ill_ipif);
8729 		}
8730 		break;
8731 	}
8732 	case DL_OK_ACK:
8733 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8734 		    dl_primstr((int)dloa->dl_correct_primitive),
8735 		    dloa->dl_correct_primitive));
8736 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8737 		    char *, dl_primstr(dloa->dl_correct_primitive),
8738 		    ill_t *, ill);
8739 
8740 		switch (dloa->dl_correct_primitive) {
8741 		case DL_ENABMULTI_REQ:
8742 		case DL_DISABMULTI_REQ:
8743 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8744 			break;
8745 		case DL_PROMISCON_REQ:
8746 		case DL_PROMISCOFF_REQ:
8747 		case DL_UNBIND_REQ:
8748 		case DL_ATTACH_REQ:
8749 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8750 			break;
8751 		}
8752 		break;
8753 	default:
8754 		break;
8755 	}
8756 
8757 	freemsg(mp);
8758 	if (mp1 == NULL)
8759 		return;
8760 
8761 	/*
8762 	 * The operation must complete without EINPROGRESS since
8763 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8764 	 * the operation will be stuck forever inside the IPSQ.
8765 	 */
8766 	ASSERT(err != EINPROGRESS);
8767 
8768 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8769 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8770 	    ipif_t *, NULL);
8771 
8772 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8773 	case 0:
8774 		ipsq_current_finish(ipsq);
8775 		break;
8776 
8777 	case SIOCSLIFNAME:
8778 	case IF_UNITSEL: {
8779 		ill_t *ill_other = ILL_OTHER(ill);
8780 
8781 		/*
8782 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8783 		 * ill has a peer which is in an IPMP group, then place ill
8784 		 * into the same group.  One catch: although ifconfig plumbs
8785 		 * the appropriate IPMP meta-interface prior to plumbing this
8786 		 * ill, it is possible for multiple ifconfig applications to
8787 		 * race (or for another application to adjust plumbing), in
8788 		 * which case the IPMP meta-interface we need will be missing.
8789 		 * If so, kick the phyint out of the group.
8790 		 */
8791 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8792 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8793 			ipmp_illgrp_t	*illg;
8794 
8795 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8796 			if (illg == NULL)
8797 				ipmp_phyint_leave_grp(ill->ill_phyint);
8798 			else
8799 				ipmp_ill_join_illgrp(ill, illg);
8800 		}
8801 
8802 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8803 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8804 		else
8805 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8806 		break;
8807 	}
8808 	case SIOCLIFADDIF:
8809 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8810 		break;
8811 
8812 	default:
8813 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8814 		break;
8815 	}
8816 }
8817 
8818 /*
8819  * ip_rput_other is called by ip_rput to handle messages modifying the global
8820  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8821  */
8822 /* ARGSUSED */
8823 void
8824 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8825 {
8826 	ill_t		*ill = q->q_ptr;
8827 	struct iocblk	*iocp;
8828 
8829 	ip1dbg(("ip_rput_other "));
8830 	if (ipsq != NULL) {
8831 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8832 		ASSERT(ipsq->ipsq_xop ==
8833 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8834 	}
8835 
8836 	switch (mp->b_datap->db_type) {
8837 	case M_ERROR:
8838 	case M_HANGUP:
8839 		/*
8840 		 * The device has a problem.  We force the ILL down.  It can
8841 		 * be brought up again manually using SIOCSIFFLAGS (via
8842 		 * ifconfig or equivalent).
8843 		 */
8844 		ASSERT(ipsq != NULL);
8845 		if (mp->b_rptr < mp->b_wptr)
8846 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8847 		if (ill->ill_error == 0)
8848 			ill->ill_error = ENXIO;
8849 		if (!ill_down_start(q, mp))
8850 			return;
8851 		ipif_all_down_tail(ipsq, q, mp, NULL);
8852 		break;
8853 	case M_IOCNAK: {
8854 		iocp = (struct iocblk *)mp->b_rptr;
8855 
8856 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8857 		/*
8858 		 * If this was the first attempt, turn off the fastpath
8859 		 * probing.
8860 		 */
8861 		mutex_enter(&ill->ill_lock);
8862 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8863 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8864 			mutex_exit(&ill->ill_lock);
8865 			/*
8866 			 * don't flush the nce_t entries: we use them
8867 			 * as an index to the ncec itself.
8868 			 */
8869 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8870 			    ill->ill_name));
8871 		} else {
8872 			mutex_exit(&ill->ill_lock);
8873 		}
8874 		freemsg(mp);
8875 		break;
8876 	}
8877 	default:
8878 		ASSERT(0);
8879 		break;
8880 	}
8881 }
8882 
8883 /*
8884  * Update any source route, record route or timestamp options
8885  * When it fails it has consumed the message and BUMPed the MIB.
8886  */
8887 boolean_t
8888 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8889     ip_recv_attr_t *ira)
8890 {
8891 	ipoptp_t	opts;
8892 	uchar_t		*opt;
8893 	uint8_t		optval;
8894 	uint8_t		optlen;
8895 	ipaddr_t	dst;
8896 	ipaddr_t	ifaddr;
8897 	uint32_t	ts;
8898 	timestruc_t	now;
8899 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
8900 
8901 	ip2dbg(("ip_forward_options\n"));
8902 	dst = ipha->ipha_dst;
8903 	for (optval = ipoptp_first(&opts, ipha);
8904 	    optval != IPOPT_EOL;
8905 	    optval = ipoptp_next(&opts)) {
8906 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
8907 		opt = opts.ipoptp_cur;
8908 		optlen = opts.ipoptp_len;
8909 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
8910 		    optval, opts.ipoptp_len));
8911 		switch (optval) {
8912 			uint32_t off;
8913 		case IPOPT_SSRR:
8914 		case IPOPT_LSRR:
8915 			/* Check if adminstratively disabled */
8916 			if (!ipst->ips_ip_forward_src_routed) {
8917 				BUMP_MIB(dst_ill->ill_ip_mib,
8918 				    ipIfStatsForwProhibits);
8919 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
8920 				    mp, dst_ill);
8921 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
8922 				    ira);
8923 				return (B_FALSE);
8924 			}
8925 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8926 				/*
8927 				 * Must be partial since ip_input_options
8928 				 * checked for strict.
8929 				 */
8930 				break;
8931 			}
8932 			off = opt[IPOPT_OFFSET];
8933 			off--;
8934 		redo_srr:
8935 			if (optlen < IP_ADDR_LEN ||
8936 			    off > optlen - IP_ADDR_LEN) {
8937 				/* End of source route */
8938 				ip1dbg((
8939 				    "ip_forward_options: end of SR\n"));
8940 				break;
8941 			}
8942 			/* Pick a reasonable address on the outbound if */
8943 			ASSERT(dst_ill != NULL);
8944 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8945 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8946 			    NULL) != 0) {
8947 				/* No source! Shouldn't happen */
8948 				ifaddr = INADDR_ANY;
8949 			}
8950 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8951 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8952 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
8953 			    ntohl(dst)));
8954 
8955 			/*
8956 			 * Check if our address is present more than
8957 			 * once as consecutive hops in source route.
8958 			 */
8959 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
8960 				off += IP_ADDR_LEN;
8961 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8962 				goto redo_srr;
8963 			}
8964 			ipha->ipha_dst = dst;
8965 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8966 			break;
8967 		case IPOPT_RR:
8968 			off = opt[IPOPT_OFFSET];
8969 			off--;
8970 			if (optlen < IP_ADDR_LEN ||
8971 			    off > optlen - IP_ADDR_LEN) {
8972 				/* No more room - ignore */
8973 				ip1dbg((
8974 				    "ip_forward_options: end of RR\n"));
8975 				break;
8976 			}
8977 			/* Pick a reasonable address on the outbound if */
8978 			ASSERT(dst_ill != NULL);
8979 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8980 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8981 			    NULL) != 0) {
8982 				/* No source! Shouldn't happen */
8983 				ifaddr = INADDR_ANY;
8984 			}
8985 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8986 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8987 			break;
8988 		case IPOPT_TS:
8989 			/* Insert timestamp if there is room */
8990 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
8991 			case IPOPT_TS_TSONLY:
8992 				off = IPOPT_TS_TIMELEN;
8993 				break;
8994 			case IPOPT_TS_PRESPEC:
8995 			case IPOPT_TS_PRESPEC_RFC791:
8996 				/* Verify that the address matched */
8997 				off = opt[IPOPT_OFFSET] - 1;
8998 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8999 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9000 					/* Not for us */
9001 					break;
9002 				}
9003 				/* FALLTHRU */
9004 			case IPOPT_TS_TSANDADDR:
9005 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9006 				break;
9007 			default:
9008 				/*
9009 				 * ip_*put_options should have already
9010 				 * dropped this packet.
9011 				 */
9012 				cmn_err(CE_PANIC, "ip_forward_options: "
9013 				    "unknown IT - bug in ip_input_options?\n");
9014 				return (B_TRUE);	/* Keep "lint" happy */
9015 			}
9016 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9017 				/* Increase overflow counter */
9018 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9019 				opt[IPOPT_POS_OV_FLG] =
9020 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9021 				    (off << 4));
9022 				break;
9023 			}
9024 			off = opt[IPOPT_OFFSET] - 1;
9025 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9026 			case IPOPT_TS_PRESPEC:
9027 			case IPOPT_TS_PRESPEC_RFC791:
9028 			case IPOPT_TS_TSANDADDR:
9029 				/* Pick a reasonable addr on the outbound if */
9030 				ASSERT(dst_ill != NULL);
9031 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9032 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9033 				    NULL, NULL) != 0) {
9034 					/* No source! Shouldn't happen */
9035 					ifaddr = INADDR_ANY;
9036 				}
9037 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9038 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9039 				/* FALLTHRU */
9040 			case IPOPT_TS_TSONLY:
9041 				off = opt[IPOPT_OFFSET] - 1;
9042 				/* Compute # of milliseconds since midnight */
9043 				gethrestime(&now);
9044 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9045 				    now.tv_nsec / (NANOSEC / MILLISEC);
9046 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9047 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9048 				break;
9049 			}
9050 			break;
9051 		}
9052 	}
9053 	return (B_TRUE);
9054 }
9055 
9056 /*
9057  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9058  * returns 'true' if there are still fragments left on the queue, in
9059  * which case we restart the timer.
9060  */
9061 void
9062 ill_frag_timer(void *arg)
9063 {
9064 	ill_t	*ill = (ill_t *)arg;
9065 	boolean_t frag_pending;
9066 	ip_stack_t *ipst = ill->ill_ipst;
9067 	time_t	timeout;
9068 
9069 	mutex_enter(&ill->ill_lock);
9070 	ASSERT(!ill->ill_fragtimer_executing);
9071 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9072 		ill->ill_frag_timer_id = 0;
9073 		mutex_exit(&ill->ill_lock);
9074 		return;
9075 	}
9076 	ill->ill_fragtimer_executing = 1;
9077 	mutex_exit(&ill->ill_lock);
9078 
9079 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9080 	    ipst->ips_ip_reassembly_timeout);
9081 
9082 	frag_pending = ill_frag_timeout(ill, timeout);
9083 
9084 	/*
9085 	 * Restart the timer, if we have fragments pending or if someone
9086 	 * wanted us to be scheduled again.
9087 	 */
9088 	mutex_enter(&ill->ill_lock);
9089 	ill->ill_fragtimer_executing = 0;
9090 	ill->ill_frag_timer_id = 0;
9091 	if (frag_pending || ill->ill_fragtimer_needrestart)
9092 		ill_frag_timer_start(ill);
9093 	mutex_exit(&ill->ill_lock);
9094 }
9095 
9096 void
9097 ill_frag_timer_start(ill_t *ill)
9098 {
9099 	ip_stack_t *ipst = ill->ill_ipst;
9100 	clock_t	timeo_ms;
9101 
9102 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9103 
9104 	/* If the ill is closing or opening don't proceed */
9105 	if (ill->ill_state_flags & ILL_CONDEMNED)
9106 		return;
9107 
9108 	if (ill->ill_fragtimer_executing) {
9109 		/*
9110 		 * ill_frag_timer is currently executing. Just record the
9111 		 * the fact that we want the timer to be restarted.
9112 		 * ill_frag_timer will post a timeout before it returns,
9113 		 * ensuring it will be called again.
9114 		 */
9115 		ill->ill_fragtimer_needrestart = 1;
9116 		return;
9117 	}
9118 
9119 	if (ill->ill_frag_timer_id == 0) {
9120 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9121 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9122 
9123 		/*
9124 		 * The timer is neither running nor is the timeout handler
9125 		 * executing. Post a timeout so that ill_frag_timer will be
9126 		 * called
9127 		 */
9128 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9129 		    MSEC_TO_TICK(timeo_ms >> 1));
9130 		ill->ill_fragtimer_needrestart = 0;
9131 	}
9132 }
9133 
9134 /*
9135  * Update any source route, record route or timestamp options.
9136  * Check that we are at end of strict source route.
9137  * The options have already been checked for sanity in ip_input_options().
9138  */
9139 boolean_t
9140 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9141 {
9142 	ipoptp_t	opts;
9143 	uchar_t		*opt;
9144 	uint8_t		optval;
9145 	uint8_t		optlen;
9146 	ipaddr_t	dst;
9147 	ipaddr_t	ifaddr;
9148 	uint32_t	ts;
9149 	timestruc_t	now;
9150 	ill_t		*ill = ira->ira_ill;
9151 	ip_stack_t	*ipst = ill->ill_ipst;
9152 
9153 	ip2dbg(("ip_input_local_options\n"));
9154 
9155 	for (optval = ipoptp_first(&opts, ipha);
9156 	    optval != IPOPT_EOL;
9157 	    optval = ipoptp_next(&opts)) {
9158 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9159 		opt = opts.ipoptp_cur;
9160 		optlen = opts.ipoptp_len;
9161 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9162 		    optval, optlen));
9163 		switch (optval) {
9164 			uint32_t off;
9165 		case IPOPT_SSRR:
9166 		case IPOPT_LSRR:
9167 			off = opt[IPOPT_OFFSET];
9168 			off--;
9169 			if (optlen < IP_ADDR_LEN ||
9170 			    off > optlen - IP_ADDR_LEN) {
9171 				/* End of source route */
9172 				ip1dbg(("ip_input_local_options: end of SR\n"));
9173 				break;
9174 			}
9175 			/*
9176 			 * This will only happen if two consecutive entries
9177 			 * in the source route contains our address or if
9178 			 * it is a packet with a loose source route which
9179 			 * reaches us before consuming the whole source route
9180 			 */
9181 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9182 			if (optval == IPOPT_SSRR) {
9183 				goto bad_src_route;
9184 			}
9185 			/*
9186 			 * Hack: instead of dropping the packet truncate the
9187 			 * source route to what has been used by filling the
9188 			 * rest with IPOPT_NOP.
9189 			 */
9190 			opt[IPOPT_OLEN] = (uint8_t)off;
9191 			while (off < optlen) {
9192 				opt[off++] = IPOPT_NOP;
9193 			}
9194 			break;
9195 		case IPOPT_RR:
9196 			off = opt[IPOPT_OFFSET];
9197 			off--;
9198 			if (optlen < IP_ADDR_LEN ||
9199 			    off > optlen - IP_ADDR_LEN) {
9200 				/* No more room - ignore */
9201 				ip1dbg((
9202 				    "ip_input_local_options: end of RR\n"));
9203 				break;
9204 			}
9205 			/* Pick a reasonable address on the outbound if */
9206 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9207 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9208 			    NULL) != 0) {
9209 				/* No source! Shouldn't happen */
9210 				ifaddr = INADDR_ANY;
9211 			}
9212 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9213 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9214 			break;
9215 		case IPOPT_TS:
9216 			/* Insert timestamp if there is romm */
9217 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9218 			case IPOPT_TS_TSONLY:
9219 				off = IPOPT_TS_TIMELEN;
9220 				break;
9221 			case IPOPT_TS_PRESPEC:
9222 			case IPOPT_TS_PRESPEC_RFC791:
9223 				/* Verify that the address matched */
9224 				off = opt[IPOPT_OFFSET] - 1;
9225 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9226 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9227 					/* Not for us */
9228 					break;
9229 				}
9230 				/* FALLTHRU */
9231 			case IPOPT_TS_TSANDADDR:
9232 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9233 				break;
9234 			default:
9235 				/*
9236 				 * ip_*put_options should have already
9237 				 * dropped this packet.
9238 				 */
9239 				cmn_err(CE_PANIC, "ip_input_local_options: "
9240 				    "unknown IT - bug in ip_input_options?\n");
9241 				return (B_TRUE);	/* Keep "lint" happy */
9242 			}
9243 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9244 				/* Increase overflow counter */
9245 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9246 				opt[IPOPT_POS_OV_FLG] =
9247 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9248 				    (off << 4));
9249 				break;
9250 			}
9251 			off = opt[IPOPT_OFFSET] - 1;
9252 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9253 			case IPOPT_TS_PRESPEC:
9254 			case IPOPT_TS_PRESPEC_RFC791:
9255 			case IPOPT_TS_TSANDADDR:
9256 				/* Pick a reasonable addr on the outbound if */
9257 				if (ip_select_source_v4(ill, INADDR_ANY,
9258 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9259 				    &ifaddr, NULL, NULL) != 0) {
9260 					/* No source! Shouldn't happen */
9261 					ifaddr = INADDR_ANY;
9262 				}
9263 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9264 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9265 				/* FALLTHRU */
9266 			case IPOPT_TS_TSONLY:
9267 				off = opt[IPOPT_OFFSET] - 1;
9268 				/* Compute # of milliseconds since midnight */
9269 				gethrestime(&now);
9270 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9271 				    now.tv_nsec / (NANOSEC / MILLISEC);
9272 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9273 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9274 				break;
9275 			}
9276 			break;
9277 		}
9278 	}
9279 	return (B_TRUE);
9280 
9281 bad_src_route:
9282 	/* make sure we clear any indication of a hardware checksum */
9283 	DB_CKSUMFLAGS(mp) = 0;
9284 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9285 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9286 	return (B_FALSE);
9287 
9288 }
9289 
9290 /*
9291  * Process IP options in an inbound packet.  Always returns the nexthop.
9292  * Normally this is the passed in nexthop, but if there is an option
9293  * that effects the nexthop (such as a source route) that will be returned.
9294  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9295  * and mp freed.
9296  */
9297 ipaddr_t
9298 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9299     ip_recv_attr_t *ira, int *errorp)
9300 {
9301 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9302 	ipoptp_t	opts;
9303 	uchar_t		*opt;
9304 	uint8_t		optval;
9305 	uint8_t		optlen;
9306 	intptr_t	code = 0;
9307 	ire_t		*ire;
9308 
9309 	ip2dbg(("ip_input_options\n"));
9310 	*errorp = 0;
9311 	for (optval = ipoptp_first(&opts, ipha);
9312 	    optval != IPOPT_EOL;
9313 	    optval = ipoptp_next(&opts)) {
9314 		opt = opts.ipoptp_cur;
9315 		optlen = opts.ipoptp_len;
9316 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9317 		    optval, optlen));
9318 		/*
9319 		 * Note: we need to verify the checksum before we
9320 		 * modify anything thus this routine only extracts the next
9321 		 * hop dst from any source route.
9322 		 */
9323 		switch (optval) {
9324 			uint32_t off;
9325 		case IPOPT_SSRR:
9326 		case IPOPT_LSRR:
9327 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9328 				if (optval == IPOPT_SSRR) {
9329 					ip1dbg(("ip_input_options: not next"
9330 					    " strict source route 0x%x\n",
9331 					    ntohl(dst)));
9332 					code = (char *)&ipha->ipha_dst -
9333 					    (char *)ipha;
9334 					goto param_prob; /* RouterReq's */
9335 				}
9336 				ip2dbg(("ip_input_options: "
9337 				    "not next source route 0x%x\n",
9338 				    ntohl(dst)));
9339 				break;
9340 			}
9341 
9342 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9343 				ip1dbg((
9344 				    "ip_input_options: bad option offset\n"));
9345 				code = (char *)&opt[IPOPT_OLEN] -
9346 				    (char *)ipha;
9347 				goto param_prob;
9348 			}
9349 			off = opt[IPOPT_OFFSET];
9350 			off--;
9351 		redo_srr:
9352 			if (optlen < IP_ADDR_LEN ||
9353 			    off > optlen - IP_ADDR_LEN) {
9354 				/* End of source route */
9355 				ip1dbg(("ip_input_options: end of SR\n"));
9356 				break;
9357 			}
9358 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9359 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9360 			    ntohl(dst)));
9361 
9362 			/*
9363 			 * Check if our address is present more than
9364 			 * once as consecutive hops in source route.
9365 			 * XXX verify per-interface ip_forwarding
9366 			 * for source route?
9367 			 */
9368 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9369 				off += IP_ADDR_LEN;
9370 				goto redo_srr;
9371 			}
9372 
9373 			if (dst == htonl(INADDR_LOOPBACK)) {
9374 				ip1dbg(("ip_input_options: loopback addr in "
9375 				    "source route!\n"));
9376 				goto bad_src_route;
9377 			}
9378 			/*
9379 			 * For strict: verify that dst is directly
9380 			 * reachable.
9381 			 */
9382 			if (optval == IPOPT_SSRR) {
9383 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9384 				    IRE_INTERFACE, NULL, ALL_ZONES,
9385 				    ira->ira_tsl,
9386 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9387 				    NULL);
9388 				if (ire == NULL) {
9389 					ip1dbg(("ip_input_options: SSRR not "
9390 					    "directly reachable: 0x%x\n",
9391 					    ntohl(dst)));
9392 					goto bad_src_route;
9393 				}
9394 				ire_refrele(ire);
9395 			}
9396 			/*
9397 			 * Defer update of the offset and the record route
9398 			 * until the packet is forwarded.
9399 			 */
9400 			break;
9401 		case IPOPT_RR:
9402 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9403 				ip1dbg((
9404 				    "ip_input_options: bad option offset\n"));
9405 				code = (char *)&opt[IPOPT_OLEN] -
9406 				    (char *)ipha;
9407 				goto param_prob;
9408 			}
9409 			break;
9410 		case IPOPT_TS:
9411 			/*
9412 			 * Verify that length >= 5 and that there is either
9413 			 * room for another timestamp or that the overflow
9414 			 * counter is not maxed out.
9415 			 */
9416 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9417 			if (optlen < IPOPT_MINLEN_IT) {
9418 				goto param_prob;
9419 			}
9420 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9421 				ip1dbg((
9422 				    "ip_input_options: bad option offset\n"));
9423 				code = (char *)&opt[IPOPT_OFFSET] -
9424 				    (char *)ipha;
9425 				goto param_prob;
9426 			}
9427 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9428 			case IPOPT_TS_TSONLY:
9429 				off = IPOPT_TS_TIMELEN;
9430 				break;
9431 			case IPOPT_TS_TSANDADDR:
9432 			case IPOPT_TS_PRESPEC:
9433 			case IPOPT_TS_PRESPEC_RFC791:
9434 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9435 				break;
9436 			default:
9437 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9438 				    (char *)ipha;
9439 				goto param_prob;
9440 			}
9441 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9442 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9443 				/*
9444 				 * No room and the overflow counter is 15
9445 				 * already.
9446 				 */
9447 				goto param_prob;
9448 			}
9449 			break;
9450 		}
9451 	}
9452 
9453 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9454 		return (dst);
9455 	}
9456 
9457 	ip1dbg(("ip_input_options: error processing IP options."));
9458 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9459 
9460 param_prob:
9461 	/* make sure we clear any indication of a hardware checksum */
9462 	DB_CKSUMFLAGS(mp) = 0;
9463 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9464 	icmp_param_problem(mp, (uint8_t)code, ira);
9465 	*errorp = -1;
9466 	return (dst);
9467 
9468 bad_src_route:
9469 	/* make sure we clear any indication of a hardware checksum */
9470 	DB_CKSUMFLAGS(mp) = 0;
9471 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9472 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9473 	*errorp = -1;
9474 	return (dst);
9475 }
9476 
9477 /*
9478  * IP & ICMP info in >=14 msg's ...
9479  *  - ip fixed part (mib2_ip_t)
9480  *  - icmp fixed part (mib2_icmp_t)
9481  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9482  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9483  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9484  *  - ipRouteAttributeTable (ip 102)	labeled routes
9485  *  - ip multicast membership (ip_member_t)
9486  *  - ip multicast source filtering (ip_grpsrc_t)
9487  *  - igmp fixed part (struct igmpstat)
9488  *  - multicast routing stats (struct mrtstat)
9489  *  - multicast routing vifs (array of struct vifctl)
9490  *  - multicast routing routes (array of struct mfcctl)
9491  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9492  *					One per ill plus one generic
9493  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9494  *					One per ill plus one generic
9495  *  - ipv6RouteEntry			all IPv6 IREs
9496  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9497  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9498  *  - ipv6AddrEntry			all IPv6 ipifs
9499  *  - ipv6 multicast membership (ipv6_member_t)
9500  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9501  *
9502  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9503  * already filled in by the caller.
9504  * If legacy_req is true then MIB structures needs to be truncated to their
9505  * legacy sizes before being returned.
9506  * Return value of 0 indicates that no messages were sent and caller
9507  * should free mpctl.
9508  */
9509 int
9510 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level, boolean_t legacy_req)
9511 {
9512 	ip_stack_t *ipst;
9513 	sctp_stack_t *sctps;
9514 
9515 	if (q->q_next != NULL) {
9516 		ipst = ILLQ_TO_IPST(q);
9517 	} else {
9518 		ipst = CONNQ_TO_IPST(q);
9519 	}
9520 	ASSERT(ipst != NULL);
9521 	sctps = ipst->ips_netstack->netstack_sctp;
9522 
9523 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9524 		return (0);
9525 	}
9526 
9527 	/*
9528 	 * For the purposes of the (broken) packet shell use
9529 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9530 	 * to make TCP and UDP appear first in the list of mib items.
9531 	 * TBD: We could expand this and use it in netstat so that
9532 	 * the kernel doesn't have to produce large tables (connections,
9533 	 * routes, etc) when netstat only wants the statistics or a particular
9534 	 * table.
9535 	 */
9536 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9537 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9538 			return (1);
9539 		}
9540 	}
9541 
9542 	if (level != MIB2_TCP) {
9543 		if ((mpctl = udp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9544 			return (1);
9545 		}
9546 	}
9547 
9548 	if (level != MIB2_UDP) {
9549 		if ((mpctl = tcp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9550 			return (1);
9551 		}
9552 	}
9553 
9554 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9555 	    ipst, legacy_req)) == NULL) {
9556 		return (1);
9557 	}
9558 
9559 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst,
9560 	    legacy_req)) == NULL) {
9561 		return (1);
9562 	}
9563 
9564 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9565 		return (1);
9566 	}
9567 
9568 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9569 		return (1);
9570 	}
9571 
9572 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9573 		return (1);
9574 	}
9575 
9576 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9577 		return (1);
9578 	}
9579 
9580 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst,
9581 	    legacy_req)) == NULL) {
9582 		return (1);
9583 	}
9584 
9585 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst,
9586 	    legacy_req)) == NULL) {
9587 		return (1);
9588 	}
9589 
9590 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9591 		return (1);
9592 	}
9593 
9594 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9595 		return (1);
9596 	}
9597 
9598 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9599 		return (1);
9600 	}
9601 
9602 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9603 		return (1);
9604 	}
9605 
9606 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9607 		return (1);
9608 	}
9609 
9610 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9611 		return (1);
9612 	}
9613 
9614 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9615 	if (mpctl == NULL)
9616 		return (1);
9617 
9618 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9619 	if (mpctl == NULL)
9620 		return (1);
9621 
9622 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9623 		return (1);
9624 	}
9625 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9626 		return (1);
9627 	}
9628 	freemsg(mpctl);
9629 	return (1);
9630 }
9631 
9632 /* Get global (legacy) IPv4 statistics */
9633 static mblk_t *
9634 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9635     ip_stack_t *ipst, boolean_t legacy_req)
9636 {
9637 	mib2_ip_t		old_ip_mib;
9638 	struct opthdr		*optp;
9639 	mblk_t			*mp2ctl;
9640 	mib2_ipAddrEntry_t	mae;
9641 
9642 	/*
9643 	 * make a copy of the original message
9644 	 */
9645 	mp2ctl = copymsg(mpctl);
9646 
9647 	/* fixed length IP structure... */
9648 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9649 	optp->level = MIB2_IP;
9650 	optp->name = 0;
9651 	SET_MIB(old_ip_mib.ipForwarding,
9652 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9653 	SET_MIB(old_ip_mib.ipDefaultTTL,
9654 	    (uint32_t)ipst->ips_ip_def_ttl);
9655 	SET_MIB(old_ip_mib.ipReasmTimeout,
9656 	    ipst->ips_ip_reassembly_timeout);
9657 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9658 	    (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9659 	    sizeof (mib2_ipAddrEntry_t));
9660 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9661 	    sizeof (mib2_ipRouteEntry_t));
9662 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9663 	    sizeof (mib2_ipNetToMediaEntry_t));
9664 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9665 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9666 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9667 	    sizeof (mib2_ipAttributeEntry_t));
9668 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9669 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9670 
9671 	/*
9672 	 * Grab the statistics from the new IP MIB
9673 	 */
9674 	SET_MIB(old_ip_mib.ipInReceives,
9675 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9676 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9677 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9678 	SET_MIB(old_ip_mib.ipForwDatagrams,
9679 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9680 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9681 	    ipmib->ipIfStatsInUnknownProtos);
9682 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9683 	SET_MIB(old_ip_mib.ipInDelivers,
9684 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9685 	SET_MIB(old_ip_mib.ipOutRequests,
9686 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9687 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9688 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9689 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9690 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9691 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9692 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9693 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9694 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9695 
9696 	/* ipRoutingDiscards is not being used */
9697 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9698 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9699 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9700 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9701 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9702 	    ipmib->ipIfStatsReasmDuplicates);
9703 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9704 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9705 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9706 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9707 	SET_MIB(old_ip_mib.rawipInOverflows,
9708 	    ipmib->rawipIfStatsInOverflows);
9709 
9710 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9711 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9712 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9713 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9714 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9715 	    ipmib->ipIfStatsOutSwitchIPVersion);
9716 
9717 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9718 	    (int)sizeof (old_ip_mib))) {
9719 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9720 		    (uint_t)sizeof (old_ip_mib)));
9721 	}
9722 
9723 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9724 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9725 	    (int)optp->level, (int)optp->name, (int)optp->len));
9726 	qreply(q, mpctl);
9727 	return (mp2ctl);
9728 }
9729 
9730 /* Per interface IPv4 statistics */
9731 static mblk_t *
9732 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9733     boolean_t legacy_req)
9734 {
9735 	struct opthdr		*optp;
9736 	mblk_t			*mp2ctl;
9737 	ill_t			*ill;
9738 	ill_walk_context_t	ctx;
9739 	mblk_t			*mp_tail = NULL;
9740 	mib2_ipIfStatsEntry_t	global_ip_mib;
9741 	mib2_ipAddrEntry_t	mae;
9742 
9743 	/*
9744 	 * Make a copy of the original message
9745 	 */
9746 	mp2ctl = copymsg(mpctl);
9747 
9748 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9749 	optp->level = MIB2_IP;
9750 	optp->name = MIB2_IP_TRAFFIC_STATS;
9751 	/* Include "unknown interface" ip_mib */
9752 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9753 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9754 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9755 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9756 	    (ipst->ips_ip_forwarding ? 1 : 2));
9757 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9758 	    (uint32_t)ipst->ips_ip_def_ttl);
9759 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9760 	    sizeof (mib2_ipIfStatsEntry_t));
9761 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9762 	    sizeof (mib2_ipAddrEntry_t));
9763 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9764 	    sizeof (mib2_ipRouteEntry_t));
9765 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9766 	    sizeof (mib2_ipNetToMediaEntry_t));
9767 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9768 	    sizeof (ip_member_t));
9769 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9770 	    sizeof (ip_grpsrc_t));
9771 
9772 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9773 
9774 	if (legacy_req) {
9775 		SET_MIB(global_ip_mib.ipIfStatsAddrEntrySize,
9776 		    LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t));
9777 	}
9778 
9779 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9780 	    (char *)&global_ip_mib, (int)sizeof (global_ip_mib))) {
9781 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9782 		    "failed to allocate %u bytes\n",
9783 		    (uint_t)sizeof (global_ip_mib)));
9784 	}
9785 
9786 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9787 	ill = ILL_START_WALK_V4(&ctx, ipst);
9788 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9789 		ill->ill_ip_mib->ipIfStatsIfIndex =
9790 		    ill->ill_phyint->phyint_ifindex;
9791 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9792 		    (ipst->ips_ip_forwarding ? 1 : 2));
9793 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9794 		    (uint32_t)ipst->ips_ip_def_ttl);
9795 
9796 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9797 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9798 		    (char *)ill->ill_ip_mib,
9799 		    (int)sizeof (*ill->ill_ip_mib))) {
9800 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9801 			    "failed to allocate %u bytes\n",
9802 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9803 		}
9804 	}
9805 	rw_exit(&ipst->ips_ill_g_lock);
9806 
9807 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9808 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9809 	    "level %d, name %d, len %d\n",
9810 	    (int)optp->level, (int)optp->name, (int)optp->len));
9811 	qreply(q, mpctl);
9812 
9813 	if (mp2ctl == NULL)
9814 		return (NULL);
9815 
9816 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst,
9817 	    legacy_req));
9818 }
9819 
9820 /* Global IPv4 ICMP statistics */
9821 static mblk_t *
9822 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9823 {
9824 	struct opthdr		*optp;
9825 	mblk_t			*mp2ctl;
9826 
9827 	/*
9828 	 * Make a copy of the original message
9829 	 */
9830 	mp2ctl = copymsg(mpctl);
9831 
9832 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9833 	optp->level = MIB2_ICMP;
9834 	optp->name = 0;
9835 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9836 	    (int)sizeof (ipst->ips_icmp_mib))) {
9837 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9838 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9839 	}
9840 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9841 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9842 	    (int)optp->level, (int)optp->name, (int)optp->len));
9843 	qreply(q, mpctl);
9844 	return (mp2ctl);
9845 }
9846 
9847 /* Global IPv4 IGMP statistics */
9848 static mblk_t *
9849 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9850 {
9851 	struct opthdr		*optp;
9852 	mblk_t			*mp2ctl;
9853 
9854 	/*
9855 	 * make a copy of the original message
9856 	 */
9857 	mp2ctl = copymsg(mpctl);
9858 
9859 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9860 	optp->level = EXPER_IGMP;
9861 	optp->name = 0;
9862 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9863 	    (int)sizeof (ipst->ips_igmpstat))) {
9864 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9865 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9866 	}
9867 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9868 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9869 	    (int)optp->level, (int)optp->name, (int)optp->len));
9870 	qreply(q, mpctl);
9871 	return (mp2ctl);
9872 }
9873 
9874 /* Global IPv4 Multicast Routing statistics */
9875 static mblk_t *
9876 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9877 {
9878 	struct opthdr		*optp;
9879 	mblk_t			*mp2ctl;
9880 
9881 	/*
9882 	 * make a copy of the original message
9883 	 */
9884 	mp2ctl = copymsg(mpctl);
9885 
9886 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9887 	optp->level = EXPER_DVMRP;
9888 	optp->name = 0;
9889 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9890 		ip0dbg(("ip_mroute_stats: failed\n"));
9891 	}
9892 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9893 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9894 	    (int)optp->level, (int)optp->name, (int)optp->len));
9895 	qreply(q, mpctl);
9896 	return (mp2ctl);
9897 }
9898 
9899 /* IPv4 address information */
9900 static mblk_t *
9901 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9902     boolean_t legacy_req)
9903 {
9904 	struct opthdr		*optp;
9905 	mblk_t			*mp2ctl;
9906 	mblk_t			*mp_tail = NULL;
9907 	ill_t			*ill;
9908 	ipif_t			*ipif;
9909 	uint_t			bitval;
9910 	mib2_ipAddrEntry_t	mae;
9911 	size_t			mae_size;
9912 	zoneid_t		zoneid;
9913 	ill_walk_context_t	ctx;
9914 
9915 	/*
9916 	 * make a copy of the original message
9917 	 */
9918 	mp2ctl = copymsg(mpctl);
9919 
9920 	mae_size = (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9921 	    sizeof (mib2_ipAddrEntry_t);
9922 
9923 	/* ipAddrEntryTable */
9924 
9925 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9926 	optp->level = MIB2_IP;
9927 	optp->name = MIB2_IP_ADDR;
9928 	zoneid = Q_TO_CONN(q)->conn_zoneid;
9929 
9930 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9931 	ill = ILL_START_WALK_V4(&ctx, ipst);
9932 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9933 		for (ipif = ill->ill_ipif; ipif != NULL;
9934 		    ipif = ipif->ipif_next) {
9935 			if (ipif->ipif_zoneid != zoneid &&
9936 			    ipif->ipif_zoneid != ALL_ZONES)
9937 				continue;
9938 			/* Sum of count from dead IRE_LO* and our current */
9939 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9940 			if (ipif->ipif_ire_local != NULL) {
9941 				mae.ipAdEntInfo.ae_ibcnt +=
9942 				    ipif->ipif_ire_local->ire_ib_pkt_count;
9943 			}
9944 			mae.ipAdEntInfo.ae_obcnt = 0;
9945 			mae.ipAdEntInfo.ae_focnt = 0;
9946 
9947 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
9948 			    OCTET_LENGTH);
9949 			mae.ipAdEntIfIndex.o_length =
9950 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
9951 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
9952 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
9953 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
9954 			mae.ipAdEntInfo.ae_subnet_len =
9955 			    ip_mask_to_plen(ipif->ipif_net_mask);
9956 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
9957 			for (bitval = 1;
9958 			    bitval &&
9959 			    !(bitval & ipif->ipif_brd_addr);
9960 			    bitval <<= 1)
9961 				noop;
9962 			mae.ipAdEntBcastAddr = bitval;
9963 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
9964 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
9965 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
9966 			mae.ipAdEntInfo.ae_broadcast_addr =
9967 			    ipif->ipif_brd_addr;
9968 			mae.ipAdEntInfo.ae_pp_dst_addr =
9969 			    ipif->ipif_pp_dst_addr;
9970 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
9971 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
9972 			mae.ipAdEntRetransmitTime =
9973 			    ill->ill_reachable_retrans_time;
9974 
9975 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9976 			    (char *)&mae, (int)mae_size)) {
9977 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
9978 				    "allocate %u bytes\n", (uint_t)mae_size));
9979 			}
9980 		}
9981 	}
9982 	rw_exit(&ipst->ips_ill_g_lock);
9983 
9984 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9985 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
9986 	    (int)optp->level, (int)optp->name, (int)optp->len));
9987 	qreply(q, mpctl);
9988 	return (mp2ctl);
9989 }
9990 
9991 /* IPv6 address information */
9992 static mblk_t *
9993 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9994     boolean_t legacy_req)
9995 {
9996 	struct opthdr		*optp;
9997 	mblk_t			*mp2ctl;
9998 	mblk_t			*mp_tail = NULL;
9999 	ill_t			*ill;
10000 	ipif_t			*ipif;
10001 	mib2_ipv6AddrEntry_t	mae6;
10002 	size_t			mae6_size;
10003 	zoneid_t		zoneid;
10004 	ill_walk_context_t	ctx;
10005 
10006 	/*
10007 	 * make a copy of the original message
10008 	 */
10009 	mp2ctl = copymsg(mpctl);
10010 
10011 	mae6_size = (legacy_req) ?
10012 	    LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t) :
10013 	    sizeof (mib2_ipv6AddrEntry_t);
10014 
10015 	/* ipv6AddrEntryTable */
10016 
10017 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10018 	optp->level = MIB2_IP6;
10019 	optp->name = MIB2_IP6_ADDR;
10020 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10021 
10022 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10023 	ill = ILL_START_WALK_V6(&ctx, ipst);
10024 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10025 		for (ipif = ill->ill_ipif; ipif != NULL;
10026 		    ipif = ipif->ipif_next) {
10027 			if (ipif->ipif_zoneid != zoneid &&
10028 			    ipif->ipif_zoneid != ALL_ZONES)
10029 				continue;
10030 			/* Sum of count from dead IRE_LO* and our current */
10031 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10032 			if (ipif->ipif_ire_local != NULL) {
10033 				mae6.ipv6AddrInfo.ae_ibcnt +=
10034 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10035 			}
10036 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10037 			mae6.ipv6AddrInfo.ae_focnt = 0;
10038 
10039 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10040 			    OCTET_LENGTH);
10041 			mae6.ipv6AddrIfIndex.o_length =
10042 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10043 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10044 			mae6.ipv6AddrPfxLength =
10045 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10046 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10047 			mae6.ipv6AddrInfo.ae_subnet_len =
10048 			    mae6.ipv6AddrPfxLength;
10049 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10050 
10051 			/* Type: stateless(1), stateful(2), unknown(3) */
10052 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10053 				mae6.ipv6AddrType = 1;
10054 			else
10055 				mae6.ipv6AddrType = 2;
10056 			/* Anycast: true(1), false(2) */
10057 			if (ipif->ipif_flags & IPIF_ANYCAST)
10058 				mae6.ipv6AddrAnycastFlag = 1;
10059 			else
10060 				mae6.ipv6AddrAnycastFlag = 2;
10061 
10062 			/*
10063 			 * Address status: preferred(1), deprecated(2),
10064 			 * invalid(3), inaccessible(4), unknown(5)
10065 			 */
10066 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10067 				mae6.ipv6AddrStatus = 3;
10068 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10069 				mae6.ipv6AddrStatus = 2;
10070 			else
10071 				mae6.ipv6AddrStatus = 1;
10072 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10073 			mae6.ipv6AddrInfo.ae_metric  =
10074 			    ipif->ipif_ill->ill_metric;
10075 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10076 			    ipif->ipif_v6pp_dst_addr;
10077 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10078 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10079 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10080 			mae6.ipv6AddrIdentifier = ill->ill_token;
10081 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10082 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10083 			mae6.ipv6AddrRetransmitTime =
10084 			    ill->ill_reachable_retrans_time;
10085 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10086 			    (char *)&mae6, (int)mae6_size)) {
10087 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10088 				    "allocate %u bytes\n",
10089 				    (uint_t)mae6_size));
10090 			}
10091 		}
10092 	}
10093 	rw_exit(&ipst->ips_ill_g_lock);
10094 
10095 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10096 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10097 	    (int)optp->level, (int)optp->name, (int)optp->len));
10098 	qreply(q, mpctl);
10099 	return (mp2ctl);
10100 }
10101 
10102 /* IPv4 multicast group membership. */
10103 static mblk_t *
10104 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10105 {
10106 	struct opthdr		*optp;
10107 	mblk_t			*mp2ctl;
10108 	ill_t			*ill;
10109 	ipif_t			*ipif;
10110 	ilm_t			*ilm;
10111 	ip_member_t		ipm;
10112 	mblk_t			*mp_tail = NULL;
10113 	ill_walk_context_t	ctx;
10114 	zoneid_t		zoneid;
10115 
10116 	/*
10117 	 * make a copy of the original message
10118 	 */
10119 	mp2ctl = copymsg(mpctl);
10120 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10121 
10122 	/* ipGroupMember table */
10123 	optp = (struct opthdr *)&mpctl->b_rptr[
10124 	    sizeof (struct T_optmgmt_ack)];
10125 	optp->level = MIB2_IP;
10126 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10127 
10128 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10129 	ill = ILL_START_WALK_V4(&ctx, ipst);
10130 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10131 		/* Make sure the ill isn't going away. */
10132 		if (!ill_check_and_refhold(ill))
10133 			continue;
10134 		rw_exit(&ipst->ips_ill_g_lock);
10135 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10136 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10137 			if (ilm->ilm_zoneid != zoneid &&
10138 			    ilm->ilm_zoneid != ALL_ZONES)
10139 				continue;
10140 
10141 			/* Is there an ipif for ilm_ifaddr? */
10142 			for (ipif = ill->ill_ipif; ipif != NULL;
10143 			    ipif = ipif->ipif_next) {
10144 				if (!IPIF_IS_CONDEMNED(ipif) &&
10145 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10146 				    ilm->ilm_ifaddr != INADDR_ANY)
10147 					break;
10148 			}
10149 			if (ipif != NULL) {
10150 				ipif_get_name(ipif,
10151 				    ipm.ipGroupMemberIfIndex.o_bytes,
10152 				    OCTET_LENGTH);
10153 			} else {
10154 				ill_get_name(ill,
10155 				    ipm.ipGroupMemberIfIndex.o_bytes,
10156 				    OCTET_LENGTH);
10157 			}
10158 			ipm.ipGroupMemberIfIndex.o_length =
10159 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10160 
10161 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10162 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10163 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10164 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10165 			    (char *)&ipm, (int)sizeof (ipm))) {
10166 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10167 				    "failed to allocate %u bytes\n",
10168 				    (uint_t)sizeof (ipm)));
10169 			}
10170 		}
10171 		rw_exit(&ill->ill_mcast_lock);
10172 		ill_refrele(ill);
10173 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10174 	}
10175 	rw_exit(&ipst->ips_ill_g_lock);
10176 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10177 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10178 	    (int)optp->level, (int)optp->name, (int)optp->len));
10179 	qreply(q, mpctl);
10180 	return (mp2ctl);
10181 }
10182 
10183 /* IPv6 multicast group membership. */
10184 static mblk_t *
10185 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10186 {
10187 	struct opthdr		*optp;
10188 	mblk_t			*mp2ctl;
10189 	ill_t			*ill;
10190 	ilm_t			*ilm;
10191 	ipv6_member_t		ipm6;
10192 	mblk_t			*mp_tail = NULL;
10193 	ill_walk_context_t	ctx;
10194 	zoneid_t		zoneid;
10195 
10196 	/*
10197 	 * make a copy of the original message
10198 	 */
10199 	mp2ctl = copymsg(mpctl);
10200 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10201 
10202 	/* ip6GroupMember table */
10203 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10204 	optp->level = MIB2_IP6;
10205 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10206 
10207 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10208 	ill = ILL_START_WALK_V6(&ctx, ipst);
10209 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10210 		/* Make sure the ill isn't going away. */
10211 		if (!ill_check_and_refhold(ill))
10212 			continue;
10213 		rw_exit(&ipst->ips_ill_g_lock);
10214 		/*
10215 		 * Normally we don't have any members on under IPMP interfaces.
10216 		 * We report them as a debugging aid.
10217 		 */
10218 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10219 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10220 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10221 			if (ilm->ilm_zoneid != zoneid &&
10222 			    ilm->ilm_zoneid != ALL_ZONES)
10223 				continue;	/* not this zone */
10224 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10225 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10226 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10227 			if (!snmp_append_data2(mpctl->b_cont,
10228 			    &mp_tail,
10229 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10230 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10231 				    "failed to allocate %u bytes\n",
10232 				    (uint_t)sizeof (ipm6)));
10233 			}
10234 		}
10235 		rw_exit(&ill->ill_mcast_lock);
10236 		ill_refrele(ill);
10237 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10238 	}
10239 	rw_exit(&ipst->ips_ill_g_lock);
10240 
10241 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10242 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10243 	    (int)optp->level, (int)optp->name, (int)optp->len));
10244 	qreply(q, mpctl);
10245 	return (mp2ctl);
10246 }
10247 
10248 /* IP multicast filtered sources */
10249 static mblk_t *
10250 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10251 {
10252 	struct opthdr		*optp;
10253 	mblk_t			*mp2ctl;
10254 	ill_t			*ill;
10255 	ipif_t			*ipif;
10256 	ilm_t			*ilm;
10257 	ip_grpsrc_t		ips;
10258 	mblk_t			*mp_tail = NULL;
10259 	ill_walk_context_t	ctx;
10260 	zoneid_t		zoneid;
10261 	int			i;
10262 	slist_t			*sl;
10263 
10264 	/*
10265 	 * make a copy of the original message
10266 	 */
10267 	mp2ctl = copymsg(mpctl);
10268 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10269 
10270 	/* ipGroupSource table */
10271 	optp = (struct opthdr *)&mpctl->b_rptr[
10272 	    sizeof (struct T_optmgmt_ack)];
10273 	optp->level = MIB2_IP;
10274 	optp->name = EXPER_IP_GROUP_SOURCES;
10275 
10276 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10277 	ill = ILL_START_WALK_V4(&ctx, ipst);
10278 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10279 		/* Make sure the ill isn't going away. */
10280 		if (!ill_check_and_refhold(ill))
10281 			continue;
10282 		rw_exit(&ipst->ips_ill_g_lock);
10283 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10284 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10285 			sl = ilm->ilm_filter;
10286 			if (ilm->ilm_zoneid != zoneid &&
10287 			    ilm->ilm_zoneid != ALL_ZONES)
10288 				continue;
10289 			if (SLIST_IS_EMPTY(sl))
10290 				continue;
10291 
10292 			/* Is there an ipif for ilm_ifaddr? */
10293 			for (ipif = ill->ill_ipif; ipif != NULL;
10294 			    ipif = ipif->ipif_next) {
10295 				if (!IPIF_IS_CONDEMNED(ipif) &&
10296 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10297 				    ilm->ilm_ifaddr != INADDR_ANY)
10298 					break;
10299 			}
10300 			if (ipif != NULL) {
10301 				ipif_get_name(ipif,
10302 				    ips.ipGroupSourceIfIndex.o_bytes,
10303 				    OCTET_LENGTH);
10304 			} else {
10305 				ill_get_name(ill,
10306 				    ips.ipGroupSourceIfIndex.o_bytes,
10307 				    OCTET_LENGTH);
10308 			}
10309 			ips.ipGroupSourceIfIndex.o_length =
10310 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10311 
10312 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10313 			for (i = 0; i < sl->sl_numsrc; i++) {
10314 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10315 					continue;
10316 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10317 				    ips.ipGroupSourceAddress);
10318 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10319 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10320 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10321 					    " failed to allocate %u bytes\n",
10322 					    (uint_t)sizeof (ips)));
10323 				}
10324 			}
10325 		}
10326 		rw_exit(&ill->ill_mcast_lock);
10327 		ill_refrele(ill);
10328 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10329 	}
10330 	rw_exit(&ipst->ips_ill_g_lock);
10331 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10332 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10333 	    (int)optp->level, (int)optp->name, (int)optp->len));
10334 	qreply(q, mpctl);
10335 	return (mp2ctl);
10336 }
10337 
10338 /* IPv6 multicast filtered sources. */
10339 static mblk_t *
10340 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10341 {
10342 	struct opthdr		*optp;
10343 	mblk_t			*mp2ctl;
10344 	ill_t			*ill;
10345 	ilm_t			*ilm;
10346 	ipv6_grpsrc_t		ips6;
10347 	mblk_t			*mp_tail = NULL;
10348 	ill_walk_context_t	ctx;
10349 	zoneid_t		zoneid;
10350 	int			i;
10351 	slist_t			*sl;
10352 
10353 	/*
10354 	 * make a copy of the original message
10355 	 */
10356 	mp2ctl = copymsg(mpctl);
10357 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10358 
10359 	/* ip6GroupMember table */
10360 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10361 	optp->level = MIB2_IP6;
10362 	optp->name = EXPER_IP6_GROUP_SOURCES;
10363 
10364 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10365 	ill = ILL_START_WALK_V6(&ctx, ipst);
10366 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10367 		/* Make sure the ill isn't going away. */
10368 		if (!ill_check_and_refhold(ill))
10369 			continue;
10370 		rw_exit(&ipst->ips_ill_g_lock);
10371 		/*
10372 		 * Normally we don't have any members on under IPMP interfaces.
10373 		 * We report them as a debugging aid.
10374 		 */
10375 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10376 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10377 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10378 			sl = ilm->ilm_filter;
10379 			if (ilm->ilm_zoneid != zoneid &&
10380 			    ilm->ilm_zoneid != ALL_ZONES)
10381 				continue;
10382 			if (SLIST_IS_EMPTY(sl))
10383 				continue;
10384 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10385 			for (i = 0; i < sl->sl_numsrc; i++) {
10386 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10387 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10388 				    (char *)&ips6, (int)sizeof (ips6))) {
10389 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10390 					    "group_src: failed to allocate "
10391 					    "%u bytes\n",
10392 					    (uint_t)sizeof (ips6)));
10393 				}
10394 			}
10395 		}
10396 		rw_exit(&ill->ill_mcast_lock);
10397 		ill_refrele(ill);
10398 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10399 	}
10400 	rw_exit(&ipst->ips_ill_g_lock);
10401 
10402 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10403 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10404 	    (int)optp->level, (int)optp->name, (int)optp->len));
10405 	qreply(q, mpctl);
10406 	return (mp2ctl);
10407 }
10408 
10409 /* Multicast routing virtual interface table. */
10410 static mblk_t *
10411 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10412 {
10413 	struct opthdr		*optp;
10414 	mblk_t			*mp2ctl;
10415 
10416 	/*
10417 	 * make a copy of the original message
10418 	 */
10419 	mp2ctl = copymsg(mpctl);
10420 
10421 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10422 	optp->level = EXPER_DVMRP;
10423 	optp->name = EXPER_DVMRP_VIF;
10424 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10425 		ip0dbg(("ip_mroute_vif: failed\n"));
10426 	}
10427 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10428 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10429 	    (int)optp->level, (int)optp->name, (int)optp->len));
10430 	qreply(q, mpctl);
10431 	return (mp2ctl);
10432 }
10433 
10434 /* Multicast routing table. */
10435 static mblk_t *
10436 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10437 {
10438 	struct opthdr		*optp;
10439 	mblk_t			*mp2ctl;
10440 
10441 	/*
10442 	 * make a copy of the original message
10443 	 */
10444 	mp2ctl = copymsg(mpctl);
10445 
10446 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10447 	optp->level = EXPER_DVMRP;
10448 	optp->name = EXPER_DVMRP_MRT;
10449 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10450 		ip0dbg(("ip_mroute_mrt: failed\n"));
10451 	}
10452 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10453 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10454 	    (int)optp->level, (int)optp->name, (int)optp->len));
10455 	qreply(q, mpctl);
10456 	return (mp2ctl);
10457 }
10458 
10459 /*
10460  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10461  * in one IRE walk.
10462  */
10463 static mblk_t *
10464 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10465     ip_stack_t *ipst)
10466 {
10467 	struct opthdr	*optp;
10468 	mblk_t		*mp2ctl;	/* Returned */
10469 	mblk_t		*mp3ctl;	/* nettomedia */
10470 	mblk_t		*mp4ctl;	/* routeattrs */
10471 	iproutedata_t	ird;
10472 	zoneid_t	zoneid;
10473 
10474 	/*
10475 	 * make copies of the original message
10476 	 *	- mp2ctl is returned unchanged to the caller for his use
10477 	 *	- mpctl is sent upstream as ipRouteEntryTable
10478 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10479 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10480 	 */
10481 	mp2ctl = copymsg(mpctl);
10482 	mp3ctl = copymsg(mpctl);
10483 	mp4ctl = copymsg(mpctl);
10484 	if (mp3ctl == NULL || mp4ctl == NULL) {
10485 		freemsg(mp4ctl);
10486 		freemsg(mp3ctl);
10487 		freemsg(mp2ctl);
10488 		freemsg(mpctl);
10489 		return (NULL);
10490 	}
10491 
10492 	bzero(&ird, sizeof (ird));
10493 
10494 	ird.ird_route.lp_head = mpctl->b_cont;
10495 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10496 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10497 	/*
10498 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10499 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10500 	 * intended a temporary solution until a proper MIB API is provided
10501 	 * that provides complete filtering/caller-opt-in.
10502 	 */
10503 	if (level == EXPER_IP_AND_ALL_IRES)
10504 		ird.ird_flags |= IRD_REPORT_ALL;
10505 
10506 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10507 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10508 
10509 	/* ipRouteEntryTable in mpctl */
10510 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10511 	optp->level = MIB2_IP;
10512 	optp->name = MIB2_IP_ROUTE;
10513 	optp->len = msgdsize(ird.ird_route.lp_head);
10514 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10515 	    (int)optp->level, (int)optp->name, (int)optp->len));
10516 	qreply(q, mpctl);
10517 
10518 	/* ipNetToMediaEntryTable in mp3ctl */
10519 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10520 
10521 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10522 	optp->level = MIB2_IP;
10523 	optp->name = MIB2_IP_MEDIA;
10524 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10525 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10526 	    (int)optp->level, (int)optp->name, (int)optp->len));
10527 	qreply(q, mp3ctl);
10528 
10529 	/* ipRouteAttributeTable in mp4ctl */
10530 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10531 	optp->level = MIB2_IP;
10532 	optp->name = EXPER_IP_RTATTR;
10533 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10534 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10535 	    (int)optp->level, (int)optp->name, (int)optp->len));
10536 	if (optp->len == 0)
10537 		freemsg(mp4ctl);
10538 	else
10539 		qreply(q, mp4ctl);
10540 
10541 	return (mp2ctl);
10542 }
10543 
10544 /*
10545  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10546  * ipv6NetToMediaEntryTable in an NDP walk.
10547  */
10548 static mblk_t *
10549 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10550     ip_stack_t *ipst)
10551 {
10552 	struct opthdr	*optp;
10553 	mblk_t		*mp2ctl;	/* Returned */
10554 	mblk_t		*mp3ctl;	/* nettomedia */
10555 	mblk_t		*mp4ctl;	/* routeattrs */
10556 	iproutedata_t	ird;
10557 	zoneid_t	zoneid;
10558 
10559 	/*
10560 	 * make copies of the original message
10561 	 *	- mp2ctl is returned unchanged to the caller for his use
10562 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10563 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10564 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10565 	 */
10566 	mp2ctl = copymsg(mpctl);
10567 	mp3ctl = copymsg(mpctl);
10568 	mp4ctl = copymsg(mpctl);
10569 	if (mp3ctl == NULL || mp4ctl == NULL) {
10570 		freemsg(mp4ctl);
10571 		freemsg(mp3ctl);
10572 		freemsg(mp2ctl);
10573 		freemsg(mpctl);
10574 		return (NULL);
10575 	}
10576 
10577 	bzero(&ird, sizeof (ird));
10578 
10579 	ird.ird_route.lp_head = mpctl->b_cont;
10580 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10581 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10582 	/*
10583 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10584 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10585 	 * intended a temporary solution until a proper MIB API is provided
10586 	 * that provides complete filtering/caller-opt-in.
10587 	 */
10588 	if (level == EXPER_IP_AND_ALL_IRES)
10589 		ird.ird_flags |= IRD_REPORT_ALL;
10590 
10591 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10592 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10593 
10594 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10595 	optp->level = MIB2_IP6;
10596 	optp->name = MIB2_IP6_ROUTE;
10597 	optp->len = msgdsize(ird.ird_route.lp_head);
10598 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10599 	    (int)optp->level, (int)optp->name, (int)optp->len));
10600 	qreply(q, mpctl);
10601 
10602 	/* ipv6NetToMediaEntryTable in mp3ctl */
10603 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10604 
10605 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10606 	optp->level = MIB2_IP6;
10607 	optp->name = MIB2_IP6_MEDIA;
10608 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10609 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10610 	    (int)optp->level, (int)optp->name, (int)optp->len));
10611 	qreply(q, mp3ctl);
10612 
10613 	/* ipv6RouteAttributeTable in mp4ctl */
10614 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10615 	optp->level = MIB2_IP6;
10616 	optp->name = EXPER_IP_RTATTR;
10617 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10618 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10619 	    (int)optp->level, (int)optp->name, (int)optp->len));
10620 	if (optp->len == 0)
10621 		freemsg(mp4ctl);
10622 	else
10623 		qreply(q, mp4ctl);
10624 
10625 	return (mp2ctl);
10626 }
10627 
10628 /*
10629  * IPv6 mib: One per ill
10630  */
10631 static mblk_t *
10632 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10633     boolean_t legacy_req)
10634 {
10635 	struct opthdr		*optp;
10636 	mblk_t			*mp2ctl;
10637 	ill_t			*ill;
10638 	ill_walk_context_t	ctx;
10639 	mblk_t			*mp_tail = NULL;
10640 	mib2_ipv6AddrEntry_t	mae6;
10641 	mib2_ipIfStatsEntry_t	*ise;
10642 	size_t			ise_size, iae_size;
10643 
10644 	/*
10645 	 * Make a copy of the original message
10646 	 */
10647 	mp2ctl = copymsg(mpctl);
10648 
10649 	/* fixed length IPv6 structure ... */
10650 
10651 	if (legacy_req) {
10652 		ise_size = LEGACY_MIB_SIZE(&ipst->ips_ip6_mib,
10653 		    mib2_ipIfStatsEntry_t);
10654 		iae_size = LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t);
10655 	} else {
10656 		ise_size = sizeof (mib2_ipIfStatsEntry_t);
10657 		iae_size = sizeof (mib2_ipv6AddrEntry_t);
10658 	}
10659 
10660 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10661 	optp->level = MIB2_IP6;
10662 	optp->name = 0;
10663 	/* Include "unknown interface" ip6_mib */
10664 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10665 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10666 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10667 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10668 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10669 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10670 	    ipst->ips_ipv6_def_hops);
10671 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10672 	    sizeof (mib2_ipIfStatsEntry_t));
10673 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10674 	    sizeof (mib2_ipv6AddrEntry_t));
10675 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10676 	    sizeof (mib2_ipv6RouteEntry_t));
10677 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10678 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10679 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10680 	    sizeof (ipv6_member_t));
10681 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10682 	    sizeof (ipv6_grpsrc_t));
10683 
10684 	/*
10685 	 * Synchronize 64- and 32-bit counters
10686 	 */
10687 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10688 	    ipIfStatsHCInReceives);
10689 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10690 	    ipIfStatsHCInDelivers);
10691 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10692 	    ipIfStatsHCOutRequests);
10693 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10694 	    ipIfStatsHCOutForwDatagrams);
10695 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10696 	    ipIfStatsHCOutMcastPkts);
10697 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10698 	    ipIfStatsHCInMcastPkts);
10699 
10700 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10701 	    (char *)&ipst->ips_ip6_mib, (int)ise_size)) {
10702 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10703 		    (uint_t)ise_size));
10704 	} else if (legacy_req) {
10705 		/* Adjust the EntrySize fields for legacy requests. */
10706 		ise =
10707 		    (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr - (int)ise_size);
10708 		SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10709 		SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10710 	}
10711 
10712 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10713 	ill = ILL_START_WALK_V6(&ctx, ipst);
10714 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10715 		ill->ill_ip_mib->ipIfStatsIfIndex =
10716 		    ill->ill_phyint->phyint_ifindex;
10717 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10718 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10719 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10720 		    ill->ill_max_hops);
10721 
10722 		/*
10723 		 * Synchronize 64- and 32-bit counters
10724 		 */
10725 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10726 		    ipIfStatsHCInReceives);
10727 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10728 		    ipIfStatsHCInDelivers);
10729 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10730 		    ipIfStatsHCOutRequests);
10731 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10732 		    ipIfStatsHCOutForwDatagrams);
10733 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10734 		    ipIfStatsHCOutMcastPkts);
10735 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10736 		    ipIfStatsHCInMcastPkts);
10737 
10738 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10739 		    (char *)ill->ill_ip_mib, (int)ise_size)) {
10740 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10741 			"%u bytes\n", (uint_t)ise_size));
10742 		} else if (legacy_req) {
10743 			/* Adjust the EntrySize fields for legacy requests. */
10744 			ise = (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr -
10745 			    (int)ise_size);
10746 			SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10747 			SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10748 		}
10749 	}
10750 	rw_exit(&ipst->ips_ill_g_lock);
10751 
10752 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10753 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10754 	    (int)optp->level, (int)optp->name, (int)optp->len));
10755 	qreply(q, mpctl);
10756 	return (mp2ctl);
10757 }
10758 
10759 /*
10760  * ICMPv6 mib: One per ill
10761  */
10762 static mblk_t *
10763 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10764 {
10765 	struct opthdr		*optp;
10766 	mblk_t			*mp2ctl;
10767 	ill_t			*ill;
10768 	ill_walk_context_t	ctx;
10769 	mblk_t			*mp_tail = NULL;
10770 	/*
10771 	 * Make a copy of the original message
10772 	 */
10773 	mp2ctl = copymsg(mpctl);
10774 
10775 	/* fixed length ICMPv6 structure ... */
10776 
10777 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10778 	optp->level = MIB2_ICMP6;
10779 	optp->name = 0;
10780 	/* Include "unknown interface" icmp6_mib */
10781 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10782 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10783 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10784 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10785 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10786 	    (char *)&ipst->ips_icmp6_mib,
10787 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10788 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10789 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10790 	}
10791 
10792 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10793 	ill = ILL_START_WALK_V6(&ctx, ipst);
10794 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10795 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10796 		    ill->ill_phyint->phyint_ifindex;
10797 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10798 		    (char *)ill->ill_icmp6_mib,
10799 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10800 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10801 			    "%u bytes\n",
10802 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10803 		}
10804 	}
10805 	rw_exit(&ipst->ips_ill_g_lock);
10806 
10807 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10808 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10809 	    (int)optp->level, (int)optp->name, (int)optp->len));
10810 	qreply(q, mpctl);
10811 	return (mp2ctl);
10812 }
10813 
10814 /*
10815  * ire_walk routine to create both ipRouteEntryTable and
10816  * ipRouteAttributeTable in one IRE walk
10817  */
10818 static void
10819 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10820 {
10821 	ill_t				*ill;
10822 	mib2_ipRouteEntry_t		*re;
10823 	mib2_ipAttributeEntry_t		iaes;
10824 	tsol_ire_gw_secattr_t		*attrp;
10825 	tsol_gc_t			*gc = NULL;
10826 	tsol_gcgrp_t			*gcgrp = NULL;
10827 	ip_stack_t			*ipst = ire->ire_ipst;
10828 
10829 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10830 
10831 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10832 		if (ire->ire_testhidden)
10833 			return;
10834 		if (ire->ire_type & IRE_IF_CLONE)
10835 			return;
10836 	}
10837 
10838 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10839 		return;
10840 
10841 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10842 		mutex_enter(&attrp->igsa_lock);
10843 		if ((gc = attrp->igsa_gc) != NULL) {
10844 			gcgrp = gc->gc_grp;
10845 			ASSERT(gcgrp != NULL);
10846 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10847 		}
10848 		mutex_exit(&attrp->igsa_lock);
10849 	}
10850 	/*
10851 	 * Return all IRE types for route table... let caller pick and choose
10852 	 */
10853 	re->ipRouteDest = ire->ire_addr;
10854 	ill = ire->ire_ill;
10855 	re->ipRouteIfIndex.o_length = 0;
10856 	if (ill != NULL) {
10857 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10858 		re->ipRouteIfIndex.o_length =
10859 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10860 	}
10861 	re->ipRouteMetric1 = -1;
10862 	re->ipRouteMetric2 = -1;
10863 	re->ipRouteMetric3 = -1;
10864 	re->ipRouteMetric4 = -1;
10865 
10866 	re->ipRouteNextHop = ire->ire_gateway_addr;
10867 	/* indirect(4), direct(3), or invalid(2) */
10868 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10869 		re->ipRouteType = 2;
10870 	else if (ire->ire_type & IRE_ONLINK)
10871 		re->ipRouteType = 3;
10872 	else
10873 		re->ipRouteType = 4;
10874 
10875 	re->ipRouteProto = -1;
10876 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10877 	re->ipRouteMask = ire->ire_mask;
10878 	re->ipRouteMetric5 = -1;
10879 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10880 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10881 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10882 
10883 	re->ipRouteInfo.re_frag_flag	= 0;
10884 	re->ipRouteInfo.re_rtt		= 0;
10885 	re->ipRouteInfo.re_src_addr	= 0;
10886 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
10887 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10888 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10889 	re->ipRouteInfo.re_flags	= ire->ire_flags;
10890 
10891 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10892 	if (ire->ire_type & IRE_INTERFACE) {
10893 		ire_t *child;
10894 
10895 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10896 		child = ire->ire_dep_children;
10897 		while (child != NULL) {
10898 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10899 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10900 			child = child->ire_dep_sib_next;
10901 		}
10902 		rw_exit(&ipst->ips_ire_dep_lock);
10903 	}
10904 
10905 	if (ire->ire_flags & RTF_DYNAMIC) {
10906 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10907 	} else {
10908 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
10909 	}
10910 
10911 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10912 	    (char *)re, (int)sizeof (*re))) {
10913 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
10914 		    (uint_t)sizeof (*re)));
10915 	}
10916 
10917 	if (gc != NULL) {
10918 		iaes.iae_routeidx = ird->ird_idx;
10919 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10920 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10921 
10922 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10923 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10924 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
10925 			    "bytes\n", (uint_t)sizeof (iaes)));
10926 		}
10927 	}
10928 
10929 	/* bump route index for next pass */
10930 	ird->ird_idx++;
10931 
10932 	kmem_free(re, sizeof (*re));
10933 	if (gcgrp != NULL)
10934 		rw_exit(&gcgrp->gcgrp_rwlock);
10935 }
10936 
10937 /*
10938  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
10939  */
10940 static void
10941 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
10942 {
10943 	ill_t				*ill;
10944 	mib2_ipv6RouteEntry_t		*re;
10945 	mib2_ipAttributeEntry_t		iaes;
10946 	tsol_ire_gw_secattr_t		*attrp;
10947 	tsol_gc_t			*gc = NULL;
10948 	tsol_gcgrp_t			*gcgrp = NULL;
10949 	ip_stack_t			*ipst = ire->ire_ipst;
10950 
10951 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
10952 
10953 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10954 		if (ire->ire_testhidden)
10955 			return;
10956 		if (ire->ire_type & IRE_IF_CLONE)
10957 			return;
10958 	}
10959 
10960 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10961 		return;
10962 
10963 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10964 		mutex_enter(&attrp->igsa_lock);
10965 		if ((gc = attrp->igsa_gc) != NULL) {
10966 			gcgrp = gc->gc_grp;
10967 			ASSERT(gcgrp != NULL);
10968 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10969 		}
10970 		mutex_exit(&attrp->igsa_lock);
10971 	}
10972 	/*
10973 	 * Return all IRE types for route table... let caller pick and choose
10974 	 */
10975 	re->ipv6RouteDest = ire->ire_addr_v6;
10976 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
10977 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
10978 	re->ipv6RouteIfIndex.o_length = 0;
10979 	ill = ire->ire_ill;
10980 	if (ill != NULL) {
10981 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
10982 		re->ipv6RouteIfIndex.o_length =
10983 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
10984 	}
10985 
10986 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
10987 
10988 	mutex_enter(&ire->ire_lock);
10989 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
10990 	mutex_exit(&ire->ire_lock);
10991 
10992 	/* remote(4), local(3), or discard(2) */
10993 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10994 		re->ipv6RouteType = 2;
10995 	else if (ire->ire_type & IRE_ONLINK)
10996 		re->ipv6RouteType = 3;
10997 	else
10998 		re->ipv6RouteType = 4;
10999 
11000 	re->ipv6RouteProtocol	= -1;
11001 	re->ipv6RoutePolicy	= 0;
11002 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
11003 	re->ipv6RouteNextHopRDI	= 0;
11004 	re->ipv6RouteWeight	= 0;
11005 	re->ipv6RouteMetric	= 0;
11006 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11007 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11008 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11009 
11010 	re->ipv6RouteInfo.re_frag_flag	= 0;
11011 	re->ipv6RouteInfo.re_rtt	= 0;
11012 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
11013 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11014 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11015 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
11016 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
11017 
11018 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11019 	if (ire->ire_type & IRE_INTERFACE) {
11020 		ire_t *child;
11021 
11022 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11023 		child = ire->ire_dep_children;
11024 		while (child != NULL) {
11025 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11026 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11027 			child = child->ire_dep_sib_next;
11028 		}
11029 		rw_exit(&ipst->ips_ire_dep_lock);
11030 	}
11031 	if (ire->ire_flags & RTF_DYNAMIC) {
11032 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11033 	} else {
11034 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
11035 	}
11036 
11037 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11038 	    (char *)re, (int)sizeof (*re))) {
11039 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11040 		    (uint_t)sizeof (*re)));
11041 	}
11042 
11043 	if (gc != NULL) {
11044 		iaes.iae_routeidx = ird->ird_idx;
11045 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11046 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11047 
11048 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11049 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11050 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11051 			    "bytes\n", (uint_t)sizeof (iaes)));
11052 		}
11053 	}
11054 
11055 	/* bump route index for next pass */
11056 	ird->ird_idx++;
11057 
11058 	kmem_free(re, sizeof (*re));
11059 	if (gcgrp != NULL)
11060 		rw_exit(&gcgrp->gcgrp_rwlock);
11061 }
11062 
11063 /*
11064  * ncec_walk routine to create ipv6NetToMediaEntryTable
11065  */
11066 static int
11067 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11068 {
11069 	ill_t				*ill;
11070 	mib2_ipv6NetToMediaEntry_t	ntme;
11071 
11072 	ill = ncec->ncec_ill;
11073 	/* skip arpce entries, and loopback ncec entries */
11074 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11075 		return (0);
11076 	/*
11077 	 * Neighbor cache entry attached to IRE with on-link
11078 	 * destination.
11079 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11080 	 */
11081 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11082 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11083 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11084 	if (ncec->ncec_lladdr != NULL) {
11085 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11086 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11087 	}
11088 	/*
11089 	 * Note: Returns ND_* states. Should be:
11090 	 * reachable(1), stale(2), delay(3), probe(4),
11091 	 * invalid(5), unknown(6)
11092 	 */
11093 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11094 	ntme.ipv6NetToMediaLastUpdated = 0;
11095 
11096 	/* other(1), dynamic(2), static(3), local(4) */
11097 	if (NCE_MYADDR(ncec)) {
11098 		ntme.ipv6NetToMediaType = 4;
11099 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11100 		ntme.ipv6NetToMediaType = 1; /* proxy */
11101 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11102 		ntme.ipv6NetToMediaType = 3;
11103 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11104 		ntme.ipv6NetToMediaType = 1;
11105 	} else {
11106 		ntme.ipv6NetToMediaType = 2;
11107 	}
11108 
11109 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11110 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11111 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11112 		    (uint_t)sizeof (ntme)));
11113 	}
11114 	return (0);
11115 }
11116 
11117 int
11118 nce2ace(ncec_t *ncec)
11119 {
11120 	int flags = 0;
11121 
11122 	if (NCE_ISREACHABLE(ncec))
11123 		flags |= ACE_F_RESOLVED;
11124 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11125 		flags |= ACE_F_AUTHORITY;
11126 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11127 		flags |= ACE_F_PUBLISH;
11128 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11129 		flags |= ACE_F_PERMANENT;
11130 	if (NCE_MYADDR(ncec))
11131 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11132 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11133 		flags |= ACE_F_UNVERIFIED;
11134 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11135 		flags |= ACE_F_AUTHORITY;
11136 	if (ncec->ncec_flags & NCE_F_DELAYED)
11137 		flags |= ACE_F_DELAYED;
11138 	return (flags);
11139 }
11140 
11141 /*
11142  * ncec_walk routine to create ipNetToMediaEntryTable
11143  */
11144 static int
11145 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11146 {
11147 	ill_t				*ill;
11148 	mib2_ipNetToMediaEntry_t	ntme;
11149 	const char			*name = "unknown";
11150 	ipaddr_t			ncec_addr;
11151 
11152 	ill = ncec->ncec_ill;
11153 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11154 	    ill->ill_net_type == IRE_LOOPBACK)
11155 		return (0);
11156 
11157 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11158 	name = ill->ill_name;
11159 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11160 	if (NCE_MYADDR(ncec)) {
11161 		ntme.ipNetToMediaType = 4;
11162 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11163 		ntme.ipNetToMediaType = 1;
11164 	} else {
11165 		ntme.ipNetToMediaType = 3;
11166 	}
11167 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11168 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11169 	    ntme.ipNetToMediaIfIndex.o_length);
11170 
11171 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11172 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11173 
11174 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11175 	ncec_addr = INADDR_BROADCAST;
11176 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11177 	    sizeof (ncec_addr));
11178 	/*
11179 	 * map all the flags to the ACE counterpart.
11180 	 */
11181 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11182 
11183 	ntme.ipNetToMediaPhysAddress.o_length =
11184 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11185 
11186 	if (!NCE_ISREACHABLE(ncec))
11187 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11188 	else {
11189 		if (ncec->ncec_lladdr != NULL) {
11190 			bcopy(ncec->ncec_lladdr,
11191 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11192 			    ntme.ipNetToMediaPhysAddress.o_length);
11193 		}
11194 	}
11195 
11196 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11197 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11198 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11199 		    (uint_t)sizeof (ntme)));
11200 	}
11201 	return (0);
11202 }
11203 
11204 /*
11205  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11206  */
11207 /* ARGSUSED */
11208 int
11209 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11210 {
11211 	switch (level) {
11212 	case MIB2_IP:
11213 	case MIB2_ICMP:
11214 		switch (name) {
11215 		default:
11216 			break;
11217 		}
11218 		return (1);
11219 	default:
11220 		return (1);
11221 	}
11222 }
11223 
11224 /*
11225  * When there exists both a 64- and 32-bit counter of a particular type
11226  * (i.e., InReceives), only the 64-bit counters are added.
11227  */
11228 void
11229 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11230 {
11231 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11232 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11233 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11234 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11235 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11236 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11237 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11238 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11239 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11240 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11241 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11242 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11243 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11244 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11245 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11246 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11247 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11248 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11249 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11250 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11251 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11252 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11253 	    o2->ipIfStatsInWrongIPVersion);
11254 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11255 	    o2->ipIfStatsInWrongIPVersion);
11256 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11257 	    o2->ipIfStatsOutSwitchIPVersion);
11258 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11259 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11260 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11261 	    o2->ipIfStatsHCInForwDatagrams);
11262 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11263 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11264 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11265 	    o2->ipIfStatsHCOutForwDatagrams);
11266 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11267 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11268 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11269 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11270 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11271 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11272 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11273 	    o2->ipIfStatsHCOutMcastOctets);
11274 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11275 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11276 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11277 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11278 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11279 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11280 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11281 }
11282 
11283 void
11284 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11285 {
11286 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11287 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11288 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11289 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11290 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11291 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11292 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11293 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11294 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11295 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11296 	    o2->ipv6IfIcmpInRouterSolicits);
11297 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11298 	    o2->ipv6IfIcmpInRouterAdvertisements);
11299 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11300 	    o2->ipv6IfIcmpInNeighborSolicits);
11301 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11302 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11303 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11304 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11305 	    o2->ipv6IfIcmpInGroupMembQueries);
11306 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11307 	    o2->ipv6IfIcmpInGroupMembResponses);
11308 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11309 	    o2->ipv6IfIcmpInGroupMembReductions);
11310 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11311 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11312 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11313 	    o2->ipv6IfIcmpOutDestUnreachs);
11314 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11315 	    o2->ipv6IfIcmpOutAdminProhibs);
11316 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11317 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11318 	    o2->ipv6IfIcmpOutParmProblems);
11319 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11320 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11321 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11322 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11323 	    o2->ipv6IfIcmpOutRouterSolicits);
11324 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11325 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11326 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11327 	    o2->ipv6IfIcmpOutNeighborSolicits);
11328 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11329 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11330 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11331 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11332 	    o2->ipv6IfIcmpOutGroupMembQueries);
11333 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11334 	    o2->ipv6IfIcmpOutGroupMembResponses);
11335 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11336 	    o2->ipv6IfIcmpOutGroupMembReductions);
11337 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11338 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11339 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11340 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11341 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11342 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11343 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11344 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11345 	    o2->ipv6IfIcmpInGroupMembTotal);
11346 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11347 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11348 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11349 	    o2->ipv6IfIcmpInGroupMembBadReports);
11350 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11351 	    o2->ipv6IfIcmpInGroupMembOurReports);
11352 }
11353 
11354 /*
11355  * Called before the options are updated to check if this packet will
11356  * be source routed from here.
11357  * This routine assumes that the options are well formed i.e. that they
11358  * have already been checked.
11359  */
11360 boolean_t
11361 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11362 {
11363 	ipoptp_t	opts;
11364 	uchar_t		*opt;
11365 	uint8_t		optval;
11366 	uint8_t		optlen;
11367 	ipaddr_t	dst;
11368 
11369 	if (IS_SIMPLE_IPH(ipha)) {
11370 		ip2dbg(("not source routed\n"));
11371 		return (B_FALSE);
11372 	}
11373 	dst = ipha->ipha_dst;
11374 	for (optval = ipoptp_first(&opts, ipha);
11375 	    optval != IPOPT_EOL;
11376 	    optval = ipoptp_next(&opts)) {
11377 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11378 		opt = opts.ipoptp_cur;
11379 		optlen = opts.ipoptp_len;
11380 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11381 		    optval, optlen));
11382 		switch (optval) {
11383 			uint32_t off;
11384 		case IPOPT_SSRR:
11385 		case IPOPT_LSRR:
11386 			/*
11387 			 * If dst is one of our addresses and there are some
11388 			 * entries left in the source route return (true).
11389 			 */
11390 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11391 				ip2dbg(("ip_source_routed: not next"
11392 				    " source route 0x%x\n",
11393 				    ntohl(dst)));
11394 				return (B_FALSE);
11395 			}
11396 			off = opt[IPOPT_OFFSET];
11397 			off--;
11398 			if (optlen < IP_ADDR_LEN ||
11399 			    off > optlen - IP_ADDR_LEN) {
11400 				/* End of source route */
11401 				ip1dbg(("ip_source_routed: end of SR\n"));
11402 				return (B_FALSE);
11403 			}
11404 			return (B_TRUE);
11405 		}
11406 	}
11407 	ip2dbg(("not source routed\n"));
11408 	return (B_FALSE);
11409 }
11410 
11411 /*
11412  * ip_unbind is called by the transports to remove a conn from
11413  * the fanout table.
11414  */
11415 void
11416 ip_unbind(conn_t *connp)
11417 {
11418 
11419 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11420 
11421 	if (is_system_labeled() && connp->conn_anon_port) {
11422 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11423 		    connp->conn_mlp_type, connp->conn_proto,
11424 		    ntohs(connp->conn_lport), B_FALSE);
11425 		connp->conn_anon_port = 0;
11426 	}
11427 	connp->conn_mlp_type = mlptSingle;
11428 
11429 	ipcl_hash_remove(connp);
11430 }
11431 
11432 /*
11433  * Used for deciding the MSS size for the upper layer. Thus
11434  * we need to check the outbound policy values in the conn.
11435  */
11436 int
11437 conn_ipsec_length(conn_t *connp)
11438 {
11439 	ipsec_latch_t *ipl;
11440 
11441 	ipl = connp->conn_latch;
11442 	if (ipl == NULL)
11443 		return (0);
11444 
11445 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11446 		return (0);
11447 
11448 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11449 }
11450 
11451 /*
11452  * Returns an estimate of the IPsec headers size. This is used if
11453  * we don't want to call into IPsec to get the exact size.
11454  */
11455 int
11456 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11457 {
11458 	ipsec_action_t *a;
11459 
11460 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11461 		return (0);
11462 
11463 	a = ixa->ixa_ipsec_action;
11464 	if (a == NULL) {
11465 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11466 		a = ixa->ixa_ipsec_policy->ipsp_act;
11467 	}
11468 	ASSERT(a != NULL);
11469 
11470 	return (a->ipa_ovhd);
11471 }
11472 
11473 /*
11474  * If there are any source route options, return the true final
11475  * destination. Otherwise, return the destination.
11476  */
11477 ipaddr_t
11478 ip_get_dst(ipha_t *ipha)
11479 {
11480 	ipoptp_t	opts;
11481 	uchar_t		*opt;
11482 	uint8_t		optval;
11483 	uint8_t		optlen;
11484 	ipaddr_t	dst;
11485 	uint32_t off;
11486 
11487 	dst = ipha->ipha_dst;
11488 
11489 	if (IS_SIMPLE_IPH(ipha))
11490 		return (dst);
11491 
11492 	for (optval = ipoptp_first(&opts, ipha);
11493 	    optval != IPOPT_EOL;
11494 	    optval = ipoptp_next(&opts)) {
11495 		opt = opts.ipoptp_cur;
11496 		optlen = opts.ipoptp_len;
11497 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11498 		switch (optval) {
11499 		case IPOPT_SSRR:
11500 		case IPOPT_LSRR:
11501 			off = opt[IPOPT_OFFSET];
11502 			/*
11503 			 * If one of the conditions is true, it means
11504 			 * end of options and dst already has the right
11505 			 * value.
11506 			 */
11507 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11508 				off = optlen - IP_ADDR_LEN;
11509 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11510 			}
11511 			return (dst);
11512 		default:
11513 			break;
11514 		}
11515 	}
11516 
11517 	return (dst);
11518 }
11519 
11520 /*
11521  * Outbound IP fragmentation routine.
11522  * Assumes the caller has checked whether or not fragmentation should
11523  * be allowed. Here we copy the DF bit from the header to all the generated
11524  * fragments.
11525  */
11526 int
11527 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11528     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11529     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11530 {
11531 	int		i1;
11532 	int		hdr_len;
11533 	mblk_t		*hdr_mp;
11534 	ipha_t		*ipha;
11535 	int		ip_data_end;
11536 	int		len;
11537 	mblk_t		*mp = mp_orig;
11538 	int		offset;
11539 	ill_t		*ill = nce->nce_ill;
11540 	ip_stack_t	*ipst = ill->ill_ipst;
11541 	mblk_t		*carve_mp;
11542 	uint32_t	frag_flag;
11543 	uint_t		priority = mp->b_band;
11544 	int		error = 0;
11545 
11546 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11547 
11548 	if (pkt_len != msgdsize(mp)) {
11549 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11550 		    pkt_len, msgdsize(mp)));
11551 		freemsg(mp);
11552 		return (EINVAL);
11553 	}
11554 
11555 	if (max_frag == 0) {
11556 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11557 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11558 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11559 		freemsg(mp);
11560 		return (EINVAL);
11561 	}
11562 
11563 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11564 	ipha = (ipha_t *)mp->b_rptr;
11565 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11566 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11567 
11568 	/*
11569 	 * Establish the starting offset.  May not be zero if we are fragging
11570 	 * a fragment that is being forwarded.
11571 	 */
11572 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11573 
11574 	/* TODO why is this test needed? */
11575 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11576 		/* TODO: notify ulp somehow */
11577 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11578 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11579 		freemsg(mp);
11580 		return (EINVAL);
11581 	}
11582 
11583 	hdr_len = IPH_HDR_LENGTH(ipha);
11584 	ipha->ipha_hdr_checksum = 0;
11585 
11586 	/*
11587 	 * Establish the number of bytes maximum per frag, after putting
11588 	 * in the header.
11589 	 */
11590 	len = (max_frag - hdr_len) & ~7;
11591 
11592 	/* Get a copy of the header for the trailing frags */
11593 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11594 	    mp);
11595 	if (hdr_mp == NULL) {
11596 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11597 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11598 		freemsg(mp);
11599 		return (ENOBUFS);
11600 	}
11601 
11602 	/* Store the starting offset, with the MoreFrags flag. */
11603 	i1 = offset | IPH_MF | frag_flag;
11604 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11605 
11606 	/* Establish the ending byte offset, based on the starting offset. */
11607 	offset <<= 3;
11608 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11609 
11610 	/* Store the length of the first fragment in the IP header. */
11611 	i1 = len + hdr_len;
11612 	ASSERT(i1 <= IP_MAXPACKET);
11613 	ipha->ipha_length = htons((uint16_t)i1);
11614 
11615 	/*
11616 	 * Compute the IP header checksum for the first frag.  We have to
11617 	 * watch out that we stop at the end of the header.
11618 	 */
11619 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11620 
11621 	/*
11622 	 * Now carve off the first frag.  Note that this will include the
11623 	 * original IP header.
11624 	 */
11625 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11626 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11627 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11628 		freeb(hdr_mp);
11629 		freemsg(mp_orig);
11630 		return (ENOBUFS);
11631 	}
11632 
11633 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11634 
11635 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11636 	    ixa_cookie);
11637 	if (error != 0 && error != EWOULDBLOCK) {
11638 		/* No point in sending the other fragments */
11639 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11640 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11641 		freeb(hdr_mp);
11642 		freemsg(mp_orig);
11643 		return (error);
11644 	}
11645 
11646 	/* No need to redo state machine in loop */
11647 	ixaflags &= ~IXAF_REACH_CONF;
11648 
11649 	/* Advance the offset to the second frag starting point. */
11650 	offset += len;
11651 	/*
11652 	 * Update hdr_len from the copied header - there might be less options
11653 	 * in the later fragments.
11654 	 */
11655 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11656 	/* Loop until done. */
11657 	for (;;) {
11658 		uint16_t	offset_and_flags;
11659 		uint16_t	ip_len;
11660 
11661 		if (ip_data_end - offset > len) {
11662 			/*
11663 			 * Carve off the appropriate amount from the original
11664 			 * datagram.
11665 			 */
11666 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11667 				mp = NULL;
11668 				break;
11669 			}
11670 			/*
11671 			 * More frags after this one.  Get another copy
11672 			 * of the header.
11673 			 */
11674 			if (carve_mp->b_datap->db_ref == 1 &&
11675 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11676 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11677 				/* Inline IP header */
11678 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11679 				    hdr_mp->b_rptr;
11680 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11681 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11682 				mp = carve_mp;
11683 			} else {
11684 				if (!(mp = copyb(hdr_mp))) {
11685 					freemsg(carve_mp);
11686 					break;
11687 				}
11688 				/* Get priority marking, if any. */
11689 				mp->b_band = priority;
11690 				mp->b_cont = carve_mp;
11691 			}
11692 			ipha = (ipha_t *)mp->b_rptr;
11693 			offset_and_flags = IPH_MF;
11694 		} else {
11695 			/*
11696 			 * Last frag.  Consume the header. Set len to
11697 			 * the length of this last piece.
11698 			 */
11699 			len = ip_data_end - offset;
11700 
11701 			/*
11702 			 * Carve off the appropriate amount from the original
11703 			 * datagram.
11704 			 */
11705 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11706 				mp = NULL;
11707 				break;
11708 			}
11709 			if (carve_mp->b_datap->db_ref == 1 &&
11710 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11711 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11712 				/* Inline IP header */
11713 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11714 				    hdr_mp->b_rptr;
11715 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11716 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11717 				mp = carve_mp;
11718 				freeb(hdr_mp);
11719 				hdr_mp = mp;
11720 			} else {
11721 				mp = hdr_mp;
11722 				/* Get priority marking, if any. */
11723 				mp->b_band = priority;
11724 				mp->b_cont = carve_mp;
11725 			}
11726 			ipha = (ipha_t *)mp->b_rptr;
11727 			/* A frag of a frag might have IPH_MF non-zero */
11728 			offset_and_flags =
11729 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11730 			    IPH_MF;
11731 		}
11732 		offset_and_flags |= (uint16_t)(offset >> 3);
11733 		offset_and_flags |= (uint16_t)frag_flag;
11734 		/* Store the offset and flags in the IP header. */
11735 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11736 
11737 		/* Store the length in the IP header. */
11738 		ip_len = (uint16_t)(len + hdr_len);
11739 		ipha->ipha_length = htons(ip_len);
11740 
11741 		/*
11742 		 * Set the IP header checksum.	Note that mp is just
11743 		 * the header, so this is easy to pass to ip_csum.
11744 		 */
11745 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11746 
11747 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11748 
11749 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11750 		    nolzid, ixa_cookie);
11751 		/* All done if we just consumed the hdr_mp. */
11752 		if (mp == hdr_mp) {
11753 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11754 			return (error);
11755 		}
11756 		if (error != 0 && error != EWOULDBLOCK) {
11757 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11758 			    mblk_t *, hdr_mp);
11759 			/* No point in sending the other fragments */
11760 			break;
11761 		}
11762 
11763 		/* Otherwise, advance and loop. */
11764 		offset += len;
11765 	}
11766 	/* Clean up following allocation failure. */
11767 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11768 	ip_drop_output("FragFails: loop ended", NULL, ill);
11769 	if (mp != hdr_mp)
11770 		freeb(hdr_mp);
11771 	if (mp != mp_orig)
11772 		freemsg(mp_orig);
11773 	return (error);
11774 }
11775 
11776 /*
11777  * Copy the header plus those options which have the copy bit set
11778  */
11779 static mblk_t *
11780 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11781     mblk_t *src)
11782 {
11783 	mblk_t	*mp;
11784 	uchar_t	*up;
11785 
11786 	/*
11787 	 * Quick check if we need to look for options without the copy bit
11788 	 * set
11789 	 */
11790 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11791 	if (!mp)
11792 		return (mp);
11793 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11794 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11795 		bcopy(rptr, mp->b_rptr, hdr_len);
11796 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11797 		return (mp);
11798 	}
11799 	up  = mp->b_rptr;
11800 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11801 	up += IP_SIMPLE_HDR_LENGTH;
11802 	rptr += IP_SIMPLE_HDR_LENGTH;
11803 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11804 	while (hdr_len > 0) {
11805 		uint32_t optval;
11806 		uint32_t optlen;
11807 
11808 		optval = *rptr;
11809 		if (optval == IPOPT_EOL)
11810 			break;
11811 		if (optval == IPOPT_NOP)
11812 			optlen = 1;
11813 		else
11814 			optlen = rptr[1];
11815 		if (optval & IPOPT_COPY) {
11816 			bcopy(rptr, up, optlen);
11817 			up += optlen;
11818 		}
11819 		rptr += optlen;
11820 		hdr_len -= optlen;
11821 	}
11822 	/*
11823 	 * Make sure that we drop an even number of words by filling
11824 	 * with EOL to the next word boundary.
11825 	 */
11826 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11827 	    hdr_len & 0x3; hdr_len++)
11828 		*up++ = IPOPT_EOL;
11829 	mp->b_wptr = up;
11830 	/* Update header length */
11831 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11832 	return (mp);
11833 }
11834 
11835 /*
11836  * Update any source route, record route, or timestamp options when
11837  * sending a packet back to ourselves.
11838  * Check that we are at end of strict source route.
11839  * The options have been sanity checked by ip_output_options().
11840  */
11841 void
11842 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11843 {
11844 	ipoptp_t	opts;
11845 	uchar_t		*opt;
11846 	uint8_t		optval;
11847 	uint8_t		optlen;
11848 	ipaddr_t	dst;
11849 	uint32_t	ts;
11850 	timestruc_t	now;
11851 
11852 	for (optval = ipoptp_first(&opts, ipha);
11853 	    optval != IPOPT_EOL;
11854 	    optval = ipoptp_next(&opts)) {
11855 		opt = opts.ipoptp_cur;
11856 		optlen = opts.ipoptp_len;
11857 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11858 		switch (optval) {
11859 			uint32_t off;
11860 		case IPOPT_SSRR:
11861 		case IPOPT_LSRR:
11862 			off = opt[IPOPT_OFFSET];
11863 			off--;
11864 			if (optlen < IP_ADDR_LEN ||
11865 			    off > optlen - IP_ADDR_LEN) {
11866 				/* End of source route */
11867 				break;
11868 			}
11869 			/*
11870 			 * This will only happen if two consecutive entries
11871 			 * in the source route contains our address or if
11872 			 * it is a packet with a loose source route which
11873 			 * reaches us before consuming the whole source route
11874 			 */
11875 
11876 			if (optval == IPOPT_SSRR) {
11877 				return;
11878 			}
11879 			/*
11880 			 * Hack: instead of dropping the packet truncate the
11881 			 * source route to what has been used by filling the
11882 			 * rest with IPOPT_NOP.
11883 			 */
11884 			opt[IPOPT_OLEN] = (uint8_t)off;
11885 			while (off < optlen) {
11886 				opt[off++] = IPOPT_NOP;
11887 			}
11888 			break;
11889 		case IPOPT_RR:
11890 			off = opt[IPOPT_OFFSET];
11891 			off--;
11892 			if (optlen < IP_ADDR_LEN ||
11893 			    off > optlen - IP_ADDR_LEN) {
11894 				/* No more room - ignore */
11895 				ip1dbg((
11896 				    "ip_output_local_options: end of RR\n"));
11897 				break;
11898 			}
11899 			dst = htonl(INADDR_LOOPBACK);
11900 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11901 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11902 			break;
11903 		case IPOPT_TS:
11904 			/* Insert timestamp if there is romm */
11905 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11906 			case IPOPT_TS_TSONLY:
11907 				off = IPOPT_TS_TIMELEN;
11908 				break;
11909 			case IPOPT_TS_PRESPEC:
11910 			case IPOPT_TS_PRESPEC_RFC791:
11911 				/* Verify that the address matched */
11912 				off = opt[IPOPT_OFFSET] - 1;
11913 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
11914 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11915 					/* Not for us */
11916 					break;
11917 				}
11918 				/* FALLTHRU */
11919 			case IPOPT_TS_TSANDADDR:
11920 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
11921 				break;
11922 			default:
11923 				/*
11924 				 * ip_*put_options should have already
11925 				 * dropped this packet.
11926 				 */
11927 				cmn_err(CE_PANIC, "ip_output_local_options: "
11928 				    "unknown IT - bug in ip_output_options?\n");
11929 				return;	/* Keep "lint" happy */
11930 			}
11931 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
11932 				/* Increase overflow counter */
11933 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
11934 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
11935 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
11936 				    (off << 4);
11937 				break;
11938 			}
11939 			off = opt[IPOPT_OFFSET] - 1;
11940 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11941 			case IPOPT_TS_PRESPEC:
11942 			case IPOPT_TS_PRESPEC_RFC791:
11943 			case IPOPT_TS_TSANDADDR:
11944 				dst = htonl(INADDR_LOOPBACK);
11945 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11946 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11947 				/* FALLTHRU */
11948 			case IPOPT_TS_TSONLY:
11949 				off = opt[IPOPT_OFFSET] - 1;
11950 				/* Compute # of milliseconds since midnight */
11951 				gethrestime(&now);
11952 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
11953 				    now.tv_nsec / (NANOSEC / MILLISEC);
11954 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
11955 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
11956 				break;
11957 			}
11958 			break;
11959 		}
11960 	}
11961 }
11962 
11963 /*
11964  * Prepend an M_DATA fastpath header, and if none present prepend a
11965  * DL_UNITDATA_REQ. Frees the mblk on failure.
11966  *
11967  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
11968  * If there is a change to them, the nce will be deleted (condemned) and
11969  * a new nce_t will be created when packets are sent. Thus we need no locks
11970  * to access those fields.
11971  *
11972  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
11973  * we place b_band in dl_priority.dl_max.
11974  */
11975 static mblk_t *
11976 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
11977 {
11978 	uint_t	hlen;
11979 	mblk_t *mp1;
11980 	uint_t	priority;
11981 	uchar_t *rptr;
11982 
11983 	rptr = mp->b_rptr;
11984 
11985 	ASSERT(DB_TYPE(mp) == M_DATA);
11986 	priority = mp->b_band;
11987 
11988 	ASSERT(nce != NULL);
11989 	if ((mp1 = nce->nce_fp_mp) != NULL) {
11990 		hlen = MBLKL(mp1);
11991 		/*
11992 		 * Check if we have enough room to prepend fastpath
11993 		 * header
11994 		 */
11995 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
11996 			rptr -= hlen;
11997 			bcopy(mp1->b_rptr, rptr, hlen);
11998 			/*
11999 			 * Set the b_rptr to the start of the link layer
12000 			 * header
12001 			 */
12002 			mp->b_rptr = rptr;
12003 			return (mp);
12004 		}
12005 		mp1 = copyb(mp1);
12006 		if (mp1 == NULL) {
12007 			ill_t *ill = nce->nce_ill;
12008 
12009 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12010 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12011 			freemsg(mp);
12012 			return (NULL);
12013 		}
12014 		mp1->b_band = priority;
12015 		mp1->b_cont = mp;
12016 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12017 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12018 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12019 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12020 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12021 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12022 		/*
12023 		 * XXX disable ICK_VALID and compute checksum
12024 		 * here; can happen if nce_fp_mp changes and
12025 		 * it can't be copied now due to insufficient
12026 		 * space. (unlikely, fp mp can change, but it
12027 		 * does not increase in length)
12028 		 */
12029 		return (mp1);
12030 	}
12031 	mp1 = copyb(nce->nce_dlur_mp);
12032 
12033 	if (mp1 == NULL) {
12034 		ill_t *ill = nce->nce_ill;
12035 
12036 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12037 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12038 		freemsg(mp);
12039 		return (NULL);
12040 	}
12041 	mp1->b_cont = mp;
12042 	if (priority != 0) {
12043 		mp1->b_band = priority;
12044 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12045 		    priority;
12046 	}
12047 	return (mp1);
12048 #undef rptr
12049 }
12050 
12051 /*
12052  * Finish the outbound IPsec processing. This function is called from
12053  * ipsec_out_process() if the IPsec packet was processed
12054  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12055  * asynchronously.
12056  *
12057  * This is common to IPv4 and IPv6.
12058  */
12059 int
12060 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12061 {
12062 	iaflags_t	ixaflags = ixa->ixa_flags;
12063 	uint_t		pktlen;
12064 
12065 
12066 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12067 	if (ixaflags & IXAF_IS_IPV4) {
12068 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12069 
12070 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12071 		pktlen = ntohs(ipha->ipha_length);
12072 	} else {
12073 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12074 
12075 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12076 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12077 	}
12078 
12079 	/*
12080 	 * We release any hard reference on the SAs here to make
12081 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12082 	 * on the SAs.
12083 	 * If in the future we want the hard latching of the SAs in the
12084 	 * ip_xmit_attr_t then we should remove this.
12085 	 */
12086 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12087 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12088 		ixa->ixa_ipsec_esp_sa = NULL;
12089 	}
12090 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12091 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12092 		ixa->ixa_ipsec_ah_sa = NULL;
12093 	}
12094 
12095 	/* Do we need to fragment? */
12096 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12097 	    pktlen > ixa->ixa_fragsize) {
12098 		if (ixaflags & IXAF_IS_IPV4) {
12099 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12100 			/*
12101 			 * We check for the DF case in ipsec_out_process
12102 			 * hence this only handles the non-DF case.
12103 			 */
12104 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12105 			    pktlen, ixa->ixa_fragsize,
12106 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12107 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12108 			    &ixa->ixa_cookie));
12109 		} else {
12110 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12111 			if (mp == NULL) {
12112 				/* MIB and ip_drop_output already done */
12113 				return (ENOMEM);
12114 			}
12115 			pktlen += sizeof (ip6_frag_t);
12116 			if (pktlen > ixa->ixa_fragsize) {
12117 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12118 				    ixa->ixa_flags, pktlen,
12119 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12120 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12121 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12122 			}
12123 		}
12124 	}
12125 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12126 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12127 	    ixa->ixa_no_loop_zoneid, NULL));
12128 }
12129 
12130 /*
12131  * Finish the inbound IPsec processing. This function is called from
12132  * ipsec_out_process() if the IPsec packet was processed
12133  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12134  * asynchronously.
12135  *
12136  * This is common to IPv4 and IPv6.
12137  */
12138 void
12139 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12140 {
12141 	iaflags_t	iraflags = ira->ira_flags;
12142 
12143 	/* Length might have changed */
12144 	if (iraflags & IRAF_IS_IPV4) {
12145 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12146 
12147 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12148 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12149 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12150 		ira->ira_protocol = ipha->ipha_protocol;
12151 
12152 		ip_fanout_v4(mp, ipha, ira);
12153 	} else {
12154 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12155 		uint8_t		*nexthdrp;
12156 
12157 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12158 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12159 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12160 		    &nexthdrp)) {
12161 			/* Malformed packet */
12162 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12163 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12164 			freemsg(mp);
12165 			return;
12166 		}
12167 		ira->ira_protocol = *nexthdrp;
12168 		ip_fanout_v6(mp, ip6h, ira);
12169 	}
12170 }
12171 
12172 /*
12173  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12174  *
12175  * If this function returns B_TRUE, the requested SA's have been filled
12176  * into the ixa_ipsec_*_sa pointers.
12177  *
12178  * If the function returns B_FALSE, the packet has been "consumed", most
12179  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12180  *
12181  * The SA references created by the protocol-specific "select"
12182  * function will be released in ip_output_post_ipsec.
12183  */
12184 static boolean_t
12185 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12186 {
12187 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12188 	ipsec_policy_t *pp;
12189 	ipsec_action_t *ap;
12190 
12191 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12192 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12193 	    (ixa->ixa_ipsec_action != NULL));
12194 
12195 	ap = ixa->ixa_ipsec_action;
12196 	if (ap == NULL) {
12197 		pp = ixa->ixa_ipsec_policy;
12198 		ASSERT(pp != NULL);
12199 		ap = pp->ipsp_act;
12200 		ASSERT(ap != NULL);
12201 	}
12202 
12203 	/*
12204 	 * We have an action.  now, let's select SA's.
12205 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12206 	 * be cached in the conn_t.
12207 	 */
12208 	if (ap->ipa_want_esp) {
12209 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12210 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12211 			    IPPROTO_ESP);
12212 		}
12213 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12214 	}
12215 
12216 	if (ap->ipa_want_ah) {
12217 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12218 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12219 			    IPPROTO_AH);
12220 		}
12221 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12222 		/*
12223 		 * The ESP and AH processing order needs to be preserved
12224 		 * when both protocols are required (ESP should be applied
12225 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12226 		 * when both ESP and AH are required, and an AH ACQUIRE
12227 		 * is needed.
12228 		 */
12229 		if (ap->ipa_want_esp && need_ah_acquire)
12230 			need_esp_acquire = B_TRUE;
12231 	}
12232 
12233 	/*
12234 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12235 	 * Release SAs that got referenced, but will not be used until we
12236 	 * acquire _all_ of the SAs we need.
12237 	 */
12238 	if (need_ah_acquire || need_esp_acquire) {
12239 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12240 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12241 			ixa->ixa_ipsec_ah_sa = NULL;
12242 		}
12243 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12244 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12245 			ixa->ixa_ipsec_esp_sa = NULL;
12246 		}
12247 
12248 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12249 		return (B_FALSE);
12250 	}
12251 
12252 	return (B_TRUE);
12253 }
12254 
12255 /*
12256  * Handle IPsec output processing.
12257  * This function is only entered once for a given packet.
12258  * We try to do things synchronously, but if we need to have user-level
12259  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12260  * will be completed
12261  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12262  *  - when asynchronous ESP is done it will do AH
12263  *
12264  * In all cases we come back in ip_output_post_ipsec() to fragment and
12265  * send out the packet.
12266  */
12267 int
12268 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12269 {
12270 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12271 	ip_stack_t	*ipst = ixa->ixa_ipst;
12272 	ipsec_stack_t	*ipss;
12273 	ipsec_policy_t	*pp;
12274 	ipsec_action_t	*ap;
12275 
12276 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12277 
12278 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12279 	    (ixa->ixa_ipsec_action != NULL));
12280 
12281 	ipss = ipst->ips_netstack->netstack_ipsec;
12282 	if (!ipsec_loaded(ipss)) {
12283 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12284 		ip_drop_packet(mp, B_TRUE, ill,
12285 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12286 		    &ipss->ipsec_dropper);
12287 		return (ENOTSUP);
12288 	}
12289 
12290 	ap = ixa->ixa_ipsec_action;
12291 	if (ap == NULL) {
12292 		pp = ixa->ixa_ipsec_policy;
12293 		ASSERT(pp != NULL);
12294 		ap = pp->ipsp_act;
12295 		ASSERT(ap != NULL);
12296 	}
12297 
12298 	/* Handle explicit drop action and bypass. */
12299 	switch (ap->ipa_act.ipa_type) {
12300 	case IPSEC_ACT_DISCARD:
12301 	case IPSEC_ACT_REJECT:
12302 		ip_drop_packet(mp, B_FALSE, ill,
12303 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12304 		return (EHOSTUNREACH);	/* IPsec policy failure */
12305 	case IPSEC_ACT_BYPASS:
12306 		return (ip_output_post_ipsec(mp, ixa));
12307 	}
12308 
12309 	/*
12310 	 * The order of processing is first insert a IP header if needed.
12311 	 * Then insert the ESP header and then the AH header.
12312 	 */
12313 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12314 		/*
12315 		 * First get the outer IP header before sending
12316 		 * it to ESP.
12317 		 */
12318 		ipha_t *oipha, *iipha;
12319 		mblk_t *outer_mp, *inner_mp;
12320 
12321 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12322 			(void) mi_strlog(ill->ill_rq, 0,
12323 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12324 			    "ipsec_out_process: "
12325 			    "Self-Encapsulation failed: Out of memory\n");
12326 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12327 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12328 			freemsg(mp);
12329 			return (ENOBUFS);
12330 		}
12331 		inner_mp = mp;
12332 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12333 		oipha = (ipha_t *)outer_mp->b_rptr;
12334 		iipha = (ipha_t *)inner_mp->b_rptr;
12335 		*oipha = *iipha;
12336 		outer_mp->b_wptr += sizeof (ipha_t);
12337 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12338 		    sizeof (ipha_t));
12339 		oipha->ipha_protocol = IPPROTO_ENCAP;
12340 		oipha->ipha_version_and_hdr_length =
12341 		    IP_SIMPLE_HDR_VERSION;
12342 		oipha->ipha_hdr_checksum = 0;
12343 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12344 		outer_mp->b_cont = inner_mp;
12345 		mp = outer_mp;
12346 
12347 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12348 	}
12349 
12350 	/* If we need to wait for a SA then we can't return any errno */
12351 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12352 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12353 	    !ipsec_out_select_sa(mp, ixa))
12354 		return (0);
12355 
12356 	/*
12357 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12358 	 * to do the heavy lifting.
12359 	 */
12360 	if (ap->ipa_want_esp) {
12361 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12362 
12363 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12364 		if (mp == NULL) {
12365 			/*
12366 			 * Either it failed or is pending. In the former case
12367 			 * ipIfStatsInDiscards was increased.
12368 			 */
12369 			return (0);
12370 		}
12371 	}
12372 
12373 	if (ap->ipa_want_ah) {
12374 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12375 
12376 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12377 		if (mp == NULL) {
12378 			/*
12379 			 * Either it failed or is pending. In the former case
12380 			 * ipIfStatsInDiscards was increased.
12381 			 */
12382 			return (0);
12383 		}
12384 	}
12385 	/*
12386 	 * We are done with IPsec processing. Send it over
12387 	 * the wire.
12388 	 */
12389 	return (ip_output_post_ipsec(mp, ixa));
12390 }
12391 
12392 /*
12393  * ioctls that go through a down/up sequence may need to wait for the down
12394  * to complete. This involves waiting for the ire and ipif refcnts to go down
12395  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12396  */
12397 /* ARGSUSED */
12398 void
12399 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12400 {
12401 	struct iocblk *iocp;
12402 	mblk_t *mp1;
12403 	ip_ioctl_cmd_t *ipip;
12404 	int err;
12405 	sin_t	*sin;
12406 	struct lifreq *lifr;
12407 	struct ifreq *ifr;
12408 
12409 	iocp = (struct iocblk *)mp->b_rptr;
12410 	ASSERT(ipsq != NULL);
12411 	/* Existence of mp1 verified in ip_wput_nondata */
12412 	mp1 = mp->b_cont->b_cont;
12413 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12414 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12415 		/*
12416 		 * Special case where ipx_current_ipif is not set:
12417 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12418 		 * We are here as were not able to complete the operation in
12419 		 * ipif_set_values because we could not become exclusive on
12420 		 * the new ipsq.
12421 		 */
12422 		ill_t *ill = q->q_ptr;
12423 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12424 	}
12425 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12426 
12427 	if (ipip->ipi_cmd_type == IF_CMD) {
12428 		/* This a old style SIOC[GS]IF* command */
12429 		ifr = (struct ifreq *)mp1->b_rptr;
12430 		sin = (sin_t *)&ifr->ifr_addr;
12431 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12432 		/* This a new style SIOC[GS]LIF* command */
12433 		lifr = (struct lifreq *)mp1->b_rptr;
12434 		sin = (sin_t *)&lifr->lifr_addr;
12435 	} else {
12436 		sin = NULL;
12437 	}
12438 
12439 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12440 	    q, mp, ipip, mp1->b_rptr);
12441 
12442 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12443 	    int, ipip->ipi_cmd,
12444 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12445 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12446 
12447 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12448 }
12449 
12450 /*
12451  * ioctl processing
12452  *
12453  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12454  * the ioctl command in the ioctl tables, determines the copyin data size
12455  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12456  *
12457  * ioctl processing then continues when the M_IOCDATA makes its way down to
12458  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12459  * associated 'conn' is refheld till the end of the ioctl and the general
12460  * ioctl processing function ip_process_ioctl() is called to extract the
12461  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12462  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12463  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12464  * is used to extract the ioctl's arguments.
12465  *
12466  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12467  * so goes thru the serialization primitive ipsq_try_enter. Then the
12468  * appropriate function to handle the ioctl is called based on the entry in
12469  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12470  * which also refreleases the 'conn' that was refheld at the start of the
12471  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12472  *
12473  * Many exclusive ioctls go thru an internal down up sequence as part of
12474  * the operation. For example an attempt to change the IP address of an
12475  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12476  * does all the cleanup such as deleting all ires that use this address.
12477  * Then we need to wait till all references to the interface go away.
12478  */
12479 void
12480 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12481 {
12482 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12483 	ip_ioctl_cmd_t *ipip = arg;
12484 	ip_extract_func_t *extract_funcp;
12485 	cmd_info_t ci;
12486 	int err;
12487 	boolean_t entered_ipsq = B_FALSE;
12488 
12489 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12490 
12491 	if (ipip == NULL)
12492 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12493 
12494 	/*
12495 	 * SIOCLIFADDIF needs to go thru a special path since the
12496 	 * ill may not exist yet. This happens in the case of lo0
12497 	 * which is created using this ioctl.
12498 	 */
12499 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12500 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12501 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12502 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12503 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12504 		return;
12505 	}
12506 
12507 	ci.ci_ipif = NULL;
12508 	switch (ipip->ipi_cmd_type) {
12509 	case MISC_CMD:
12510 	case MSFILT_CMD:
12511 		/*
12512 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12513 		 */
12514 		if (ipip->ipi_cmd == IF_UNITSEL) {
12515 			/* ioctl comes down the ill */
12516 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12517 			ipif_refhold(ci.ci_ipif);
12518 		}
12519 		err = 0;
12520 		ci.ci_sin = NULL;
12521 		ci.ci_sin6 = NULL;
12522 		ci.ci_lifr = NULL;
12523 		extract_funcp = NULL;
12524 		break;
12525 
12526 	case IF_CMD:
12527 	case LIF_CMD:
12528 		extract_funcp = ip_extract_lifreq;
12529 		break;
12530 
12531 	case ARP_CMD:
12532 	case XARP_CMD:
12533 		extract_funcp = ip_extract_arpreq;
12534 		break;
12535 
12536 	default:
12537 		ASSERT(0);
12538 	}
12539 
12540 	if (extract_funcp != NULL) {
12541 		err = (*extract_funcp)(q, mp, ipip, &ci);
12542 		if (err != 0) {
12543 			DTRACE_PROBE4(ipif__ioctl,
12544 			    char *, "ip_process_ioctl finish err",
12545 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12546 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12547 			return;
12548 		}
12549 
12550 		/*
12551 		 * All of the extraction functions return a refheld ipif.
12552 		 */
12553 		ASSERT(ci.ci_ipif != NULL);
12554 	}
12555 
12556 	if (!(ipip->ipi_flags & IPI_WR)) {
12557 		/*
12558 		 * A return value of EINPROGRESS means the ioctl is
12559 		 * either queued and waiting for some reason or has
12560 		 * already completed.
12561 		 */
12562 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12563 		    ci.ci_lifr);
12564 		if (ci.ci_ipif != NULL) {
12565 			DTRACE_PROBE4(ipif__ioctl,
12566 			    char *, "ip_process_ioctl finish RD",
12567 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12568 			    ipif_t *, ci.ci_ipif);
12569 			ipif_refrele(ci.ci_ipif);
12570 		} else {
12571 			DTRACE_PROBE4(ipif__ioctl,
12572 			    char *, "ip_process_ioctl finish RD",
12573 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12574 		}
12575 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12576 		return;
12577 	}
12578 
12579 	ASSERT(ci.ci_ipif != NULL);
12580 
12581 	/*
12582 	 * If ipsq is non-NULL, we are already being called exclusively
12583 	 */
12584 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12585 	if (ipsq == NULL) {
12586 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12587 		    NEW_OP, B_TRUE);
12588 		if (ipsq == NULL) {
12589 			ipif_refrele(ci.ci_ipif);
12590 			return;
12591 		}
12592 		entered_ipsq = B_TRUE;
12593 	}
12594 	/*
12595 	 * Release the ipif so that ipif_down and friends that wait for
12596 	 * references to go away are not misled about the current ipif_refcnt
12597 	 * values. We are writer so we can access the ipif even after releasing
12598 	 * the ipif.
12599 	 */
12600 	ipif_refrele(ci.ci_ipif);
12601 
12602 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12603 
12604 	/*
12605 	 * A return value of EINPROGRESS means the ioctl is
12606 	 * either queued and waiting for some reason or has
12607 	 * already completed.
12608 	 */
12609 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12610 
12611 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12612 	    int, ipip->ipi_cmd,
12613 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12614 	    ipif_t *, ci.ci_ipif);
12615 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12616 
12617 	if (entered_ipsq)
12618 		ipsq_exit(ipsq);
12619 }
12620 
12621 /*
12622  * Complete the ioctl. Typically ioctls use the mi package and need to
12623  * do mi_copyout/mi_copy_done.
12624  */
12625 void
12626 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12627 {
12628 	conn_t	*connp = NULL;
12629 
12630 	if (err == EINPROGRESS)
12631 		return;
12632 
12633 	if (CONN_Q(q)) {
12634 		connp = Q_TO_CONN(q);
12635 		ASSERT(connp->conn_ref >= 2);
12636 	}
12637 
12638 	switch (mode) {
12639 	case COPYOUT:
12640 		if (err == 0)
12641 			mi_copyout(q, mp);
12642 		else
12643 			mi_copy_done(q, mp, err);
12644 		break;
12645 
12646 	case NO_COPYOUT:
12647 		mi_copy_done(q, mp, err);
12648 		break;
12649 
12650 	default:
12651 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12652 		break;
12653 	}
12654 
12655 	/*
12656 	 * The conn refhold and ioctlref placed on the conn at the start of the
12657 	 * ioctl are released here.
12658 	 */
12659 	if (connp != NULL) {
12660 		CONN_DEC_IOCTLREF(connp);
12661 		CONN_OPER_PENDING_DONE(connp);
12662 	}
12663 
12664 	if (ipsq != NULL)
12665 		ipsq_current_finish(ipsq);
12666 }
12667 
12668 /* Handles all non data messages */
12669 void
12670 ip_wput_nondata(queue_t *q, mblk_t *mp)
12671 {
12672 	mblk_t		*mp1;
12673 	struct iocblk	*iocp;
12674 	ip_ioctl_cmd_t	*ipip;
12675 	conn_t		*connp;
12676 	cred_t		*cr;
12677 	char		*proto_str;
12678 
12679 	if (CONN_Q(q))
12680 		connp = Q_TO_CONN(q);
12681 	else
12682 		connp = NULL;
12683 
12684 	switch (DB_TYPE(mp)) {
12685 	case M_IOCTL:
12686 		/*
12687 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12688 		 * will arrange to copy in associated control structures.
12689 		 */
12690 		ip_sioctl_copyin_setup(q, mp);
12691 		return;
12692 	case M_IOCDATA:
12693 		/*
12694 		 * Ensure that this is associated with one of our trans-
12695 		 * parent ioctls.  If it's not ours, discard it if we're
12696 		 * running as a driver, or pass it on if we're a module.
12697 		 */
12698 		iocp = (struct iocblk *)mp->b_rptr;
12699 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12700 		if (ipip == NULL) {
12701 			if (q->q_next == NULL) {
12702 				goto nak;
12703 			} else {
12704 				putnext(q, mp);
12705 			}
12706 			return;
12707 		}
12708 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12709 			/*
12710 			 * The ioctl is one we recognise, but is not consumed
12711 			 * by IP as a module and we are a module, so we drop
12712 			 */
12713 			goto nak;
12714 		}
12715 
12716 		/* IOCTL continuation following copyin or copyout. */
12717 		if (mi_copy_state(q, mp, NULL) == -1) {
12718 			/*
12719 			 * The copy operation failed.  mi_copy_state already
12720 			 * cleaned up, so we're out of here.
12721 			 */
12722 			return;
12723 		}
12724 		/*
12725 		 * If we just completed a copy in, we become writer and
12726 		 * continue processing in ip_sioctl_copyin_done.  If it
12727 		 * was a copy out, we call mi_copyout again.  If there is
12728 		 * nothing more to copy out, it will complete the IOCTL.
12729 		 */
12730 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12731 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12732 				mi_copy_done(q, mp, EPROTO);
12733 				return;
12734 			}
12735 			/*
12736 			 * Check for cases that need more copying.  A return
12737 			 * value of 0 means a second copyin has been started,
12738 			 * so we return; a return value of 1 means no more
12739 			 * copying is needed, so we continue.
12740 			 */
12741 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12742 			    MI_COPY_COUNT(mp) == 1) {
12743 				if (ip_copyin_msfilter(q, mp) == 0)
12744 					return;
12745 			}
12746 			/*
12747 			 * Refhold the conn, till the ioctl completes. This is
12748 			 * needed in case the ioctl ends up in the pending mp
12749 			 * list. Every mp in the ipx_pending_mp list must have
12750 			 * a refhold on the conn to resume processing. The
12751 			 * refhold is released when the ioctl completes
12752 			 * (whether normally or abnormally). An ioctlref is also
12753 			 * placed on the conn to prevent TCP from removing the
12754 			 * queue needed to send the ioctl reply back.
12755 			 * In all cases ip_ioctl_finish is called to finish
12756 			 * the ioctl and release the refholds.
12757 			 */
12758 			if (connp != NULL) {
12759 				/* This is not a reentry */
12760 				CONN_INC_REF(connp);
12761 				CONN_INC_IOCTLREF(connp);
12762 			} else {
12763 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12764 					mi_copy_done(q, mp, EINVAL);
12765 					return;
12766 				}
12767 			}
12768 
12769 			ip_process_ioctl(NULL, q, mp, ipip);
12770 
12771 		} else {
12772 			mi_copyout(q, mp);
12773 		}
12774 		return;
12775 
12776 	case M_IOCNAK:
12777 		/*
12778 		 * The only way we could get here is if a resolver didn't like
12779 		 * an IOCTL we sent it.	 This shouldn't happen.
12780 		 */
12781 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12782 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12783 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12784 		freemsg(mp);
12785 		return;
12786 	case M_IOCACK:
12787 		/* /dev/ip shouldn't see this */
12788 		goto nak;
12789 	case M_FLUSH:
12790 		if (*mp->b_rptr & FLUSHW)
12791 			flushq(q, FLUSHALL);
12792 		if (q->q_next) {
12793 			putnext(q, mp);
12794 			return;
12795 		}
12796 		if (*mp->b_rptr & FLUSHR) {
12797 			*mp->b_rptr &= ~FLUSHW;
12798 			qreply(q, mp);
12799 			return;
12800 		}
12801 		freemsg(mp);
12802 		return;
12803 	case M_CTL:
12804 		break;
12805 	case M_PROTO:
12806 	case M_PCPROTO:
12807 		/*
12808 		 * The only PROTO messages we expect are SNMP-related.
12809 		 */
12810 		switch (((union T_primitives *)mp->b_rptr)->type) {
12811 		case T_SVR4_OPTMGMT_REQ:
12812 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12813 			    "flags %x\n",
12814 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12815 
12816 			if (connp == NULL) {
12817 				proto_str = "T_SVR4_OPTMGMT_REQ";
12818 				goto protonak;
12819 			}
12820 
12821 			/*
12822 			 * All Solaris components should pass a db_credp
12823 			 * for this TPI message, hence we ASSERT.
12824 			 * But in case there is some other M_PROTO that looks
12825 			 * like a TPI message sent by some other kernel
12826 			 * component, we check and return an error.
12827 			 */
12828 			cr = msg_getcred(mp, NULL);
12829 			ASSERT(cr != NULL);
12830 			if (cr == NULL) {
12831 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12832 				if (mp != NULL)
12833 					qreply(q, mp);
12834 				return;
12835 			}
12836 
12837 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12838 				proto_str = "Bad SNMPCOM request?";
12839 				goto protonak;
12840 			}
12841 			return;
12842 		default:
12843 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12844 			    (int)*(uint_t *)mp->b_rptr));
12845 			freemsg(mp);
12846 			return;
12847 		}
12848 	default:
12849 		break;
12850 	}
12851 	if (q->q_next) {
12852 		putnext(q, mp);
12853 	} else
12854 		freemsg(mp);
12855 	return;
12856 
12857 nak:
12858 	iocp->ioc_error = EINVAL;
12859 	mp->b_datap->db_type = M_IOCNAK;
12860 	iocp->ioc_count = 0;
12861 	qreply(q, mp);
12862 	return;
12863 
12864 protonak:
12865 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12866 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12867 		qreply(q, mp);
12868 }
12869 
12870 /*
12871  * Process IP options in an outbound packet.  Verify that the nexthop in a
12872  * strict source route is onlink.
12873  * Returns non-zero if something fails in which case an ICMP error has been
12874  * sent and mp freed.
12875  *
12876  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12877  */
12878 int
12879 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12880 {
12881 	ipoptp_t	opts;
12882 	uchar_t		*opt;
12883 	uint8_t		optval;
12884 	uint8_t		optlen;
12885 	ipaddr_t	dst;
12886 	intptr_t	code = 0;
12887 	ire_t		*ire;
12888 	ip_stack_t	*ipst = ixa->ixa_ipst;
12889 	ip_recv_attr_t	iras;
12890 
12891 	ip2dbg(("ip_output_options\n"));
12892 
12893 	dst = ipha->ipha_dst;
12894 	for (optval = ipoptp_first(&opts, ipha);
12895 	    optval != IPOPT_EOL;
12896 	    optval = ipoptp_next(&opts)) {
12897 		opt = opts.ipoptp_cur;
12898 		optlen = opts.ipoptp_len;
12899 		ip2dbg(("ip_output_options: opt %d, len %d\n",
12900 		    optval, optlen));
12901 		switch (optval) {
12902 			uint32_t off;
12903 		case IPOPT_SSRR:
12904 		case IPOPT_LSRR:
12905 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12906 				ip1dbg((
12907 				    "ip_output_options: bad option offset\n"));
12908 				code = (char *)&opt[IPOPT_OLEN] -
12909 				    (char *)ipha;
12910 				goto param_prob;
12911 			}
12912 			off = opt[IPOPT_OFFSET];
12913 			ip1dbg(("ip_output_options: next hop 0x%x\n",
12914 			    ntohl(dst)));
12915 			/*
12916 			 * For strict: verify that dst is directly
12917 			 * reachable.
12918 			 */
12919 			if (optval == IPOPT_SSRR) {
12920 				ire = ire_ftable_lookup_v4(dst, 0, 0,
12921 				    IRE_INTERFACE, NULL, ALL_ZONES,
12922 				    ixa->ixa_tsl,
12923 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
12924 				    NULL);
12925 				if (ire == NULL) {
12926 					ip1dbg(("ip_output_options: SSRR not"
12927 					    " directly reachable: 0x%x\n",
12928 					    ntohl(dst)));
12929 					goto bad_src_route;
12930 				}
12931 				ire_refrele(ire);
12932 			}
12933 			break;
12934 		case IPOPT_RR:
12935 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12936 				ip1dbg((
12937 				    "ip_output_options: bad option offset\n"));
12938 				code = (char *)&opt[IPOPT_OLEN] -
12939 				    (char *)ipha;
12940 				goto param_prob;
12941 			}
12942 			break;
12943 		case IPOPT_TS:
12944 			/*
12945 			 * Verify that length >=5 and that there is either
12946 			 * room for another timestamp or that the overflow
12947 			 * counter is not maxed out.
12948 			 */
12949 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
12950 			if (optlen < IPOPT_MINLEN_IT) {
12951 				goto param_prob;
12952 			}
12953 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12954 				ip1dbg((
12955 				    "ip_output_options: bad option offset\n"));
12956 				code = (char *)&opt[IPOPT_OFFSET] -
12957 				    (char *)ipha;
12958 				goto param_prob;
12959 			}
12960 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12961 			case IPOPT_TS_TSONLY:
12962 				off = IPOPT_TS_TIMELEN;
12963 				break;
12964 			case IPOPT_TS_TSANDADDR:
12965 			case IPOPT_TS_PRESPEC:
12966 			case IPOPT_TS_PRESPEC_RFC791:
12967 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12968 				break;
12969 			default:
12970 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
12971 				    (char *)ipha;
12972 				goto param_prob;
12973 			}
12974 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
12975 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
12976 				/*
12977 				 * No room and the overflow counter is 15
12978 				 * already.
12979 				 */
12980 				goto param_prob;
12981 			}
12982 			break;
12983 		}
12984 	}
12985 
12986 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
12987 		return (0);
12988 
12989 	ip1dbg(("ip_output_options: error processing IP options."));
12990 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
12991 
12992 param_prob:
12993 	bzero(&iras, sizeof (iras));
12994 	iras.ira_ill = iras.ira_rill = ill;
12995 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
12996 	iras.ira_rifindex = iras.ira_ruifindex;
12997 	iras.ira_flags = IRAF_IS_IPV4;
12998 
12999 	ip_drop_output("ip_output_options", mp, ill);
13000 	icmp_param_problem(mp, (uint8_t)code, &iras);
13001 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13002 	return (-1);
13003 
13004 bad_src_route:
13005 	bzero(&iras, sizeof (iras));
13006 	iras.ira_ill = iras.ira_rill = ill;
13007 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13008 	iras.ira_rifindex = iras.ira_ruifindex;
13009 	iras.ira_flags = IRAF_IS_IPV4;
13010 
13011 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13012 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13013 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13014 	return (-1);
13015 }
13016 
13017 /*
13018  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13019  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13020  * thru /etc/system.
13021  */
13022 #define	CONN_MAXDRAINCNT	64
13023 
13024 static void
13025 conn_drain_init(ip_stack_t *ipst)
13026 {
13027 	int i, j;
13028 	idl_tx_list_t *itl_tx;
13029 
13030 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13031 
13032 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
13033 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13034 		/*
13035 		 * Default value of the number of drainers is the
13036 		 * number of cpus, subject to maximum of 8 drainers.
13037 		 */
13038 		if (boot_max_ncpus != -1)
13039 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13040 		else
13041 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13042 	}
13043 
13044 	ipst->ips_idl_tx_list =
13045 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13046 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13047 		itl_tx =  &ipst->ips_idl_tx_list[i];
13048 		itl_tx->txl_drain_list =
13049 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13050 		    sizeof (idl_t), KM_SLEEP);
13051 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13052 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13053 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13054 			    MUTEX_DEFAULT, NULL);
13055 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13056 		}
13057 	}
13058 }
13059 
13060 static void
13061 conn_drain_fini(ip_stack_t *ipst)
13062 {
13063 	int i;
13064 	idl_tx_list_t *itl_tx;
13065 
13066 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13067 		itl_tx =  &ipst->ips_idl_tx_list[i];
13068 		kmem_free(itl_tx->txl_drain_list,
13069 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13070 	}
13071 	kmem_free(ipst->ips_idl_tx_list,
13072 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13073 	ipst->ips_idl_tx_list = NULL;
13074 }
13075 
13076 /*
13077  * Flow control has blocked us from proceeding.  Insert the given conn in one
13078  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13079  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13080  * will call conn_walk_drain().  See the flow control notes at the top of this
13081  * file for more details.
13082  */
13083 void
13084 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13085 {
13086 	idl_t	*idl = tx_list->txl_drain_list;
13087 	uint_t	index;
13088 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13089 
13090 	mutex_enter(&connp->conn_lock);
13091 	if (connp->conn_state_flags & CONN_CLOSING) {
13092 		/*
13093 		 * The conn is closing as a result of which CONN_CLOSING
13094 		 * is set. Return.
13095 		 */
13096 		mutex_exit(&connp->conn_lock);
13097 		return;
13098 	} else if (connp->conn_idl == NULL) {
13099 		/*
13100 		 * Assign the next drain list round robin. We dont' use
13101 		 * a lock, and thus it may not be strictly round robin.
13102 		 * Atomicity of load/stores is enough to make sure that
13103 		 * conn_drain_list_index is always within bounds.
13104 		 */
13105 		index = tx_list->txl_drain_index;
13106 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13107 		connp->conn_idl = &tx_list->txl_drain_list[index];
13108 		index++;
13109 		if (index == ipst->ips_conn_drain_list_cnt)
13110 			index = 0;
13111 		tx_list->txl_drain_index = index;
13112 	} else {
13113 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13114 	}
13115 	mutex_exit(&connp->conn_lock);
13116 
13117 	idl = connp->conn_idl;
13118 	mutex_enter(&idl->idl_lock);
13119 	if ((connp->conn_drain_prev != NULL) ||
13120 	    (connp->conn_state_flags & CONN_CLOSING)) {
13121 		/*
13122 		 * The conn is either already in the drain list or closing.
13123 		 * (We needed to check for CONN_CLOSING again since close can
13124 		 * sneak in between dropping conn_lock and acquiring idl_lock.)
13125 		 */
13126 		mutex_exit(&idl->idl_lock);
13127 		return;
13128 	}
13129 
13130 	/*
13131 	 * The conn is not in the drain list. Insert it at the
13132 	 * tail of the drain list. The drain list is circular
13133 	 * and doubly linked. idl_conn points to the 1st element
13134 	 * in the list.
13135 	 */
13136 	if (idl->idl_conn == NULL) {
13137 		idl->idl_conn = connp;
13138 		connp->conn_drain_next = connp;
13139 		connp->conn_drain_prev = connp;
13140 	} else {
13141 		conn_t *head = idl->idl_conn;
13142 
13143 		connp->conn_drain_next = head;
13144 		connp->conn_drain_prev = head->conn_drain_prev;
13145 		head->conn_drain_prev->conn_drain_next = connp;
13146 		head->conn_drain_prev = connp;
13147 	}
13148 	/*
13149 	 * For non streams based sockets assert flow control.
13150 	 */
13151 	conn_setqfull(connp, NULL);
13152 	mutex_exit(&idl->idl_lock);
13153 }
13154 
13155 static void
13156 conn_drain_remove(conn_t *connp)
13157 {
13158 	idl_t *idl = connp->conn_idl;
13159 
13160 	if (idl != NULL) {
13161 		/*
13162 		 * Remove ourself from the drain list.
13163 		 */
13164 		if (connp->conn_drain_next == connp) {
13165 			/* Singleton in the list */
13166 			ASSERT(connp->conn_drain_prev == connp);
13167 			idl->idl_conn = NULL;
13168 		} else {
13169 			connp->conn_drain_prev->conn_drain_next =
13170 			    connp->conn_drain_next;
13171 			connp->conn_drain_next->conn_drain_prev =
13172 			    connp->conn_drain_prev;
13173 			if (idl->idl_conn == connp)
13174 				idl->idl_conn = connp->conn_drain_next;
13175 		}
13176 
13177 		/*
13178 		 * NOTE: because conn_idl is associated with a specific drain
13179 		 * list which in turn is tied to the index the TX ring
13180 		 * (txl_cookie) hashes to, and because the TX ring can change
13181 		 * over the lifetime of the conn_t, we must clear conn_idl so
13182 		 * a subsequent conn_drain_insert() will set conn_idl again
13183 		 * based on the latest txl_cookie.
13184 		 */
13185 		connp->conn_idl = NULL;
13186 	}
13187 	connp->conn_drain_next = NULL;
13188 	connp->conn_drain_prev = NULL;
13189 
13190 	conn_clrqfull(connp, NULL);
13191 	/*
13192 	 * For streams based sockets open up flow control.
13193 	 */
13194 	if (!IPCL_IS_NONSTR(connp))
13195 		enableok(connp->conn_wq);
13196 }
13197 
13198 /*
13199  * This conn is closing, and we are called from ip_close. OR
13200  * this conn is draining because flow-control on the ill has been relieved.
13201  *
13202  * We must also need to remove conn's on this idl from the list, and also
13203  * inform the sockfs upcalls about the change in flow-control.
13204  */
13205 static void
13206 conn_drain(conn_t *connp, boolean_t closing)
13207 {
13208 	idl_t *idl;
13209 	conn_t *next_connp;
13210 
13211 	/*
13212 	 * connp->conn_idl is stable at this point, and no lock is needed
13213 	 * to check it. If we are called from ip_close, close has already
13214 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13215 	 * called us only because conn_idl is non-null. If we are called thru
13216 	 * service, conn_idl could be null, but it cannot change because
13217 	 * service is single-threaded per queue, and there cannot be another
13218 	 * instance of service trying to call conn_drain_insert on this conn
13219 	 * now.
13220 	 */
13221 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13222 
13223 	/*
13224 	 * If the conn doesn't exist or is not on a drain list, bail.
13225 	 */
13226 	if (connp == NULL || connp->conn_idl == NULL ||
13227 	    connp->conn_drain_prev == NULL) {
13228 		return;
13229 	}
13230 
13231 	idl = connp->conn_idl;
13232 	ASSERT(MUTEX_HELD(&idl->idl_lock));
13233 
13234 	if (!closing) {
13235 		next_connp = connp->conn_drain_next;
13236 		while (next_connp != connp) {
13237 			conn_t *delconnp = next_connp;
13238 
13239 			next_connp = next_connp->conn_drain_next;
13240 			conn_drain_remove(delconnp);
13241 		}
13242 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13243 	}
13244 	conn_drain_remove(connp);
13245 }
13246 
13247 /*
13248  * Write service routine. Shared perimeter entry point.
13249  * The device queue's messages has fallen below the low water mark and STREAMS
13250  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13251  * each waiting conn.
13252  */
13253 void
13254 ip_wsrv(queue_t *q)
13255 {
13256 	ill_t	*ill;
13257 
13258 	ill = (ill_t *)q->q_ptr;
13259 	if (ill->ill_state_flags == 0) {
13260 		ip_stack_t *ipst = ill->ill_ipst;
13261 
13262 		/*
13263 		 * The device flow control has opened up.
13264 		 * Walk through conn drain lists and qenable the
13265 		 * first conn in each list. This makes sense only
13266 		 * if the stream is fully plumbed and setup.
13267 		 * Hence the ill_state_flags check above.
13268 		 */
13269 		ip1dbg(("ip_wsrv: walking\n"));
13270 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13271 		enableok(ill->ill_wq);
13272 	}
13273 }
13274 
13275 /*
13276  * Callback to disable flow control in IP.
13277  *
13278  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13279  * is enabled.
13280  *
13281  * When MAC_TX() is not able to send any more packets, dld sets its queue
13282  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13283  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13284  * function and wakes up corresponding mac worker threads, which in turn
13285  * calls this callback function, and disables flow control.
13286  */
13287 void
13288 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13289 {
13290 	ill_t *ill = (ill_t *)arg;
13291 	ip_stack_t *ipst = ill->ill_ipst;
13292 	idl_tx_list_t *idl_txl;
13293 
13294 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13295 	mutex_enter(&idl_txl->txl_lock);
13296 	/* add code to to set a flag to indicate idl_txl is enabled */
13297 	conn_walk_drain(ipst, idl_txl);
13298 	mutex_exit(&idl_txl->txl_lock);
13299 }
13300 
13301 /*
13302  * Flow control has been relieved and STREAMS has backenabled us; drain
13303  * all the conn lists on `tx_list'.
13304  */
13305 static void
13306 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13307 {
13308 	int i;
13309 	idl_t *idl;
13310 
13311 	IP_STAT(ipst, ip_conn_walk_drain);
13312 
13313 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13314 		idl = &tx_list->txl_drain_list[i];
13315 		mutex_enter(&idl->idl_lock);
13316 		conn_drain(idl->idl_conn, B_FALSE);
13317 		mutex_exit(&idl->idl_lock);
13318 	}
13319 }
13320 
13321 /*
13322  * Determine if the ill and multicast aspects of that packets
13323  * "matches" the conn.
13324  */
13325 boolean_t
13326 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13327 {
13328 	ill_t		*ill = ira->ira_rill;
13329 	zoneid_t	zoneid = ira->ira_zoneid;
13330 	uint_t		in_ifindex;
13331 	ipaddr_t	dst, src;
13332 
13333 	dst = ipha->ipha_dst;
13334 	src = ipha->ipha_src;
13335 
13336 	/*
13337 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13338 	 * unicast, broadcast and multicast reception to
13339 	 * conn_incoming_ifindex.
13340 	 * conn_wantpacket is called for unicast, broadcast and
13341 	 * multicast packets.
13342 	 */
13343 	in_ifindex = connp->conn_incoming_ifindex;
13344 
13345 	/* mpathd can bind to the under IPMP interface, which we allow */
13346 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13347 		if (!IS_UNDER_IPMP(ill))
13348 			return (B_FALSE);
13349 
13350 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13351 			return (B_FALSE);
13352 	}
13353 
13354 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13355 		return (B_FALSE);
13356 
13357 	if (!(ira->ira_flags & IRAF_MULTICAST))
13358 		return (B_TRUE);
13359 
13360 	if (connp->conn_multi_router) {
13361 		/* multicast packet and multicast router socket: send up */
13362 		return (B_TRUE);
13363 	}
13364 
13365 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13366 	    ipha->ipha_protocol == IPPROTO_RSVP)
13367 		return (B_TRUE);
13368 
13369 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13370 }
13371 
13372 void
13373 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13374 {
13375 	if (IPCL_IS_NONSTR(connp)) {
13376 		(*connp->conn_upcalls->su_txq_full)
13377 		    (connp->conn_upper_handle, B_TRUE);
13378 		if (flow_stopped != NULL)
13379 			*flow_stopped = B_TRUE;
13380 	} else {
13381 		queue_t *q = connp->conn_wq;
13382 
13383 		ASSERT(q != NULL);
13384 		if (!(q->q_flag & QFULL)) {
13385 			mutex_enter(QLOCK(q));
13386 			if (!(q->q_flag & QFULL)) {
13387 				/* still need to set QFULL */
13388 				q->q_flag |= QFULL;
13389 				/* set flow_stopped to true under QLOCK */
13390 				if (flow_stopped != NULL)
13391 					*flow_stopped = B_TRUE;
13392 				mutex_exit(QLOCK(q));
13393 			} else {
13394 				/* flow_stopped is left unchanged */
13395 				mutex_exit(QLOCK(q));
13396 			}
13397 		}
13398 	}
13399 }
13400 
13401 void
13402 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13403 {
13404 	if (IPCL_IS_NONSTR(connp)) {
13405 		(*connp->conn_upcalls->su_txq_full)
13406 		    (connp->conn_upper_handle, B_FALSE);
13407 		if (flow_stopped != NULL)
13408 			*flow_stopped = B_FALSE;
13409 	} else {
13410 		queue_t *q = connp->conn_wq;
13411 
13412 		ASSERT(q != NULL);
13413 		if (q->q_flag & QFULL) {
13414 			mutex_enter(QLOCK(q));
13415 			if (q->q_flag & QFULL) {
13416 				q->q_flag &= ~QFULL;
13417 				/* set flow_stopped to false under QLOCK */
13418 				if (flow_stopped != NULL)
13419 					*flow_stopped = B_FALSE;
13420 				mutex_exit(QLOCK(q));
13421 				if (q->q_flag & QWANTW)
13422 					qbackenable(q, 0);
13423 			} else {
13424 				/* flow_stopped is left unchanged */
13425 				mutex_exit(QLOCK(q));
13426 			}
13427 		}
13428 	}
13429 
13430 	mutex_enter(&connp->conn_lock);
13431 	connp->conn_blocked = B_FALSE;
13432 	mutex_exit(&connp->conn_lock);
13433 }
13434 
13435 /*
13436  * Return the length in bytes of the IPv4 headers (base header, label, and
13437  * other IP options) that will be needed based on the
13438  * ip_pkt_t structure passed by the caller.
13439  *
13440  * The returned length does not include the length of the upper level
13441  * protocol (ULP) header.
13442  * The caller needs to check that the length doesn't exceed the max for IPv4.
13443  */
13444 int
13445 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13446 {
13447 	int len;
13448 
13449 	len = IP_SIMPLE_HDR_LENGTH;
13450 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13451 		ASSERT(ipp->ipp_label_len_v4 != 0);
13452 		/* We need to round up here */
13453 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13454 	}
13455 
13456 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13457 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13458 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13459 		len += ipp->ipp_ipv4_options_len;
13460 	}
13461 	return (len);
13462 }
13463 
13464 /*
13465  * All-purpose routine to build an IPv4 header with options based
13466  * on the abstract ip_pkt_t.
13467  *
13468  * The caller has to set the source and destination address as well as
13469  * ipha_length. The caller has to massage any source route and compensate
13470  * for the ULP pseudo-header checksum due to the source route.
13471  */
13472 void
13473 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13474     uint8_t protocol)
13475 {
13476 	ipha_t	*ipha = (ipha_t *)buf;
13477 	uint8_t *cp;
13478 
13479 	/* Initialize IPv4 header */
13480 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13481 	ipha->ipha_length = 0;	/* Caller will set later */
13482 	ipha->ipha_ident = 0;
13483 	ipha->ipha_fragment_offset_and_flags = 0;
13484 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13485 	ipha->ipha_protocol = protocol;
13486 	ipha->ipha_hdr_checksum = 0;
13487 
13488 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13489 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13490 		ipha->ipha_src = ipp->ipp_addr_v4;
13491 
13492 	cp = (uint8_t *)&ipha[1];
13493 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13494 		ASSERT(ipp->ipp_label_len_v4 != 0);
13495 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13496 		cp += ipp->ipp_label_len_v4;
13497 		/* We need to round up here */
13498 		while ((uintptr_t)cp & 0x3) {
13499 			*cp++ = IPOPT_NOP;
13500 		}
13501 	}
13502 
13503 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13504 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13505 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13506 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13507 		cp += ipp->ipp_ipv4_options_len;
13508 	}
13509 	ipha->ipha_version_and_hdr_length =
13510 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13511 
13512 	ASSERT((int)(cp - buf) == buf_len);
13513 }
13514 
13515 /* Allocate the private structure */
13516 static int
13517 ip_priv_alloc(void **bufp)
13518 {
13519 	void	*buf;
13520 
13521 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13522 		return (ENOMEM);
13523 
13524 	*bufp = buf;
13525 	return (0);
13526 }
13527 
13528 /* Function to delete the private structure */
13529 void
13530 ip_priv_free(void *buf)
13531 {
13532 	ASSERT(buf != NULL);
13533 	kmem_free(buf, sizeof (ip_priv_t));
13534 }
13535 
13536 /*
13537  * The entry point for IPPF processing.
13538  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13539  * routine just returns.
13540  *
13541  * When called, ip_process generates an ipp_packet_t structure
13542  * which holds the state information for this packet and invokes the
13543  * the classifier (via ipp_packet_process). The classification, depending on
13544  * configured filters, results in a list of actions for this packet. Invoking
13545  * an action may cause the packet to be dropped, in which case we return NULL.
13546  * proc indicates the callout position for
13547  * this packet and ill is the interface this packet arrived on or will leave
13548  * on (inbound and outbound resp.).
13549  *
13550  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13551  * on the ill corrsponding to the destination IP address.
13552  */
13553 mblk_t *
13554 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13555 {
13556 	ip_priv_t	*priv;
13557 	ipp_action_id_t	aid;
13558 	int		rc = 0;
13559 	ipp_packet_t	*pp;
13560 
13561 	/* If the classifier is not loaded, return  */
13562 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13563 		return (mp);
13564 	}
13565 
13566 	ASSERT(mp != NULL);
13567 
13568 	/* Allocate the packet structure */
13569 	rc = ipp_packet_alloc(&pp, "ip", aid);
13570 	if (rc != 0)
13571 		goto drop;
13572 
13573 	/* Allocate the private structure */
13574 	rc = ip_priv_alloc((void **)&priv);
13575 	if (rc != 0) {
13576 		ipp_packet_free(pp);
13577 		goto drop;
13578 	}
13579 	priv->proc = proc;
13580 	priv->ill_index = ill_get_upper_ifindex(rill);
13581 
13582 	ipp_packet_set_private(pp, priv, ip_priv_free);
13583 	ipp_packet_set_data(pp, mp);
13584 
13585 	/* Invoke the classifier */
13586 	rc = ipp_packet_process(&pp);
13587 	if (pp != NULL) {
13588 		mp = ipp_packet_get_data(pp);
13589 		ipp_packet_free(pp);
13590 		if (rc != 0)
13591 			goto drop;
13592 		return (mp);
13593 	} else {
13594 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13595 		mp = NULL;
13596 	}
13597 drop:
13598 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13599 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13600 		ip_drop_input("ip_process", mp, ill);
13601 	} else {
13602 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13603 		ip_drop_output("ip_process", mp, ill);
13604 	}
13605 	freemsg(mp);
13606 	return (NULL);
13607 }
13608 
13609 /*
13610  * Propagate a multicast group membership operation (add/drop) on
13611  * all the interfaces crossed by the related multirt routes.
13612  * The call is considered successful if the operation succeeds
13613  * on at least one interface.
13614  *
13615  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13616  * multicast addresses with the ire argument being the first one.
13617  * We walk the bucket to find all the of those.
13618  *
13619  * Common to IPv4 and IPv6.
13620  */
13621 static int
13622 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13623     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13624     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13625     mcast_record_t fmode, const in6_addr_t *v6src)
13626 {
13627 	ire_t		*ire_gw;
13628 	irb_t		*irb;
13629 	int		ifindex;
13630 	int		error = 0;
13631 	int		result;
13632 	ip_stack_t	*ipst = ire->ire_ipst;
13633 	ipaddr_t	group;
13634 	boolean_t	isv6;
13635 	int		match_flags;
13636 
13637 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13638 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13639 		isv6 = B_FALSE;
13640 	} else {
13641 		isv6 = B_TRUE;
13642 	}
13643 
13644 	irb = ire->ire_bucket;
13645 	ASSERT(irb != NULL);
13646 
13647 	result = 0;
13648 	irb_refhold(irb);
13649 	for (; ire != NULL; ire = ire->ire_next) {
13650 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13651 			continue;
13652 
13653 		/* We handle -ifp routes by matching on the ill if set */
13654 		match_flags = MATCH_IRE_TYPE;
13655 		if (ire->ire_ill != NULL)
13656 			match_flags |= MATCH_IRE_ILL;
13657 
13658 		if (isv6) {
13659 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13660 				continue;
13661 
13662 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13663 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13664 			    match_flags, 0, ipst, NULL);
13665 		} else {
13666 			if (ire->ire_addr != group)
13667 				continue;
13668 
13669 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13670 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13671 			    match_flags, 0, ipst, NULL);
13672 		}
13673 		/* No interface route exists for the gateway; skip this ire. */
13674 		if (ire_gw == NULL)
13675 			continue;
13676 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13677 			ire_refrele(ire_gw);
13678 			continue;
13679 		}
13680 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13681 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13682 
13683 		/*
13684 		 * The operation is considered a success if
13685 		 * it succeeds at least once on any one interface.
13686 		 */
13687 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13688 		    fmode, v6src);
13689 		if (error == 0)
13690 			result = CGTP_MCAST_SUCCESS;
13691 
13692 		ire_refrele(ire_gw);
13693 	}
13694 	irb_refrele(irb);
13695 	/*
13696 	 * Consider the call as successful if we succeeded on at least
13697 	 * one interface. Otherwise, return the last encountered error.
13698 	 */
13699 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13700 }
13701 
13702 /*
13703  * Return the expected CGTP hooks version number.
13704  */
13705 int
13706 ip_cgtp_filter_supported(void)
13707 {
13708 	return (ip_cgtp_filter_rev);
13709 }
13710 
13711 /*
13712  * CGTP hooks can be registered by invoking this function.
13713  * Checks that the version number matches.
13714  */
13715 int
13716 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13717 {
13718 	netstack_t *ns;
13719 	ip_stack_t *ipst;
13720 
13721 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13722 		return (ENOTSUP);
13723 
13724 	ns = netstack_find_by_stackid(stackid);
13725 	if (ns == NULL)
13726 		return (EINVAL);
13727 	ipst = ns->netstack_ip;
13728 	ASSERT(ipst != NULL);
13729 
13730 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13731 		netstack_rele(ns);
13732 		return (EALREADY);
13733 	}
13734 
13735 	ipst->ips_ip_cgtp_filter_ops = ops;
13736 
13737 	ill_set_inputfn_all(ipst);
13738 
13739 	netstack_rele(ns);
13740 	return (0);
13741 }
13742 
13743 /*
13744  * CGTP hooks can be unregistered by invoking this function.
13745  * Returns ENXIO if there was no registration.
13746  * Returns EBUSY if the ndd variable has not been turned off.
13747  */
13748 int
13749 ip_cgtp_filter_unregister(netstackid_t stackid)
13750 {
13751 	netstack_t *ns;
13752 	ip_stack_t *ipst;
13753 
13754 	ns = netstack_find_by_stackid(stackid);
13755 	if (ns == NULL)
13756 		return (EINVAL);
13757 	ipst = ns->netstack_ip;
13758 	ASSERT(ipst != NULL);
13759 
13760 	if (ipst->ips_ip_cgtp_filter) {
13761 		netstack_rele(ns);
13762 		return (EBUSY);
13763 	}
13764 
13765 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13766 		netstack_rele(ns);
13767 		return (ENXIO);
13768 	}
13769 	ipst->ips_ip_cgtp_filter_ops = NULL;
13770 
13771 	ill_set_inputfn_all(ipst);
13772 
13773 	netstack_rele(ns);
13774 	return (0);
13775 }
13776 
13777 /*
13778  * Check whether there is a CGTP filter registration.
13779  * Returns non-zero if there is a registration, otherwise returns zero.
13780  * Note: returns zero if bad stackid.
13781  */
13782 int
13783 ip_cgtp_filter_is_registered(netstackid_t stackid)
13784 {
13785 	netstack_t *ns;
13786 	ip_stack_t *ipst;
13787 	int ret;
13788 
13789 	ns = netstack_find_by_stackid(stackid);
13790 	if (ns == NULL)
13791 		return (0);
13792 	ipst = ns->netstack_ip;
13793 	ASSERT(ipst != NULL);
13794 
13795 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13796 		ret = 1;
13797 	else
13798 		ret = 0;
13799 
13800 	netstack_rele(ns);
13801 	return (ret);
13802 }
13803 
13804 static int
13805 ip_squeue_switch(int val)
13806 {
13807 	int rval;
13808 
13809 	switch (val) {
13810 	case IP_SQUEUE_ENTER_NODRAIN:
13811 		rval = SQ_NODRAIN;
13812 		break;
13813 	case IP_SQUEUE_ENTER:
13814 		rval = SQ_PROCESS;
13815 		break;
13816 	case IP_SQUEUE_FILL:
13817 	default:
13818 		rval = SQ_FILL;
13819 		break;
13820 	}
13821 	return (rval);
13822 }
13823 
13824 static void *
13825 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13826 {
13827 	kstat_t *ksp;
13828 
13829 	ip_stat_t template = {
13830 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
13831 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
13832 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
13833 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13834 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13835 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13836 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13837 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13838 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13839 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13840 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13841 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13842 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13843 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13844 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13845 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13846 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13847 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13848 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13849 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13850 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13851 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13852 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13853 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13854 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13855 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13856 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13857 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13858 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13859 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13860 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
13861 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
13862 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
13863 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
13864 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
13865 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
13866 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
13867 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
13868 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
13869 	};
13870 
13871 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13872 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13873 	    KSTAT_FLAG_VIRTUAL, stackid);
13874 
13875 	if (ksp == NULL)
13876 		return (NULL);
13877 
13878 	bcopy(&template, ip_statisticsp, sizeof (template));
13879 	ksp->ks_data = (void *)ip_statisticsp;
13880 	ksp->ks_private = (void *)(uintptr_t)stackid;
13881 
13882 	kstat_install(ksp);
13883 	return (ksp);
13884 }
13885 
13886 static void
13887 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13888 {
13889 	if (ksp != NULL) {
13890 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13891 		kstat_delete_netstack(ksp, stackid);
13892 	}
13893 }
13894 
13895 static void *
13896 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13897 {
13898 	kstat_t	*ksp;
13899 
13900 	ip_named_kstat_t template = {
13901 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
13902 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
13903 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
13904 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
13905 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
13906 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
13907 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
13908 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
13909 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
13910 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
13911 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
13912 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
13913 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
13914 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
13915 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
13916 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
13917 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
13918 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
13919 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
13920 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
13921 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
13922 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
13923 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
13924 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
13925 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
13926 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
13927 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
13928 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
13929 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
13930 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
13931 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
13932 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
13933 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
13934 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
13935 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
13936 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
13937 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
13938 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
13939 	};
13940 
13941 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
13942 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
13943 	if (ksp == NULL || ksp->ks_data == NULL)
13944 		return (NULL);
13945 
13946 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
13947 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
13948 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
13949 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
13950 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
13951 
13952 	template.netToMediaEntrySize.value.i32 =
13953 	    sizeof (mib2_ipNetToMediaEntry_t);
13954 
13955 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
13956 
13957 	bcopy(&template, ksp->ks_data, sizeof (template));
13958 	ksp->ks_update = ip_kstat_update;
13959 	ksp->ks_private = (void *)(uintptr_t)stackid;
13960 
13961 	kstat_install(ksp);
13962 	return (ksp);
13963 }
13964 
13965 static void
13966 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
13967 {
13968 	if (ksp != NULL) {
13969 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13970 		kstat_delete_netstack(ksp, stackid);
13971 	}
13972 }
13973 
13974 static int
13975 ip_kstat_update(kstat_t *kp, int rw)
13976 {
13977 	ip_named_kstat_t *ipkp;
13978 	mib2_ipIfStatsEntry_t ipmib;
13979 	ill_walk_context_t ctx;
13980 	ill_t *ill;
13981 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
13982 	netstack_t	*ns;
13983 	ip_stack_t	*ipst;
13984 
13985 	if (kp == NULL || kp->ks_data == NULL)
13986 		return (EIO);
13987 
13988 	if (rw == KSTAT_WRITE)
13989 		return (EACCES);
13990 
13991 	ns = netstack_find_by_stackid(stackid);
13992 	if (ns == NULL)
13993 		return (-1);
13994 	ipst = ns->netstack_ip;
13995 	if (ipst == NULL) {
13996 		netstack_rele(ns);
13997 		return (-1);
13998 	}
13999 	ipkp = (ip_named_kstat_t *)kp->ks_data;
14000 
14001 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14002 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14003 	ill = ILL_START_WALK_V4(&ctx, ipst);
14004 	for (; ill != NULL; ill = ill_next(&ctx, ill))
14005 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14006 	rw_exit(&ipst->ips_ill_g_lock);
14007 
14008 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
14009 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
14010 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
14011 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
14012 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
14013 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14014 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
14015 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
14016 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
14017 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
14018 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
14019 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
14020 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
14021 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
14022 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
14023 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
14024 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
14025 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
14026 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
14027 
14028 	ipkp->routingDiscards.value.ui32 =	0;
14029 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
14030 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
14031 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
14032 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
14033 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
14034 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
14035 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
14036 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
14037 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
14038 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
14039 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
14040 
14041 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
14042 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
14043 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14044 
14045 	netstack_rele(ns);
14046 
14047 	return (0);
14048 }
14049 
14050 static void *
14051 icmp_kstat_init(netstackid_t stackid)
14052 {
14053 	kstat_t	*ksp;
14054 
14055 	icmp_named_kstat_t template = {
14056 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14057 		{ "inErrors",		KSTAT_DATA_UINT32 },
14058 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14059 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14060 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14061 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14062 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14063 		{ "inEchos",		KSTAT_DATA_UINT32 },
14064 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14065 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14066 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14067 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14068 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14069 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14070 		{ "outErrors",		KSTAT_DATA_UINT32 },
14071 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14072 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14073 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14074 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14075 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14076 		{ "outEchos",		KSTAT_DATA_UINT32 },
14077 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14078 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14079 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14080 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14081 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14082 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14083 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14084 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14085 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14086 		{ "outDrops",		KSTAT_DATA_UINT32 },
14087 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14088 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14089 	};
14090 
14091 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14092 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14093 	if (ksp == NULL || ksp->ks_data == NULL)
14094 		return (NULL);
14095 
14096 	bcopy(&template, ksp->ks_data, sizeof (template));
14097 
14098 	ksp->ks_update = icmp_kstat_update;
14099 	ksp->ks_private = (void *)(uintptr_t)stackid;
14100 
14101 	kstat_install(ksp);
14102 	return (ksp);
14103 }
14104 
14105 static void
14106 icmp_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 icmp_kstat_update(kstat_t *kp, int rw)
14116 {
14117 	icmp_named_kstat_t *icmpkp;
14118 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14119 	netstack_t	*ns;
14120 	ip_stack_t	*ipst;
14121 
14122 	if ((kp == NULL) || (kp->ks_data == NULL))
14123 		return (EIO);
14124 
14125 	if (rw == KSTAT_WRITE)
14126 		return (EACCES);
14127 
14128 	ns = netstack_find_by_stackid(stackid);
14129 	if (ns == NULL)
14130 		return (-1);
14131 	ipst = ns->netstack_ip;
14132 	if (ipst == NULL) {
14133 		netstack_rele(ns);
14134 		return (-1);
14135 	}
14136 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14137 
14138 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14139 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14140 	icmpkp->inDestUnreachs.value.ui32 =
14141 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14142 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14143 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14144 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14145 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14146 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14147 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14148 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14149 	icmpkp->inTimestampReps.value.ui32 =
14150 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14151 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14152 	icmpkp->inAddrMaskReps.value.ui32 =
14153 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14154 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14155 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14156 	icmpkp->outDestUnreachs.value.ui32 =
14157 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14158 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14159 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14160 	icmpkp->outSrcQuenchs.value.ui32 =
14161 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14162 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14163 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14164 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14165 	icmpkp->outTimestamps.value.ui32 =
14166 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14167 	icmpkp->outTimestampReps.value.ui32 =
14168 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14169 	icmpkp->outAddrMasks.value.ui32 =
14170 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14171 	icmpkp->outAddrMaskReps.value.ui32 =
14172 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14173 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14174 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14175 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14176 	icmpkp->outFragNeeded.value.ui32 =
14177 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14178 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14179 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14180 	icmpkp->inBadRedirects.value.ui32 =
14181 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14182 
14183 	netstack_rele(ns);
14184 	return (0);
14185 }
14186 
14187 /*
14188  * This is the fanout function for raw socket opened for SCTP.  Note
14189  * that it is called after SCTP checks that there is no socket which
14190  * wants a packet.  Then before SCTP handles this out of the blue packet,
14191  * this function is called to see if there is any raw socket for SCTP.
14192  * If there is and it is bound to the correct address, the packet will
14193  * be sent to that socket.  Note that only one raw socket can be bound to
14194  * a port.  This is assured in ipcl_sctp_hash_insert();
14195  */
14196 void
14197 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14198     ip_recv_attr_t *ira)
14199 {
14200 	conn_t		*connp;
14201 	queue_t		*rq;
14202 	boolean_t	secure;
14203 	ill_t		*ill = ira->ira_ill;
14204 	ip_stack_t	*ipst = ill->ill_ipst;
14205 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14206 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14207 	iaflags_t	iraflags = ira->ira_flags;
14208 	ill_t		*rill = ira->ira_rill;
14209 
14210 	secure = iraflags & IRAF_IPSEC_SECURE;
14211 
14212 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14213 	    ira, ipst);
14214 	if (connp == NULL) {
14215 		/*
14216 		 * Although raw sctp is not summed, OOB chunks must be.
14217 		 * Drop the packet here if the sctp checksum failed.
14218 		 */
14219 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14220 			SCTPS_BUMP_MIB(sctps, sctpChecksumError);
14221 			freemsg(mp);
14222 			return;
14223 		}
14224 		ira->ira_ill = ira->ira_rill = NULL;
14225 		sctp_ootb_input(mp, ira, ipst);
14226 		ira->ira_ill = ill;
14227 		ira->ira_rill = rill;
14228 		return;
14229 	}
14230 	rq = connp->conn_rq;
14231 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14232 		CONN_DEC_REF(connp);
14233 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14234 		freemsg(mp);
14235 		return;
14236 	}
14237 	if (((iraflags & IRAF_IS_IPV4) ?
14238 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14239 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14240 	    secure) {
14241 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14242 		    ip6h, ira);
14243 		if (mp == NULL) {
14244 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14245 			/* Note that mp is NULL */
14246 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14247 			CONN_DEC_REF(connp);
14248 			return;
14249 		}
14250 	}
14251 
14252 	if (iraflags & IRAF_ICMP_ERROR) {
14253 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14254 	} else {
14255 		ill_t *rill = ira->ira_rill;
14256 
14257 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14258 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14259 		ira->ira_ill = ira->ira_rill = NULL;
14260 		(connp->conn_recv)(connp, mp, NULL, ira);
14261 		ira->ira_ill = ill;
14262 		ira->ira_rill = rill;
14263 	}
14264 	CONN_DEC_REF(connp);
14265 }
14266 
14267 /*
14268  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14269  * header before the ip payload.
14270  */
14271 static void
14272 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14273 {
14274 	int len = (mp->b_wptr - mp->b_rptr);
14275 	mblk_t *ip_mp;
14276 
14277 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14278 	if (is_fp_mp || len != fp_mp_len) {
14279 		if (len > fp_mp_len) {
14280 			/*
14281 			 * fastpath header and ip header in the first mblk
14282 			 */
14283 			mp->b_rptr += fp_mp_len;
14284 		} else {
14285 			/*
14286 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14287 			 * attach the fastpath header before ip header.
14288 			 */
14289 			ip_mp = mp->b_cont;
14290 			freeb(mp);
14291 			mp = ip_mp;
14292 			mp->b_rptr += (fp_mp_len - len);
14293 		}
14294 	} else {
14295 		ip_mp = mp->b_cont;
14296 		freeb(mp);
14297 		mp = ip_mp;
14298 	}
14299 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14300 	freemsg(mp);
14301 }
14302 
14303 /*
14304  * Normal post fragmentation function.
14305  *
14306  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14307  * using the same state machine.
14308  *
14309  * We return an error on failure. In particular we return EWOULDBLOCK
14310  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14311  * (currently by canputnext failure resulting in backenabling from GLD.)
14312  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14313  * indication that they can flow control until ip_wsrv() tells then to restart.
14314  *
14315  * If the nce passed by caller is incomplete, this function
14316  * queues the packet and if necessary, sends ARP request and bails.
14317  * If the Neighbor Cache passed is fully resolved, we simply prepend
14318  * the link-layer header to the packet, do ipsec hw acceleration
14319  * work if necessary, and send the packet out on the wire.
14320  */
14321 /* ARGSUSED6 */
14322 int
14323 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14324     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14325 {
14326 	queue_t		*wq;
14327 	ill_t		*ill = nce->nce_ill;
14328 	ip_stack_t	*ipst = ill->ill_ipst;
14329 	uint64_t	delta;
14330 	boolean_t	isv6 = ill->ill_isv6;
14331 	boolean_t	fp_mp;
14332 	ncec_t		*ncec = nce->nce_common;
14333 	int64_t		now = LBOLT_FASTPATH64;
14334 	boolean_t	is_probe;
14335 
14336 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14337 
14338 	ASSERT(mp != NULL);
14339 	ASSERT(mp->b_datap->db_type == M_DATA);
14340 	ASSERT(pkt_len == msgdsize(mp));
14341 
14342 	/*
14343 	 * If we have already been here and are coming back after ARP/ND.
14344 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14345 	 * in that case since they have seen the packet when it came here
14346 	 * the first time.
14347 	 */
14348 	if (ixaflags & IXAF_NO_TRACE)
14349 		goto sendit;
14350 
14351 	if (ixaflags & IXAF_IS_IPV4) {
14352 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14353 
14354 		ASSERT(!isv6);
14355 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14356 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14357 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14358 			int	error;
14359 
14360 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14361 			    ipst->ips_ipv4firewall_physical_out,
14362 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14363 			DTRACE_PROBE1(ip4__physical__out__end,
14364 			    mblk_t *, mp);
14365 			if (mp == NULL)
14366 				return (error);
14367 
14368 			/* The length could have changed */
14369 			pkt_len = msgdsize(mp);
14370 		}
14371 		if (ipst->ips_ip4_observe.he_interested) {
14372 			/*
14373 			 * Note that for TX the zoneid is the sending
14374 			 * zone, whether or not MLP is in play.
14375 			 * Since the szone argument is the IP zoneid (i.e.,
14376 			 * zero for exclusive-IP zones) and ipobs wants
14377 			 * the system zoneid, we map it here.
14378 			 */
14379 			szone = IP_REAL_ZONEID(szone, ipst);
14380 
14381 			/*
14382 			 * On the outbound path the destination zone will be
14383 			 * unknown as we're sending this packet out on the
14384 			 * wire.
14385 			 */
14386 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14387 			    ill, ipst);
14388 		}
14389 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14390 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14391 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14392 	} else {
14393 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14394 
14395 		ASSERT(isv6);
14396 		ASSERT(pkt_len ==
14397 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14398 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14399 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14400 			int	error;
14401 
14402 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14403 			    ipst->ips_ipv6firewall_physical_out,
14404 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14405 			DTRACE_PROBE1(ip6__physical__out__end,
14406 			    mblk_t *, mp);
14407 			if (mp == NULL)
14408 				return (error);
14409 
14410 			/* The length could have changed */
14411 			pkt_len = msgdsize(mp);
14412 		}
14413 		if (ipst->ips_ip6_observe.he_interested) {
14414 			/* See above */
14415 			szone = IP_REAL_ZONEID(szone, ipst);
14416 
14417 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14418 			    ill, ipst);
14419 		}
14420 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14421 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14422 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14423 	}
14424 
14425 sendit:
14426 	/*
14427 	 * We check the state without a lock because the state can never
14428 	 * move "backwards" to initial or incomplete.
14429 	 */
14430 	switch (ncec->ncec_state) {
14431 	case ND_REACHABLE:
14432 	case ND_STALE:
14433 	case ND_DELAY:
14434 	case ND_PROBE:
14435 		mp = ip_xmit_attach_llhdr(mp, nce);
14436 		if (mp == NULL) {
14437 			/*
14438 			 * ip_xmit_attach_llhdr has increased
14439 			 * ipIfStatsOutDiscards and called ip_drop_output()
14440 			 */
14441 			return (ENOBUFS);
14442 		}
14443 		/*
14444 		 * check if nce_fastpath completed and we tagged on a
14445 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14446 		 */
14447 		fp_mp = (mp->b_datap->db_type == M_DATA);
14448 
14449 		if (fp_mp &&
14450 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14451 			ill_dld_direct_t *idd;
14452 
14453 			idd = &ill->ill_dld_capab->idc_direct;
14454 			/*
14455 			 * Send the packet directly to DLD, where it
14456 			 * may be queued depending on the availability
14457 			 * of transmit resources at the media layer.
14458 			 * Return value should be taken into
14459 			 * account and flow control the TCP.
14460 			 */
14461 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14462 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14463 			    pkt_len);
14464 
14465 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14466 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14467 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14468 			} else {
14469 				uintptr_t cookie;
14470 
14471 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14472 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14473 					if (ixacookie != NULL)
14474 						*ixacookie = cookie;
14475 					return (EWOULDBLOCK);
14476 				}
14477 			}
14478 		} else {
14479 			wq = ill->ill_wq;
14480 
14481 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14482 			    !canputnext(wq)) {
14483 				if (ixacookie != NULL)
14484 					*ixacookie = 0;
14485 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14486 				    nce->nce_fp_mp != NULL ?
14487 				    MBLKL(nce->nce_fp_mp) : 0);
14488 				return (EWOULDBLOCK);
14489 			}
14490 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14491 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14492 			    pkt_len);
14493 			putnext(wq, mp);
14494 		}
14495 
14496 		/*
14497 		 * The rest of this function implements Neighbor Unreachability
14498 		 * detection. Determine if the ncec is eligible for NUD.
14499 		 */
14500 		if (ncec->ncec_flags & NCE_F_NONUD)
14501 			return (0);
14502 
14503 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14504 
14505 		/*
14506 		 * Check for upper layer advice
14507 		 */
14508 		if (ixaflags & IXAF_REACH_CONF) {
14509 			timeout_id_t tid;
14510 
14511 			/*
14512 			 * It should be o.k. to check the state without
14513 			 * a lock here, at most we lose an advice.
14514 			 */
14515 			ncec->ncec_last = TICK_TO_MSEC(now);
14516 			if (ncec->ncec_state != ND_REACHABLE) {
14517 				mutex_enter(&ncec->ncec_lock);
14518 				ncec->ncec_state = ND_REACHABLE;
14519 				tid = ncec->ncec_timeout_id;
14520 				ncec->ncec_timeout_id = 0;
14521 				mutex_exit(&ncec->ncec_lock);
14522 				(void) untimeout(tid);
14523 				if (ip_debug > 2) {
14524 					/* ip1dbg */
14525 					pr_addr_dbg("ip_xmit: state"
14526 					    " for %s changed to"
14527 					    " REACHABLE\n", AF_INET6,
14528 					    &ncec->ncec_addr);
14529 				}
14530 			}
14531 			return (0);
14532 		}
14533 
14534 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14535 		ip1dbg(("ip_xmit: delta = %" PRId64
14536 		    " ill_reachable_time = %d \n", delta,
14537 		    ill->ill_reachable_time));
14538 		if (delta > (uint64_t)ill->ill_reachable_time) {
14539 			mutex_enter(&ncec->ncec_lock);
14540 			switch (ncec->ncec_state) {
14541 			case ND_REACHABLE:
14542 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14543 				/* FALLTHROUGH */
14544 			case ND_STALE:
14545 				/*
14546 				 * ND_REACHABLE is identical to
14547 				 * ND_STALE in this specific case. If
14548 				 * reachable time has expired for this
14549 				 * neighbor (delta is greater than
14550 				 * reachable time), conceptually, the
14551 				 * neighbor cache is no longer in
14552 				 * REACHABLE state, but already in
14553 				 * STALE state.  So the correct
14554 				 * transition here is to ND_DELAY.
14555 				 */
14556 				ncec->ncec_state = ND_DELAY;
14557 				mutex_exit(&ncec->ncec_lock);
14558 				nce_restart_timer(ncec,
14559 				    ipst->ips_delay_first_probe_time);
14560 				if (ip_debug > 3) {
14561 					/* ip2dbg */
14562 					pr_addr_dbg("ip_xmit: state"
14563 					    " for %s changed to"
14564 					    " DELAY\n", AF_INET6,
14565 					    &ncec->ncec_addr);
14566 				}
14567 				break;
14568 			case ND_DELAY:
14569 			case ND_PROBE:
14570 				mutex_exit(&ncec->ncec_lock);
14571 				/* Timers have already started */
14572 				break;
14573 			case ND_UNREACHABLE:
14574 				/*
14575 				 * nce_timer has detected that this ncec
14576 				 * is unreachable and initiated deleting
14577 				 * this ncec.
14578 				 * This is a harmless race where we found the
14579 				 * ncec before it was deleted and have
14580 				 * just sent out a packet using this
14581 				 * unreachable ncec.
14582 				 */
14583 				mutex_exit(&ncec->ncec_lock);
14584 				break;
14585 			default:
14586 				ASSERT(0);
14587 				mutex_exit(&ncec->ncec_lock);
14588 			}
14589 		}
14590 		return (0);
14591 
14592 	case ND_INCOMPLETE:
14593 		/*
14594 		 * the state could have changed since we didn't hold the lock.
14595 		 * Re-verify state under lock.
14596 		 */
14597 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14598 		mutex_enter(&ncec->ncec_lock);
14599 		if (NCE_ISREACHABLE(ncec)) {
14600 			mutex_exit(&ncec->ncec_lock);
14601 			goto sendit;
14602 		}
14603 		/* queue the packet */
14604 		nce_queue_mp(ncec, mp, is_probe);
14605 		mutex_exit(&ncec->ncec_lock);
14606 		DTRACE_PROBE2(ip__xmit__incomplete,
14607 		    (ncec_t *), ncec, (mblk_t *), mp);
14608 		return (0);
14609 
14610 	case ND_INITIAL:
14611 		/*
14612 		 * State could have changed since we didn't hold the lock, so
14613 		 * re-verify state.
14614 		 */
14615 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14616 		mutex_enter(&ncec->ncec_lock);
14617 		if (NCE_ISREACHABLE(ncec))  {
14618 			mutex_exit(&ncec->ncec_lock);
14619 			goto sendit;
14620 		}
14621 		nce_queue_mp(ncec, mp, is_probe);
14622 		if (ncec->ncec_state == ND_INITIAL) {
14623 			ncec->ncec_state = ND_INCOMPLETE;
14624 			mutex_exit(&ncec->ncec_lock);
14625 			/*
14626 			 * figure out the source we want to use
14627 			 * and resolve it.
14628 			 */
14629 			ip_ndp_resolve(ncec);
14630 		} else  {
14631 			mutex_exit(&ncec->ncec_lock);
14632 		}
14633 		return (0);
14634 
14635 	case ND_UNREACHABLE:
14636 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14637 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14638 		    mp, ill);
14639 		freemsg(mp);
14640 		return (0);
14641 
14642 	default:
14643 		ASSERT(0);
14644 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14645 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14646 		    mp, ill);
14647 		freemsg(mp);
14648 		return (ENETUNREACH);
14649 	}
14650 }
14651 
14652 /*
14653  * Return B_TRUE if the buffers differ in length or content.
14654  * This is used for comparing extension header buffers.
14655  * Note that an extension header would be declared different
14656  * even if all that changed was the next header value in that header i.e.
14657  * what really changed is the next extension header.
14658  */
14659 boolean_t
14660 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14661     uint_t blen)
14662 {
14663 	if (!b_valid)
14664 		blen = 0;
14665 
14666 	if (alen != blen)
14667 		return (B_TRUE);
14668 	if (alen == 0)
14669 		return (B_FALSE);	/* Both zero length */
14670 	return (bcmp(abuf, bbuf, alen));
14671 }
14672 
14673 /*
14674  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14675  * Return B_FALSE if memory allocation fails - don't change any state!
14676  */
14677 boolean_t
14678 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14679     const void *src, uint_t srclen)
14680 {
14681 	void *dst;
14682 
14683 	if (!src_valid)
14684 		srclen = 0;
14685 
14686 	ASSERT(*dstlenp == 0);
14687 	if (src != NULL && srclen != 0) {
14688 		dst = mi_alloc(srclen, BPRI_MED);
14689 		if (dst == NULL)
14690 			return (B_FALSE);
14691 	} else {
14692 		dst = NULL;
14693 	}
14694 	if (*dstp != NULL)
14695 		mi_free(*dstp);
14696 	*dstp = dst;
14697 	*dstlenp = dst == NULL ? 0 : srclen;
14698 	return (B_TRUE);
14699 }
14700 
14701 /*
14702  * Replace what is in *dst, *dstlen with the source.
14703  * Assumes ip_allocbuf has already been called.
14704  */
14705 void
14706 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14707     const void *src, uint_t srclen)
14708 {
14709 	if (!src_valid)
14710 		srclen = 0;
14711 
14712 	ASSERT(*dstlenp == srclen);
14713 	if (src != NULL && srclen != 0)
14714 		bcopy(src, *dstp, srclen);
14715 }
14716 
14717 /*
14718  * Free the storage pointed to by the members of an ip_pkt_t.
14719  */
14720 void
14721 ip_pkt_free(ip_pkt_t *ipp)
14722 {
14723 	uint_t	fields = ipp->ipp_fields;
14724 
14725 	if (fields & IPPF_HOPOPTS) {
14726 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14727 		ipp->ipp_hopopts = NULL;
14728 		ipp->ipp_hopoptslen = 0;
14729 	}
14730 	if (fields & IPPF_RTHDRDSTOPTS) {
14731 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14732 		ipp->ipp_rthdrdstopts = NULL;
14733 		ipp->ipp_rthdrdstoptslen = 0;
14734 	}
14735 	if (fields & IPPF_DSTOPTS) {
14736 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14737 		ipp->ipp_dstopts = NULL;
14738 		ipp->ipp_dstoptslen = 0;
14739 	}
14740 	if (fields & IPPF_RTHDR) {
14741 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14742 		ipp->ipp_rthdr = NULL;
14743 		ipp->ipp_rthdrlen = 0;
14744 	}
14745 	if (fields & IPPF_IPV4_OPTIONS) {
14746 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14747 		ipp->ipp_ipv4_options = NULL;
14748 		ipp->ipp_ipv4_options_len = 0;
14749 	}
14750 	if (fields & IPPF_LABEL_V4) {
14751 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14752 		ipp->ipp_label_v4 = NULL;
14753 		ipp->ipp_label_len_v4 = 0;
14754 	}
14755 	if (fields & IPPF_LABEL_V6) {
14756 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14757 		ipp->ipp_label_v6 = NULL;
14758 		ipp->ipp_label_len_v6 = 0;
14759 	}
14760 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14761 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14762 }
14763 
14764 /*
14765  * Copy from src to dst and allocate as needed.
14766  * Returns zero or ENOMEM.
14767  *
14768  * The caller must initialize dst to zero.
14769  */
14770 int
14771 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14772 {
14773 	uint_t	fields = src->ipp_fields;
14774 
14775 	/* Start with fields that don't require memory allocation */
14776 	dst->ipp_fields = fields &
14777 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14778 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14779 
14780 	dst->ipp_addr = src->ipp_addr;
14781 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14782 	dst->ipp_hoplimit = src->ipp_hoplimit;
14783 	dst->ipp_tclass = src->ipp_tclass;
14784 	dst->ipp_type_of_service = src->ipp_type_of_service;
14785 
14786 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14787 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14788 		return (0);
14789 
14790 	if (fields & IPPF_HOPOPTS) {
14791 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14792 		if (dst->ipp_hopopts == NULL) {
14793 			ip_pkt_free(dst);
14794 			return (ENOMEM);
14795 		}
14796 		dst->ipp_fields |= IPPF_HOPOPTS;
14797 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14798 		    src->ipp_hopoptslen);
14799 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14800 	}
14801 	if (fields & IPPF_RTHDRDSTOPTS) {
14802 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14803 		    kmflag);
14804 		if (dst->ipp_rthdrdstopts == NULL) {
14805 			ip_pkt_free(dst);
14806 			return (ENOMEM);
14807 		}
14808 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14809 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14810 		    src->ipp_rthdrdstoptslen);
14811 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14812 	}
14813 	if (fields & IPPF_DSTOPTS) {
14814 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14815 		if (dst->ipp_dstopts == NULL) {
14816 			ip_pkt_free(dst);
14817 			return (ENOMEM);
14818 		}
14819 		dst->ipp_fields |= IPPF_DSTOPTS;
14820 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14821 		    src->ipp_dstoptslen);
14822 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14823 	}
14824 	if (fields & IPPF_RTHDR) {
14825 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14826 		if (dst->ipp_rthdr == NULL) {
14827 			ip_pkt_free(dst);
14828 			return (ENOMEM);
14829 		}
14830 		dst->ipp_fields |= IPPF_RTHDR;
14831 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14832 		    src->ipp_rthdrlen);
14833 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14834 	}
14835 	if (fields & IPPF_IPV4_OPTIONS) {
14836 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14837 		    kmflag);
14838 		if (dst->ipp_ipv4_options == NULL) {
14839 			ip_pkt_free(dst);
14840 			return (ENOMEM);
14841 		}
14842 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14843 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14844 		    src->ipp_ipv4_options_len);
14845 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14846 	}
14847 	if (fields & IPPF_LABEL_V4) {
14848 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14849 		if (dst->ipp_label_v4 == NULL) {
14850 			ip_pkt_free(dst);
14851 			return (ENOMEM);
14852 		}
14853 		dst->ipp_fields |= IPPF_LABEL_V4;
14854 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14855 		    src->ipp_label_len_v4);
14856 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14857 	}
14858 	if (fields & IPPF_LABEL_V6) {
14859 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14860 		if (dst->ipp_label_v6 == NULL) {
14861 			ip_pkt_free(dst);
14862 			return (ENOMEM);
14863 		}
14864 		dst->ipp_fields |= IPPF_LABEL_V6;
14865 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14866 		    src->ipp_label_len_v6);
14867 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14868 	}
14869 	if (fields & IPPF_FRAGHDR) {
14870 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14871 		if (dst->ipp_fraghdr == NULL) {
14872 			ip_pkt_free(dst);
14873 			return (ENOMEM);
14874 		}
14875 		dst->ipp_fields |= IPPF_FRAGHDR;
14876 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14877 		    src->ipp_fraghdrlen);
14878 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14879 	}
14880 	return (0);
14881 }
14882 
14883 /*
14884  * Returns INADDR_ANY if no source route
14885  */
14886 ipaddr_t
14887 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14888 {
14889 	ipaddr_t	nexthop = INADDR_ANY;
14890 	ipoptp_t	opts;
14891 	uchar_t		*opt;
14892 	uint8_t		optval;
14893 	uint8_t		optlen;
14894 	uint32_t	totallen;
14895 
14896 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14897 		return (INADDR_ANY);
14898 
14899 	totallen = ipp->ipp_ipv4_options_len;
14900 	if (totallen & 0x3)
14901 		return (INADDR_ANY);
14902 
14903 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14904 	    optval != IPOPT_EOL;
14905 	    optval = ipoptp_next(&opts)) {
14906 		opt = opts.ipoptp_cur;
14907 		switch (optval) {
14908 			uint8_t off;
14909 		case IPOPT_SSRR:
14910 		case IPOPT_LSRR:
14911 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14912 				break;
14913 			}
14914 			optlen = opts.ipoptp_len;
14915 			off = opt[IPOPT_OFFSET];
14916 			off--;
14917 			if (optlen < IP_ADDR_LEN ||
14918 			    off > optlen - IP_ADDR_LEN) {
14919 				/* End of source route */
14920 				break;
14921 			}
14922 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
14923 			if (nexthop == htonl(INADDR_LOOPBACK)) {
14924 				/* Ignore */
14925 				nexthop = INADDR_ANY;
14926 				break;
14927 			}
14928 			break;
14929 		}
14930 	}
14931 	return (nexthop);
14932 }
14933 
14934 /*
14935  * Reverse a source route.
14936  */
14937 void
14938 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
14939 {
14940 	ipaddr_t	tmp;
14941 	ipoptp_t	opts;
14942 	uchar_t		*opt;
14943 	uint8_t		optval;
14944 	uint32_t	totallen;
14945 
14946 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14947 		return;
14948 
14949 	totallen = ipp->ipp_ipv4_options_len;
14950 	if (totallen & 0x3)
14951 		return;
14952 
14953 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14954 	    optval != IPOPT_EOL;
14955 	    optval = ipoptp_next(&opts)) {
14956 		uint8_t off1, off2;
14957 
14958 		opt = opts.ipoptp_cur;
14959 		switch (optval) {
14960 		case IPOPT_SSRR:
14961 		case IPOPT_LSRR:
14962 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14963 				break;
14964 			}
14965 			off1 = IPOPT_MINOFF_SR - 1;
14966 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
14967 			while (off2 > off1) {
14968 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
14969 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
14970 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
14971 				off2 -= IP_ADDR_LEN;
14972 				off1 += IP_ADDR_LEN;
14973 			}
14974 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
14975 			break;
14976 		}
14977 	}
14978 }
14979 
14980 /*
14981  * Returns NULL if no routing header
14982  */
14983 in6_addr_t *
14984 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
14985 {
14986 	in6_addr_t	*nexthop = NULL;
14987 	ip6_rthdr0_t	*rthdr;
14988 
14989 	if (!(ipp->ipp_fields & IPPF_RTHDR))
14990 		return (NULL);
14991 
14992 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
14993 	if (rthdr->ip6r0_segleft == 0)
14994 		return (NULL);
14995 
14996 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
14997 	return (nexthop);
14998 }
14999 
15000 zoneid_t
15001 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15002     zoneid_t lookup_zoneid)
15003 {
15004 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15005 	ire_t		*ire;
15006 	int		ire_flags = MATCH_IRE_TYPE;
15007 	zoneid_t	zoneid = ALL_ZONES;
15008 
15009 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15010 		return (ALL_ZONES);
15011 
15012 	if (lookup_zoneid != ALL_ZONES)
15013 		ire_flags |= MATCH_IRE_ZONEONLY;
15014 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15015 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15016 	if (ire != NULL) {
15017 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15018 		ire_refrele(ire);
15019 	}
15020 	return (zoneid);
15021 }
15022 
15023 zoneid_t
15024 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15025     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15026 {
15027 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15028 	ire_t		*ire;
15029 	int		ire_flags = MATCH_IRE_TYPE;
15030 	zoneid_t	zoneid = ALL_ZONES;
15031 
15032 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15033 		return (ALL_ZONES);
15034 
15035 	if (IN6_IS_ADDR_LINKLOCAL(addr))
15036 		ire_flags |= MATCH_IRE_ILL;
15037 
15038 	if (lookup_zoneid != ALL_ZONES)
15039 		ire_flags |= MATCH_IRE_ZONEONLY;
15040 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15041 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15042 	if (ire != NULL) {
15043 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15044 		ire_refrele(ire);
15045 	}
15046 	return (zoneid);
15047 }
15048 
15049 /*
15050  * IP obserability hook support functions.
15051  */
15052 static void
15053 ipobs_init(ip_stack_t *ipst)
15054 {
15055 	netid_t id;
15056 
15057 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15058 
15059 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15060 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15061 
15062 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15063 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15064 }
15065 
15066 static void
15067 ipobs_fini(ip_stack_t *ipst)
15068 {
15069 
15070 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15071 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15072 }
15073 
15074 /*
15075  * hook_pkt_observe_t is composed in network byte order so that the
15076  * entire mblk_t chain handed into hook_run can be used as-is.
15077  * The caveat is that use of the fields, such as the zone fields,
15078  * requires conversion into host byte order first.
15079  */
15080 void
15081 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15082     const ill_t *ill, ip_stack_t *ipst)
15083 {
15084 	hook_pkt_observe_t *hdr;
15085 	uint64_t grifindex;
15086 	mblk_t *imp;
15087 
15088 	imp = allocb(sizeof (*hdr), BPRI_HI);
15089 	if (imp == NULL)
15090 		return;
15091 
15092 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15093 	/*
15094 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15095 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15096 	 */
15097 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15098 	imp->b_cont = mp;
15099 
15100 	ASSERT(DB_TYPE(mp) == M_DATA);
15101 
15102 	if (IS_UNDER_IPMP(ill))
15103 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15104 	else
15105 		grifindex = 0;
15106 
15107 	hdr->hpo_version = 1;
15108 	hdr->hpo_htype = htons(htype);
15109 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15110 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15111 	hdr->hpo_grifindex = htonl(grifindex);
15112 	hdr->hpo_zsrc = htonl(zsrc);
15113 	hdr->hpo_zdst = htonl(zdst);
15114 	hdr->hpo_pkt = imp;
15115 	hdr->hpo_ctx = ipst->ips_netstack;
15116 
15117 	if (ill->ill_isv6) {
15118 		hdr->hpo_family = AF_INET6;
15119 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15120 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15121 	} else {
15122 		hdr->hpo_family = AF_INET;
15123 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15124 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15125 	}
15126 
15127 	imp->b_cont = NULL;
15128 	freemsg(imp);
15129 }
15130 
15131 /*
15132  * Utility routine that checks if `v4srcp' is a valid address on underlying
15133  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15134  * associated with `v4srcp' on success.  NOTE: if this is not called from
15135  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15136  * group during or after this lookup.
15137  */
15138 boolean_t
15139 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15140 {
15141 	ipif_t *ipif;
15142 
15143 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15144 	if (ipif != NULL) {
15145 		if (ipifp != NULL)
15146 			*ipifp = ipif;
15147 		else
15148 			ipif_refrele(ipif);
15149 		return (B_TRUE);
15150 	}
15151 
15152 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15153 	    *v4srcp));
15154 	return (B_FALSE);
15155 }
15156 
15157 /*
15158  * Transport protocol call back function for CPU state change.
15159  */
15160 /* ARGSUSED */
15161 static int
15162 ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
15163 {
15164 	processorid_t cpu_seqid;
15165 	netstack_handle_t nh;
15166 	netstack_t *ns;
15167 
15168 	ASSERT(MUTEX_HELD(&cpu_lock));
15169 
15170 	switch (what) {
15171 	case CPU_CONFIG:
15172 	case CPU_ON:
15173 	case CPU_INIT:
15174 	case CPU_CPUPART_IN:
15175 		cpu_seqid = cpu[id]->cpu_seqid;
15176 		netstack_next_init(&nh);
15177 		while ((ns = netstack_next(&nh)) != NULL) {
15178 			tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
15179 			sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
15180 			udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
15181 			netstack_rele(ns);
15182 		}
15183 		netstack_next_fini(&nh);
15184 		break;
15185 	case CPU_UNCONFIG:
15186 	case CPU_OFF:
15187 	case CPU_CPUPART_OUT:
15188 		/*
15189 		 * Nothing to do.  We don't remove the per CPU stats from
15190 		 * the IP stack even when the CPU goes offline.
15191 		 */
15192 		break;
15193 	default:
15194 		break;
15195 	}
15196 	return (0);
15197 }
15198