xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 4f1fc35da1d29699488fd1c9472dbeb042b2b9d0)
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 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/suntpi.h>
42 #include <sys/cmn_err.h>
43 #include <sys/debug.h>
44 #include <sys/kobj.h>
45 #include <sys/modctl.h>
46 #include <sys/atomic.h>
47 #include <sys/policy.h>
48 #include <sys/priv.h>
49 #include <sys/taskq.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/sdt.h>
55 #include <sys/socket.h>
56 #include <sys/vtrace.h>
57 #include <sys/isa_defs.h>
58 #include <sys/mac.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/optcom.h>
73 #include <inet/kstatcom.h>
74 
75 #include <netinet/igmp_var.h>
76 #include <netinet/ip6.h>
77 #include <netinet/icmp6.h>
78 #include <netinet/sctp.h>
79 
80 #include <inet/ip.h>
81 #include <inet/ip_impl.h>
82 #include <inet/ip6.h>
83 #include <inet/ip6_asp.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/ip_multi.h>
87 #include <inet/ip_if.h>
88 #include <inet/ip_ire.h>
89 #include <inet/ip_ftable.h>
90 #include <inet/ip_rts.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <inet/iptun/iptun_impl.h>
101 #include <inet/ipdrop.h>
102 #include <inet/ip_netinfo.h>
103 #include <inet/ilb_ip.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/pattr.h>
114 #include <inet/ipclassifier.h>
115 #include <inet/sctp_ip.h>
116 #include <inet/sctp/sctp_impl.h>
117 #include <inet/udp_impl.h>
118 #include <inet/rawip_impl.h>
119 #include <inet/rts_impl.h>
120 
121 #include <sys/tsol/label.h>
122 #include <sys/tsol/tnet.h>
123 
124 #include <sys/squeue_impl.h>
125 #include <inet/ip_arp.h>
126 
127 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 
139 /*
140  * Setable in /etc/system
141  */
142 int ip_poll_normal_ms = 100;
143 int ip_poll_normal_ticks = 0;
144 int ip_modclose_ackwait_ms = 3000;
145 
146 /*
147  * It would be nice to have these present only in DEBUG systems, but the
148  * current design of the global symbol checking logic requires them to be
149  * unconditionally present.
150  */
151 uint_t ip_thread_data;			/* TSD key for debug support */
152 krwlock_t ip_thread_rwlock;
153 list_t	ip_thread_list;
154 
155 /*
156  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
157  */
158 
159 struct listptr_s {
160 	mblk_t	*lp_head;	/* pointer to the head of the list */
161 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
162 };
163 
164 typedef struct listptr_s listptr_t;
165 
166 /*
167  * This is used by ip_snmp_get_mib2_ip_route_media and
168  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
169  */
170 typedef struct iproutedata_s {
171 	uint_t		ird_idx;
172 	uint_t		ird_flags;	/* see below */
173 	listptr_t	ird_route;	/* ipRouteEntryTable */
174 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
175 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
176 } iproutedata_t;
177 
178 /* Include ire_testhidden and IRE_IF_CLONE routes */
179 #define	IRD_REPORT_ALL	0x01
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, IPMP operations, most set ioctls, etc.
236  *
237  * Plumbing is a long sequence of operations involving message
238  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
239  * involved in plumbing operations. A natural model is to serialize these
240  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
241  * parallel without any interference. But various set ioctls on hme0 are best
242  * serialized, along with IPMP operations and processing of DLPI control
243  * messages received from drivers on a per phyint basis. This serialization is
244  * provided by the ipsq_t and primitives operating on this. Details can
245  * be found in ip_if.c above the core primitives operating on ipsq_t.
246  *
247  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
248  * Simiarly lookup of an ire by a thread also returns a refheld ire.
249  * In addition ipif's and ill's referenced by the ire are also indirectly
250  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
251  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
252  * address of an ipif has to go through the ipsq_t. This ensures that only
253  * one such exclusive operation proceeds at any time on the ipif. It then
254  * waits for all refcnts
255  * associated with this ipif to come down to zero. The address is changed
256  * only after the ipif has been quiesced. Then the ipif is brought up again.
257  * More details are described above the comment in ip_sioctl_flags.
258  *
259  * Packet processing is based mostly on IREs and are fully multi-threaded
260  * using standard Solaris MT techniques.
261  *
262  * There are explicit locks in IP to handle:
263  * - The ip_g_head list maintained by mi_open_link() and friends.
264  *
265  * - The reassembly data structures (one lock per hash bucket)
266  *
267  * - conn_lock is meant to protect conn_t fields. The fields actually
268  *   protected by conn_lock are documented in the conn_t definition.
269  *
270  * - ire_lock to protect some of the fields of the ire, IRE tables
271  *   (one lock per hash bucket). Refer to ip_ire.c for details.
272  *
273  * - ndp_g_lock and ncec_lock for protecting NCEs.
274  *
275  * - ill_lock protects fields of the ill and ipif. Details in ip.h
276  *
277  * - ill_g_lock: This is a global reader/writer lock. Protects the following
278  *	* The AVL tree based global multi list of all ills.
279  *	* The linked list of all ipifs of an ill
280  *	* The <ipsq-xop> mapping
281  *	* <ill-phyint> association
282  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
283  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
284  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
285  *   writer for the actual duration of the insertion/deletion/change.
286  *
287  * - ill_lock:  This is a per ill mutex.
288  *   It protects some members of the ill_t struct; see ip.h for details.
289  *   It also protects the <ill-phyint> assoc.
290  *   It also protects the list of ipifs hanging off the ill.
291  *
292  * - ipsq_lock: This is a per ipsq_t mutex lock.
293  *   This protects some members of the ipsq_t struct; see ip.h for details.
294  *   It also protects the <ipsq-ipxop> mapping
295  *
296  * - ipx_lock: This is a per ipxop_t mutex lock.
297  *   This protects some members of the ipxop_t struct; see ip.h for details.
298  *
299  * - phyint_lock: This is a per phyint mutex lock. Protects just the
300  *   phyint_flags
301  *
302  * - ip_g_nd_lock: This is a global reader/writer lock.
303  *   Any call to nd_load to load a new parameter to the ND table must hold the
304  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
305  *   as reader.
306  *
307  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
308  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
309  *   uniqueness check also done atomically.
310  *
311  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
312  *   group list linked by ill_usesrc_grp_next. It also protects the
313  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
314  *   group is being added or deleted.  This lock is taken as a reader when
315  *   walking the list/group(eg: to get the number of members in a usesrc group).
316  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
317  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
318  *   example, it is not necessary to take this lock in the initial portion
319  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
320  *   operations are executed exclusively and that ensures that the "usesrc
321  *   group state" cannot change. The "usesrc group state" change can happen
322  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
323  *
324  * Changing <ill-phyint>, <ipsq-xop> assocications:
325  *
326  * To change the <ill-phyint> association, the ill_g_lock must be held
327  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
328  * must be held.
329  *
330  * To change the <ipsq-xop> association, the ill_g_lock must be held as
331  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
332  * This is only done when ills are added or removed from IPMP groups.
333  *
334  * To add or delete an ipif from the list of ipifs hanging off the ill,
335  * ill_g_lock (writer) and ill_lock must be held and the thread must be
336  * a writer on the associated ipsq.
337  *
338  * To add or delete an ill to the system, the ill_g_lock must be held as
339  * writer and the thread must be a writer on the associated ipsq.
340  *
341  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
342  * must be a writer on the associated ipsq.
343  *
344  * Lock hierarchy
345  *
346  * Some lock hierarchy scenarios are listed below.
347  *
348  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
349  * ill_g_lock -> ill_lock(s) -> phyint_lock
350  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
351  * ill_g_lock -> ip_addr_avail_lock
352  * conn_lock -> irb_lock -> ill_lock -> ire_lock
353  * ill_g_lock -> ip_g_nd_lock
354  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
355  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
356  * arl_lock -> ill_lock
357  * ips_ire_dep_lock -> irb_lock
358  *
359  * When more than 1 ill lock is needed to be held, all ill lock addresses
360  * are sorted on address and locked starting from highest addressed lock
361  * downward.
362  *
363  * Multicast scenarios
364  * ips_ill_g_lock -> ill_mcast_lock
365  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
366  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
367  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
368  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
369  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
370  *
371  * IPsec scenarios
372  *
373  * ipsa_lock -> ill_g_lock -> ill_lock
374  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
375  *
376  * Trusted Solaris scenarios
377  *
378  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
379  * igsa_lock -> gcdb_lock
380  * gcgrp_rwlock -> ire_lock
381  * gcgrp_rwlock -> gcdb_lock
382  *
383  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
384  *
385  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
386  * sq_lock -> conn_lock -> QLOCK(q)
387  * ill_lock -> ft_lock -> fe_lock
388  *
389  * Routing/forwarding table locking notes:
390  *
391  * Lock acquisition order: Radix tree lock, irb_lock.
392  * Requirements:
393  * i.  Walker must not hold any locks during the walker callback.
394  * ii  Walker must not see a truncated tree during the walk because of any node
395  *     deletion.
396  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
397  *     in many places in the code to walk the irb list. Thus even if all the
398  *     ires in a bucket have been deleted, we still can't free the radix node
399  *     until the ires have actually been inactive'd (freed).
400  *
401  * Tree traversal - Need to hold the global tree lock in read mode.
402  * Before dropping the global tree lock, need to either increment the ire_refcnt
403  * to ensure that the radix node can't be deleted.
404  *
405  * Tree add - Need to hold the global tree lock in write mode to add a
406  * radix node. To prevent the node from being deleted, increment the
407  * irb_refcnt, after the node is added to the tree. The ire itself is
408  * added later while holding the irb_lock, but not the tree lock.
409  *
410  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
411  * All associated ires must be inactive (i.e. freed), and irb_refcnt
412  * must be zero.
413  *
414  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
415  * global tree lock (read mode) for traversal.
416  *
417  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
418  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
419  *
420  * IPsec notes :
421  *
422  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
423  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
424  * ip_xmit_attr_t has the
425  * information used by the IPsec code for applying the right level of
426  * protection. The information initialized by IP in the ip_xmit_attr_t
427  * is determined by the per-socket policy or global policy in the system.
428  * For inbound datagrams, the ip_recv_attr_t
429  * starts out with nothing in it. It gets filled
430  * with the right information if it goes through the AH/ESP code, which
431  * happens if the incoming packet is secure. The information initialized
432  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
433  * the policy requirements needed by per-socket policy or global policy
434  * is met or not.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_policy_set once the destination is known.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  * ---------------------
455  * Non-TCP streams are flow controlled by IP. The way this is accomplished
456  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
457  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
458  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
459  * functions.
460  *
461  * Per Tx ring udp flow control:
462  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
463  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
464  *
465  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
466  * To achieve best performance, outgoing traffic need to be fanned out among
467  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
468  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
469  * the address of connp as fanout hint to mac_tx(). Under flow controlled
470  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
471  * cookie points to a specific Tx ring that is blocked. The cookie is used to
472  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
473  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
474  * connp's. The drain list is not a single list but a configurable number of
475  * lists.
476  *
477  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
478  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
479  * which is equal to 128. This array in turn contains a pointer to idl_t[],
480  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
481  * list will point to the list of connp's that are flow controlled.
482  *
483  *                      ---------------   -------   -------   -------
484  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   |  ---------------   -------   -------   -------
487  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
488  * ----------------  |  ---------------   -------   -------   -------
489  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
490  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
491  *                   |  ---------------   -------   -------   -------
492  *                   .        .              .         .         .
493  *                   |  ---------------   -------   -------   -------
494  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
495  *                      ---------------   -------   -------   -------
496  *                      ---------------   -------   -------   -------
497  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
498  *                   |  ---------------   -------   -------   -------
499  *                   |  ---------------   -------   -------   -------
500  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
501  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
502  * ----------------  |        .              .         .         .
503  *                   |  ---------------   -------   -------   -------
504  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
505  *                      ---------------   -------   -------   -------
506  *     .....
507  * ----------------
508  * |idl_tx_list[n]|-> ...
509  * ----------------
510  *
511  * When mac_tx() returns a cookie, the cookie is used to hash into a
512  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
513  * called passing idl_tx_list. The connp gets inserted in a drain list
514  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
515  * the sockets (non stream based) and sets QFULL condition on the conn_wq
516  * of streams sockets, or the su_txqfull for non-streams sockets.
517  * connp->conn_direct_blocked will be set to indicate the blocked
518  * condition.
519  *
520  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
521  * A cookie is passed in the call to ill_flow_enable() that identifies the
522  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
523  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
524  * and goes through each conn in the drain list and calls conn_idl_remove
525  * for the conn to clear the qfull condition for the conn, as well as to
526  * remove the conn from the idl list. In addition, streams based sockets
527  * will have the conn_wq enabled, causing ip_wsrv to run for the
528  * conn. ip_wsrv drains the queued messages, and removes the conn from the
529  * drain list, if all messages were drained. It also notifies the
530  * conn_upcalls for the conn to signal that flow-control has opened up.
531  *
532  * In reality the drain list is not a single list, but a configurable number
533  * of lists. conn_walk_drain() in the IP module, notifies the conn_upcalls for
534  * each conn in the list. conn_drain_insert and conn_drain_tail are the only
535  * functions that manipulate this drain list. conn_drain_insert is called in
536  * from the protocol layer when conn_ip_output returns EWOULDBLOCK.
537  * (as opposed to from ip_wsrv context for STREAMS
538  * case -- see below). The synchronization between drain insertion and flow
539  * control wakeup is handled by using idl_txl->txl_lock.
540  *
541  * Flow control using STREAMS:
542  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
543  * is used. On the send side, if the packet cannot be sent down to the
544  * driver by IP, because of a canput failure, ip_xmit drops the packet
545  * and returns EWOULDBLOCK to the caller, who may then invoke
546  * ixa_check_drain_insert to insert the conn on the 0'th drain list.
547  * When ip_wsrv runs on the ill_wq because flow control has been relieved, the
548  * blocked conns in the * 0'th drain list is drained as with the
549  * non-STREAMS case.
550  *
551  * In both the STREAMS and non-STREAMS case, the sockfs upcall to set
552  * qfull is done when the conn is inserted into the drain list
553  * (conn_drain_insert()) and cleared when the conn is removed from the drain
554  * list (conn_idl_remove()).
555  *
556  * IPQOS notes:
557  *
558  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
559  * and IPQoS modules. IPPF includes hooks in IP at different control points
560  * (callout positions) which direct packets to IPQoS modules for policy
561  * processing. Policies, if present, are global.
562  *
563  * The callout positions are located in the following paths:
564  *		o local_in (packets destined for this host)
565  *		o local_out (packets orginating from this host )
566  *		o fwd_in  (packets forwarded by this m/c - inbound)
567  *		o fwd_out (packets forwarded by this m/c - outbound)
568  * Hooks at these callout points can be enabled/disabled using the ndd variable
569  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
570  * By default all the callout positions are enabled.
571  *
572  * Outbound (local_out)
573  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
574  *
575  * Inbound (local_in)
576  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
577  *
578  * Forwarding (in and out)
579  * Hooks are placed in ire_recv_forward_v4/v6.
580  *
581  * IP Policy Framework processing (IPPF processing)
582  * Policy processing for a packet is initiated by ip_process, which ascertains
583  * that the classifier (ipgpc) is loaded and configured, failing which the
584  * packet resumes normal processing in IP. If the clasifier is present, the
585  * packet is acted upon by one or more IPQoS modules (action instances), per
586  * filters configured in ipgpc and resumes normal IP processing thereafter.
587  * An action instance can drop a packet in course of its processing.
588  *
589  * Zones notes:
590  *
591  * The partitioning rules for networking are as follows:
592  * 1) Packets coming from a zone must have a source address belonging to that
593  * zone.
594  * 2) Packets coming from a zone can only be sent on a physical interface on
595  * which the zone has an IP address.
596  * 3) Between two zones on the same machine, packet delivery is only allowed if
597  * there's a matching route for the destination and zone in the forwarding
598  * table.
599  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
600  * different zones can bind to the same port with the wildcard address
601  * (INADDR_ANY).
602  *
603  * The granularity of interface partitioning is at the logical interface level.
604  * Therefore, every zone has its own IP addresses, and incoming packets can be
605  * attributed to a zone unambiguously. A logical interface is placed into a zone
606  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
607  * structure. Rule (1) is implemented by modifying the source address selection
608  * algorithm so that the list of eligible addresses is filtered based on the
609  * sending process zone.
610  *
611  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
612  * across all zones, depending on their type. Here is the break-up:
613  *
614  * IRE type				Shared/exclusive
615  * --------				----------------
616  * IRE_BROADCAST			Exclusive
617  * IRE_DEFAULT (default routes)		Shared (*)
618  * IRE_LOCAL				Exclusive (x)
619  * IRE_LOOPBACK				Exclusive
620  * IRE_PREFIX (net routes)		Shared (*)
621  * IRE_IF_NORESOLVER (interface routes)	Exclusive
622  * IRE_IF_RESOLVER (interface routes)	Exclusive
623  * IRE_IF_CLONE (interface routes)	Exclusive
624  * IRE_HOST (host routes)		Shared (*)
625  *
626  * (*) A zone can only use a default or off-subnet route if the gateway is
627  * directly reachable from the zone, that is, if the gateway's address matches
628  * one of the zone's logical interfaces.
629  *
630  * (x) IRE_LOCAL are handled a bit differently.
631  * When ip_restrict_interzone_loopback is set (the default),
632  * ire_route_recursive restricts loopback using an IRE_LOCAL
633  * between zone to the case when L2 would have conceptually looped the packet
634  * back, i.e. the loopback which is required since neither Ethernet drivers
635  * nor Ethernet hardware loops them back. This is the case when the normal
636  * routes (ignoring IREs with different zoneids) would send out the packet on
637  * the same ill as the ill with which is IRE_LOCAL is associated.
638  *
639  * Multiple zones can share a common broadcast address; typically all zones
640  * share the 255.255.255.255 address. Incoming as well as locally originated
641  * broadcast packets must be dispatched to all the zones on the broadcast
642  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
643  * since some zones may not be on the 10.16.72/24 network. To handle this, each
644  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
645  * sent to every zone that has an IRE_BROADCAST entry for the destination
646  * address on the input ill, see ip_input_broadcast().
647  *
648  * Applications in different zones can join the same multicast group address.
649  * The same logic applies for multicast as for broadcast. ip_input_multicast
650  * dispatches packets to all zones that have members on the physical interface.
651  */
652 
653 /*
654  * Squeue Fanout flags:
655  *	0: No fanout.
656  *	1: Fanout across all squeues
657  */
658 boolean_t	ip_squeue_fanout = 0;
659 
660 /*
661  * Maximum dups allowed per packet.
662  */
663 uint_t ip_max_frag_dups = 10;
664 
665 /* RFC 1122 Conformance */
666 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
667 
668 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
669 		    cred_t *credp, boolean_t isv6);
670 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
671 
672 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
673 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
674 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
675     ip_recv_attr_t *);
676 static void	icmp_options_update(ipha_t *);
677 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
678 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
679 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
680 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
681     ip_recv_attr_t *);
682 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
683 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
684     ip_recv_attr_t *);
685 
686 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
687 char		*ip_dot_addr(ipaddr_t, char *);
688 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
689 int		ip_close(queue_t *, int);
690 static char	*ip_dot_saddr(uchar_t *, char *);
691 static void	ip_lrput(queue_t *, mblk_t *);
692 ipaddr_t	ip_net_mask(ipaddr_t);
693 char		*ip_nv_lookup(nv_t *, int);
694 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
695 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
696 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
697     ipndp_t *, size_t);
698 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
699 void	ip_rput(queue_t *, mblk_t *);
700 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
701 		    void *dummy_arg);
702 int		ip_snmp_get(queue_t *, mblk_t *, int);
703 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
704 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
705 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
706 		    ip_stack_t *);
707 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
708 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
709 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
710 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
711 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
712 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
713 		    ip_stack_t *ipst);
714 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
715 		    ip_stack_t *ipst);
716 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
717 		    ip_stack_t *ipst);
718 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
719 		    ip_stack_t *ipst);
720 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
721 		    ip_stack_t *ipst);
722 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
723 		    ip_stack_t *ipst);
724 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
725 		    ip_stack_t *ipst);
726 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
727 		    ip_stack_t *ipst);
728 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
729 		    ip_stack_t *ipst);
730 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
731 		    ip_stack_t *ipst);
732 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
733 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
734 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
735 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
736 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
737 
738 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
739 		    mblk_t *);
740 
741 static void	conn_drain_init(ip_stack_t *);
742 static void	conn_drain_fini(ip_stack_t *);
743 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
744 
745 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
746 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
747 
748 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
749 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
750 static void	ip_stack_fini(netstackid_t stackid, void *arg);
751 
752 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
753 
754 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
755     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
756     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
757     const in6_addr_t *);
758 
759 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
760 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
761     caddr_t, cred_t *);
762 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
763     caddr_t cp, cred_t *cr);
764 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
765     cred_t *);
766 static int	ip_squeue_switch(int);
767 
768 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
769 static void	ip_kstat_fini(netstackid_t, kstat_t *);
770 static int	ip_kstat_update(kstat_t *kp, int rw);
771 static void	*icmp_kstat_init(netstackid_t);
772 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
773 static int	icmp_kstat_update(kstat_t *kp, int rw);
774 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
775 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
776 
777 static void	ipobs_init(ip_stack_t *);
778 static void	ipobs_fini(ip_stack_t *);
779 
780 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
781 
782 /* How long, in seconds, we allow frags to hang around. */
783 #define	IP_FRAG_TIMEOUT		15
784 #define	IPV6_FRAG_TIMEOUT	60
785 
786 static long ip_rput_pullups;
787 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
788 
789 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
790 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
791 
792 int	ip_debug;
793 
794 /*
795  * Multirouting/CGTP stuff
796  */
797 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
798 
799 /*
800  * Named Dispatch Parameter Table.
801  * All of these are alterable, within the min/max values given, at run time.
802  */
803 static ipparam_t	lcl_param_arr[] = {
804 	/* min	max	value	name */
805 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
806 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
807 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
808 	{  0,	1,	0,	"ip_respond_to_timestamp"},
809 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
810 	{  0,	1,	1,	"ip_send_redirects"},
811 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
812 	{  0,	10,	0,	"ip_mrtdebug"},
813 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
814 	{  1,	8,	3,	"ip_nce_reclaim_fraction" },
815 	{  1,	8,	3,	"ip_dce_reclaim_fraction" },
816 	{  1,	255,	255,	"ip_def_ttl" },
817 	{  0,	1,	0,	"ip_forward_src_routed"},
818 	{  0,	256,	32,	"ip_wroff_extra" },
819 	{  2, 999999999, 60*20, "ip_pathmtu_interval" },	/* In seconds */
820 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
821 	{  0,	1,	1,	"ip_path_mtu_discovery" },
822 	{ 68,	65535,	576,	"ip_pmtu_min" },
823 	{  0,	1,	0,	"ip_ignore_redirect" },
824 	{  0,	1,	0,	"ip_arp_icmp_error" },
825 	{  1,	254,	1,	"ip_broadcast_ttl" },
826 	{  0,	99999,	100,	"ip_icmp_err_interval" },
827 	{  1,	99999,	10,	"ip_icmp_err_burst" },
828 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
829 	/*
830 	 * See comments for ip_strict_src_multihoming for an explanation
831 	 * of the semantics of ip_strict_dst_multihoming
832 	 */
833 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
834 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
835 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
836 	{  0,	1,	1,	"icmp_accept_clear_messages" },
837 	{  0,	1,	1,	"igmp_accept_clear_messages" },
838 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
839 				"ip_ndp_delay_first_probe_time"},
840 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
841 				"ip_ndp_max_unicast_solicit"},
842 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
843 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
844 	{  0,	1,	0,	"ip6_forward_src_routed"},
845 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
846 	{  0,	1,	1,	"ip6_send_redirects"},
847 	{  0,	1,	0,	"ip6_ignore_redirect" },
848 	/*
849 	 * See comments for ip6_strict_src_multihoming for an explanation
850 	 * of the semantics of ip6_strict_dst_multihoming
851 	 */
852 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
853 
854 	{  0,	2,	2,	"ip_src_check" },
855 
856 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
857 
858 	{  0,	1,	1,	"pim_accept_clear_messages" },
859 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
860 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
861 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
862 	{  0,	15,	0,	"ip_policy_mask" },
863 	{  0,	2,	2,	"ip_ecmp_behavior" },
864 	{  0,	255,	1,	"ip_multirt_ttl" },
865 	{  0,	3600,	60,	"ip_ire_badcnt_lifetime" },	/* In seconds */
866 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
867 	{  0,	1000,	1,	"ip_max_temp_defend" },
868 	/*
869 	 * when a conflict of an active address is detected,
870 	 * defend up to ip_max_defend times, within any
871 	 * ip_defend_interval span.
872 	 */
873 	{  0,	1000,	3,	"ip_max_defend" },
874 	{  0,	999999,	30,	"ip_defend_interval" },
875 	{  0,	3600000, 300000, "ip_dup_recovery" },
876 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
877 	{  0,	1,	1,	"ip_lso_outbound" },
878 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
879 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
880 #ifdef DEBUG
881 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
882 #else
883 	{  0,	0,	0,	"" },
884 #endif
885 	/* delay before sending first probe: */
886 	{  0,	20000,	1000,	"arp_probe_delay" },
887 	{  0,	20000,	100,	"arp_fastprobe_delay" },
888 	/* interval at which DAD probes are sent: */
889 	{ 10,	20000,	1500,	"arp_probe_interval" },
890 	{ 10,	20000,	150,	"arp_fastprobe_interval" },
891 	/* setting probe count to 0 will disable ARP probing for DAD. */
892 	{  0,	20,	3,	"arp_probe_count" },
893 	{  0,	20,	3,	"arp_fastprobe_count" },
894 
895 	{  0,	3600000, 15000,	"ipv4_dad_announce_interval"},
896 	{  0,	3600000, 15000,	"ipv6_dad_announce_interval"},
897 	/*
898 	 * Rate limiting parameters for DAD defense used in
899 	 * ill_defend_rate_limit():
900 	 * defend_rate : pkts/hour permitted
901 	 * defend_interval : time that can elapse before we send out a
902 	 *			DAD defense.
903 	 * defend_period: denominator for defend_rate (in seconds).
904 	 */
905 	{  0,	3600000, 300000,	"arp_defend_interval"},
906 	{  0,	20000, 100,		"arp_defend_rate"},
907 	{  0,	3600000, 300000,	"ndp_defend_interval"},
908 	{  0,	20000, 100,		"ndp_defend_rate"},
909 	{  5,	86400,	3600,		"arp_defend_period"},
910 	{  5,	86400,	3600,		"ndp_defend_period"},
911 	{  0,	1,	1,		"ipv4_icmp_return_pmtu" },
912 	{  0,	1,	1,		"ipv6_icmp_return_pmtu" },
913 	/*
914 	 * publish count/interval values used to announce local addresses
915 	 * for IPv4, IPv6.
916 	 */
917 	{  1,	20,	5,	"ip_arp_publish_count" },
918 	{  1000, 20000, 2000,   "ip_arp_publish_interval" },
919 	/*
920 	 * The ip*strict_src_multihoming and ip*strict_dst_multihoming provide
921 	 * a range of choices for setting strong/weak/preferred end-system
922 	 * behavior. The semantics for setting these are:
923 	 *
924 	 * ip*_strict_dst_multihoming = 0
925 	 *    weak end system model for managing ip destination addresses.
926 	 *    A packet with IP dst D1 that's received on interface I1 will be
927 	 *    accepted as long as D1 is one of the local addresses on
928 	 *    the machine, even if D1 is not configured on I1.
929 	 * ip*strict_dst_multihioming = 1
930 	 *    strong end system model for managing ip destination addresses.
931 	 *    A packet with IP dst D1 that's received on interface I1 will be
932 	 *    accepted if, and only if, D1 is configured on I1.
933 	 *
934 	 * ip*strict_src_multihoming = 0
935 	 *    Source agnostic route selection for outgoing packets: the
936 	 *    outgoing interface for a packet will be computed using
937 	 *    default algorithms for route selection, where the route
938 	 *    with the longest matching prefix is chosen for the output
939 	 *    unless other route selection constraints are explicitly
940 	 *    specified during routing table lookup.  This may result
941 	 *    in packet being sent out on interface I2 with source
942 	 *    address S1, even though S1 is not a configured address on I2.
943 	 * ip*strict_src_multihoming = 1
944 	 *    Preferred source aware route selection for outgoing packets: for
945 	 *    a packet with source S2, destination D2, the route selection
946 	 *    algorithm will first attempt to find a route for the destination
947 	 *    that goes out through an interface where S2 is
948 	 *    configured. If such a route cannot be found, then the
949 	 *    best-matching route for D2 will be selected.
950 	 * ip*strict_src_multihoming = 2
951 	 *    Source aware route selection for outgoing packets: a packet will
952 	 *    be sent out on an interface I2 only if the src address S2 of the
953 	 *    packet is a configured address on I2. In conjunction with
954 	 *    the setting 'ip_strict_dst_multihoming == 1', this will result in
955 	 *    the implementation of Strong ES as defined in Section 3.3.4.2 of
956 	 *    RFC 1122
957 	 */
958 	{  0,	2,	0,	"ip_strict_src_multihoming" },
959 	{  0,	2,	0,	"ip6_strict_src_multihoming" }
960 };
961 
962 /*
963  * Extended NDP table
964  * The addresses for the first two are filled in to be ips_ip_g_forward
965  * and ips_ipv6_forward at init time.
966  */
967 static ipndp_t	lcl_ndp_arr[] = {
968 	/* getf			setf		data			name */
969 #define	IPNDP_IP_FORWARDING_OFFSET	0
970 	{  ip_param_generic_get,	ip_forward_set,	NULL,
971 	    "ip_forwarding" },
972 #define	IPNDP_IP6_FORWARDING_OFFSET	1
973 	{  ip_param_generic_get,	ip_forward_set,	NULL,
974 	    "ip6_forwarding" },
975 	{ ip_param_generic_get, ip_input_proc_set,
976 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
977 	{ ip_param_generic_get, ip_int_set,
978 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
979 #define	IPNDP_CGTP_FILTER_OFFSET	4
980 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
981 	    "ip_cgtp_filter" },
982 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
983 	    "ip_debug" },
984 };
985 
986 /*
987  * Table of IP ioctls encoding the various properties of the ioctl and
988  * indexed based on the last byte of the ioctl command. Occasionally there
989  * is a clash, and there is more than 1 ioctl with the same last byte.
990  * In such a case 1 ioctl is encoded in the ndx table and the remaining
991  * ioctls are encoded in the misc table. An entry in the ndx table is
992  * retrieved by indexing on the last byte of the ioctl command and comparing
993  * the ioctl command with the value in the ndx table. In the event of a
994  * mismatch the misc table is then searched sequentially for the desired
995  * ioctl command.
996  *
997  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
998  */
999 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1000 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1001 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1002 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1003 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1004 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1005 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1006 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1007 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1008 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1009 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1010 
1011 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1012 			MISC_CMD, ip_siocaddrt, NULL },
1013 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1014 			MISC_CMD, ip_siocdelrt, NULL },
1015 
1016 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1017 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1018 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1019 			IF_CMD, ip_sioctl_get_addr, NULL },
1020 
1021 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1022 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1023 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1024 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1025 
1026 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1027 			IPI_PRIV | IPI_WR,
1028 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1029 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1030 			IPI_MODOK | IPI_GET_CMD,
1031 			IF_CMD, ip_sioctl_get_flags, NULL },
1032 
1033 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* copyin size cannot be coded for SIOCGIFCONF */
1037 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1038 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1039 
1040 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1041 			IF_CMD, ip_sioctl_mtu, NULL },
1042 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1043 			IF_CMD, ip_sioctl_get_mtu, NULL },
1044 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1045 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1046 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1047 			IF_CMD, ip_sioctl_brdaddr, NULL },
1048 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1049 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1050 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1051 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1052 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1053 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1054 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1055 			IF_CMD, ip_sioctl_metric, NULL },
1056 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 
1058 	/* See 166-168 below for extended SIOC*XARP ioctls */
1059 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1060 			ARP_CMD, ip_sioctl_arp, NULL },
1061 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1062 			ARP_CMD, ip_sioctl_arp, NULL },
1063 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1064 			ARP_CMD, ip_sioctl_arp, NULL },
1065 
1066 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1087 
1088 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1089 			MISC_CMD, if_unitsel, if_unitsel_restart },
1090 
1091 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 
1110 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1111 			IPI_PRIV | IPI_WR | IPI_MODOK,
1112 			IF_CMD, ip_sioctl_sifname, NULL },
1113 
1114 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 
1128 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1129 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1130 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1131 			IF_CMD, ip_sioctl_get_muxid, NULL },
1132 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1133 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1134 
1135 	/* Both if and lif variants share same func */
1136 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1137 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1138 	/* Both if and lif variants share same func */
1139 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1140 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1141 
1142 	/* copyin size cannot be coded for SIOCGIFCONF */
1143 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1144 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1145 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1159 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1160 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 
1163 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1164 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1165 			ip_sioctl_removeif_restart },
1166 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1167 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1168 			LIF_CMD, ip_sioctl_addif, NULL },
1169 #define	SIOCLIFADDR_NDX 112
1170 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1171 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1172 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1173 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1174 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1175 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1176 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1177 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1178 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1179 			IPI_PRIV | IPI_WR,
1180 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1181 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1182 			IPI_GET_CMD | IPI_MODOK,
1183 			LIF_CMD, ip_sioctl_get_flags, NULL },
1184 
1185 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 
1188 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1189 			ip_sioctl_get_lifconf, NULL },
1190 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1191 			LIF_CMD, ip_sioctl_mtu, NULL },
1192 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1193 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1194 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1195 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1196 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1197 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1198 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1199 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1200 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1201 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1202 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1203 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1204 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1205 			LIF_CMD, ip_sioctl_metric, NULL },
1206 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1207 			IPI_PRIV | IPI_WR | IPI_MODOK,
1208 			LIF_CMD, ip_sioctl_slifname,
1209 			ip_sioctl_slifname_restart },
1210 
1211 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1212 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1213 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1214 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1215 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1216 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1217 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1218 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1219 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1220 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1221 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1222 			LIF_CMD, ip_sioctl_token, NULL },
1223 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1224 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1225 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1226 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1227 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1228 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1229 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1230 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1231 
1232 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1233 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1234 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1235 			LIF_CMD, ip_siocdelndp_v6, NULL },
1236 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1237 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1238 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1239 			LIF_CMD, ip_siocsetndp_v6, NULL },
1240 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1241 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1242 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1243 			MISC_CMD, ip_sioctl_tonlink, NULL },
1244 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1245 			MISC_CMD, ip_sioctl_tmysite, NULL },
1246 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1247 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1248 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1249 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1250 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1251 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1252 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1253 
1254 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1255 
1256 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1257 			LIF_CMD, ip_sioctl_get_binding, NULL },
1258 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1259 			IPI_PRIV | IPI_WR,
1260 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1261 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1262 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1263 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1264 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1265 
1266 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1267 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1268 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1269 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1270 
1271 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1272 
1273 	/* These are handled in ip_sioctl_copyin_setup itself */
1274 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1275 			MISC_CMD, NULL, NULL },
1276 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1277 			MISC_CMD, NULL, NULL },
1278 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1279 
1280 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1281 			ip_sioctl_get_lifconf, NULL },
1282 
1283 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1284 			XARP_CMD, ip_sioctl_arp, NULL },
1285 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1286 			XARP_CMD, ip_sioctl_arp, NULL },
1287 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1288 			XARP_CMD, ip_sioctl_arp, NULL },
1289 
1290 	/* SIOCPOPSOCKFS is not handled by IP */
1291 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1292 
1293 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1294 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1295 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1296 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1297 			ip_sioctl_slifzone_restart },
1298 	/* 172-174 are SCTP ioctls and not handled by IP */
1299 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1300 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1301 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1302 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1303 			IPI_GET_CMD, LIF_CMD,
1304 			ip_sioctl_get_lifusesrc, 0 },
1305 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1306 			IPI_PRIV | IPI_WR,
1307 			LIF_CMD, ip_sioctl_slifusesrc,
1308 			NULL },
1309 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1310 			ip_sioctl_get_lifsrcof, NULL },
1311 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1312 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1313 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1314 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1315 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1316 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1317 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1318 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1319 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1320 	/* SIOCSENABLESDP is handled by SDP */
1321 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1322 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1323 	/* 185 */ { IPI_DONTCARE /* SIOCGIFHWADDR */, 0, 0, 0, NULL, NULL },
1324 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1325 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1326 			ip_sioctl_ilb_cmd, NULL },
1327 };
1328 
1329 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1330 
1331 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1332 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1333 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1334 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1335 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1336 	{ ND_GET,	0, 0, 0, NULL, NULL },
1337 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1338 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1339 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1340 		MISC_CMD, mrt_ioctl},
1341 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1342 		MISC_CMD, mrt_ioctl},
1343 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1344 		MISC_CMD, mrt_ioctl}
1345 };
1346 
1347 int ip_misc_ioctl_count =
1348     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1349 
1350 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1351 					/* Settable in /etc/system */
1352 /* Defined in ip_ire.c */
1353 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1354 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1355 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1356 
1357 static nv_t	ire_nv_arr[] = {
1358 	{ IRE_BROADCAST, "BROADCAST" },
1359 	{ IRE_LOCAL, "LOCAL" },
1360 	{ IRE_LOOPBACK, "LOOPBACK" },
1361 	{ IRE_DEFAULT, "DEFAULT" },
1362 	{ IRE_PREFIX, "PREFIX" },
1363 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1364 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1365 	{ IRE_IF_CLONE, "IF_CLONE" },
1366 	{ IRE_HOST, "HOST" },
1367 	{ IRE_MULTICAST, "MULTICAST" },
1368 	{ IRE_NOROUTE, "NOROUTE" },
1369 	{ 0 }
1370 };
1371 
1372 nv_t	*ire_nv_tbl = ire_nv_arr;
1373 
1374 /* Simple ICMP IP Header Template */
1375 static ipha_t icmp_ipha = {
1376 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1377 };
1378 
1379 struct module_info ip_mod_info = {
1380 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1381 	IP_MOD_LOWAT
1382 };
1383 
1384 /*
1385  * Duplicate static symbols within a module confuses mdb; so we avoid the
1386  * problem by making the symbols here distinct from those in udp.c.
1387  */
1388 
1389 /*
1390  * Entry points for IP as a device and as a module.
1391  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1392  */
1393 static struct qinit iprinitv4 = {
1394 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1395 	&ip_mod_info
1396 };
1397 
1398 struct qinit iprinitv6 = {
1399 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1400 	&ip_mod_info
1401 };
1402 
1403 static struct qinit ipwinit = {
1404 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1405 	&ip_mod_info
1406 };
1407 
1408 static struct qinit iplrinit = {
1409 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1410 	&ip_mod_info
1411 };
1412 
1413 static struct qinit iplwinit = {
1414 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1415 	&ip_mod_info
1416 };
1417 
1418 /* For AF_INET aka /dev/ip */
1419 struct streamtab ipinfov4 = {
1420 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1421 };
1422 
1423 /* For AF_INET6 aka /dev/ip6 */
1424 struct streamtab ipinfov6 = {
1425 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1426 };
1427 
1428 #ifdef	DEBUG
1429 boolean_t skip_sctp_cksum = B_FALSE;
1430 #endif
1431 
1432 /*
1433  * Generate an ICMP fragmentation needed message.
1434  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1435  * constructed by the caller.
1436  */
1437 void
1438 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1439 {
1440 	icmph_t	icmph;
1441 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1442 
1443 	mp = icmp_pkt_err_ok(mp, ira);
1444 	if (mp == NULL)
1445 		return;
1446 
1447 	bzero(&icmph, sizeof (icmph_t));
1448 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1449 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1450 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1451 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1452 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1453 
1454 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1455 }
1456 
1457 /*
1458  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1459  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1460  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1461  * Likewise, if the ICMP error is misformed (too short, etc), then it
1462  * returns NULL. The caller uses this to determine whether or not to send
1463  * to raw sockets.
1464  *
1465  * All error messages are passed to the matching transport stream.
1466  *
1467  * The following cases are handled by icmp_inbound:
1468  * 1) It needs to send a reply back and possibly delivering it
1469  *    to the "interested" upper clients.
1470  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1471  * 3) It needs to change some values in IP only.
1472  * 4) It needs to change some values in IP and upper layers e.g TCP
1473  *    by delivering an error to the upper layers.
1474  *
1475  * We handle the above three cases in the context of IPsec in the
1476  * following way :
1477  *
1478  * 1) Send the reply back in the same way as the request came in.
1479  *    If it came in encrypted, it goes out encrypted. If it came in
1480  *    clear, it goes out in clear. Thus, this will prevent chosen
1481  *    plain text attack.
1482  * 2) The client may or may not expect things to come in secure.
1483  *    If it comes in secure, the policy constraints are checked
1484  *    before delivering it to the upper layers. If it comes in
1485  *    clear, ipsec_inbound_accept_clear will decide whether to
1486  *    accept this in clear or not. In both the cases, if the returned
1487  *    message (IP header + 8 bytes) that caused the icmp message has
1488  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1489  *    sending up. If there are only 8 bytes of returned message, then
1490  *    upper client will not be notified.
1491  * 3) Check with global policy to see whether it matches the constaints.
1492  *    But this will be done only if icmp_accept_messages_in_clear is
1493  *    zero.
1494  * 4) If we need to change both in IP and ULP, then the decision taken
1495  *    while affecting the values in IP and while delivering up to TCP
1496  *    should be the same.
1497  *
1498  * 	There are two cases.
1499  *
1500  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1501  *	   failed), we will not deliver it to the ULP, even though they
1502  *	   are *willing* to accept in *clear*. This is fine as our global
1503  *	   disposition to icmp messages asks us reject the datagram.
1504  *
1505  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1506  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1507  *	   to deliver it to ULP (policy failed), it can lead to
1508  *	   consistency problems. The cases known at this time are
1509  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1510  *	   values :
1511  *
1512  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1513  *	     and Upper layer rejects. Then the communication will
1514  *	     come to a stop. This is solved by making similar decisions
1515  *	     at both levels. Currently, when we are unable to deliver
1516  *	     to the Upper Layer (due to policy failures) while IP has
1517  *	     adjusted dce_pmtu, the next outbound datagram would
1518  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1519  *	     will be with the right level of protection. Thus the right
1520  *	     value will be communicated even if we are not able to
1521  *	     communicate when we get from the wire initially. But this
1522  *	     assumes there would be at least one outbound datagram after
1523  *	     IP has adjusted its dce_pmtu value. To make things
1524  *	     simpler, we accept in clear after the validation of
1525  *	     AH/ESP headers.
1526  *
1527  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1528  *	     upper layer depending on the level of protection the upper
1529  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1530  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1531  *	     should be accepted in clear when the Upper layer expects secure.
1532  *	     Thus the communication may get aborted by some bad ICMP
1533  *	     packets.
1534  */
1535 mblk_t *
1536 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1537 {
1538 	icmph_t		*icmph;
1539 	ipha_t		*ipha;		/* Outer header */
1540 	int		ip_hdr_length;	/* Outer header length */
1541 	boolean_t	interested;
1542 	ipif_t		*ipif;
1543 	uint32_t	ts;
1544 	uint32_t	*tsp;
1545 	timestruc_t	now;
1546 	ill_t		*ill = ira->ira_ill;
1547 	ip_stack_t	*ipst = ill->ill_ipst;
1548 	zoneid_t	zoneid = ira->ira_zoneid;
1549 	int		len_needed;
1550 	mblk_t		*mp_ret = NULL;
1551 
1552 	ipha = (ipha_t *)mp->b_rptr;
1553 
1554 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1555 
1556 	ip_hdr_length = ira->ira_ip_hdr_length;
1557 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1558 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1559 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1560 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1561 			freemsg(mp);
1562 			return (NULL);
1563 		}
1564 		/* Last chance to get real. */
1565 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1566 		if (ipha == NULL) {
1567 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1568 			freemsg(mp);
1569 			return (NULL);
1570 		}
1571 	}
1572 
1573 	/* The IP header will always be a multiple of four bytes */
1574 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1575 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1576 	    icmph->icmph_code));
1577 
1578 	/*
1579 	 * We will set "interested" to "true" if we should pass a copy to
1580 	 * the transport or if we handle the packet locally.
1581 	 */
1582 	interested = B_FALSE;
1583 	switch (icmph->icmph_type) {
1584 	case ICMP_ECHO_REPLY:
1585 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1586 		break;
1587 	case ICMP_DEST_UNREACHABLE:
1588 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1589 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1590 		interested = B_TRUE;	/* Pass up to transport */
1591 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1592 		break;
1593 	case ICMP_SOURCE_QUENCH:
1594 		interested = B_TRUE;	/* Pass up to transport */
1595 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1596 		break;
1597 	case ICMP_REDIRECT:
1598 		if (!ipst->ips_ip_ignore_redirect)
1599 			interested = B_TRUE;
1600 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1601 		break;
1602 	case ICMP_ECHO_REQUEST:
1603 		/*
1604 		 * Whether to respond to echo requests that come in as IP
1605 		 * broadcasts or as IP multicast is subject to debate
1606 		 * (what isn't?).  We aim to please, you pick it.
1607 		 * Default is do it.
1608 		 */
1609 		if (ira->ira_flags & IRAF_MULTICAST) {
1610 			/* multicast: respond based on tunable */
1611 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1612 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1613 			/* broadcast: respond based on tunable */
1614 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1615 		} else {
1616 			/* unicast: always respond */
1617 			interested = B_TRUE;
1618 		}
1619 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1620 		if (!interested) {
1621 			/* We never pass these to RAW sockets */
1622 			freemsg(mp);
1623 			return (NULL);
1624 		}
1625 
1626 		/* Check db_ref to make sure we can modify the packet. */
1627 		if (mp->b_datap->db_ref > 1) {
1628 			mblk_t	*mp1;
1629 
1630 			mp1 = copymsg(mp);
1631 			freemsg(mp);
1632 			if (!mp1) {
1633 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1634 				return (NULL);
1635 			}
1636 			mp = mp1;
1637 			ipha = (ipha_t *)mp->b_rptr;
1638 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1639 		}
1640 		icmph->icmph_type = ICMP_ECHO_REPLY;
1641 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1642 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1643 		return (NULL);
1644 
1645 	case ICMP_ROUTER_ADVERTISEMENT:
1646 	case ICMP_ROUTER_SOLICITATION:
1647 		break;
1648 	case ICMP_TIME_EXCEEDED:
1649 		interested = B_TRUE;	/* Pass up to transport */
1650 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1651 		break;
1652 	case ICMP_PARAM_PROBLEM:
1653 		interested = B_TRUE;	/* Pass up to transport */
1654 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1655 		break;
1656 	case ICMP_TIME_STAMP_REQUEST:
1657 		/* Response to Time Stamp Requests is local policy. */
1658 		if (ipst->ips_ip_g_resp_to_timestamp) {
1659 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1660 				interested =
1661 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1662 			else
1663 				interested = B_TRUE;
1664 		}
1665 		if (!interested) {
1666 			/* We never pass these to RAW sockets */
1667 			freemsg(mp);
1668 			return (NULL);
1669 		}
1670 
1671 		/* Make sure we have enough of the packet */
1672 		len_needed = ip_hdr_length + ICMPH_SIZE +
1673 		    3 * sizeof (uint32_t);
1674 
1675 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1676 			ipha = ip_pullup(mp, len_needed, ira);
1677 			if (ipha == NULL) {
1678 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1679 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1680 				    mp, ill);
1681 				freemsg(mp);
1682 				return (NULL);
1683 			}
1684 			/* Refresh following the pullup. */
1685 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1686 		}
1687 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1688 		/* Check db_ref to make sure we can modify the packet. */
1689 		if (mp->b_datap->db_ref > 1) {
1690 			mblk_t	*mp1;
1691 
1692 			mp1 = copymsg(mp);
1693 			freemsg(mp);
1694 			if (!mp1) {
1695 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1696 				return (NULL);
1697 			}
1698 			mp = mp1;
1699 			ipha = (ipha_t *)mp->b_rptr;
1700 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1701 		}
1702 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1703 		tsp = (uint32_t *)&icmph[1];
1704 		tsp++;		/* Skip past 'originate time' */
1705 		/* Compute # of milliseconds since midnight */
1706 		gethrestime(&now);
1707 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1708 		    now.tv_nsec / (NANOSEC / MILLISEC);
1709 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1710 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1711 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1712 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1713 		return (NULL);
1714 
1715 	case ICMP_TIME_STAMP_REPLY:
1716 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1717 		break;
1718 	case ICMP_INFO_REQUEST:
1719 		/* Per RFC 1122 3.2.2.7, ignore this. */
1720 	case ICMP_INFO_REPLY:
1721 		break;
1722 	case ICMP_ADDRESS_MASK_REQUEST:
1723 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1724 			interested =
1725 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1726 		} else {
1727 			interested = B_TRUE;
1728 		}
1729 		if (!interested) {
1730 			/* We never pass these to RAW sockets */
1731 			freemsg(mp);
1732 			return (NULL);
1733 		}
1734 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1735 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1736 			ipha = ip_pullup(mp, len_needed, ira);
1737 			if (ipha == NULL) {
1738 				BUMP_MIB(ill->ill_ip_mib,
1739 				    ipIfStatsInTruncatedPkts);
1740 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1741 				    ill);
1742 				freemsg(mp);
1743 				return (NULL);
1744 			}
1745 			/* Refresh following the pullup. */
1746 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1747 		}
1748 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1749 		/* Check db_ref to make sure we can modify the packet. */
1750 		if (mp->b_datap->db_ref > 1) {
1751 			mblk_t	*mp1;
1752 
1753 			mp1 = copymsg(mp);
1754 			freemsg(mp);
1755 			if (!mp1) {
1756 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1757 				return (NULL);
1758 			}
1759 			mp = mp1;
1760 			ipha = (ipha_t *)mp->b_rptr;
1761 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1762 		}
1763 		/*
1764 		 * Need the ipif with the mask be the same as the source
1765 		 * address of the mask reply. For unicast we have a specific
1766 		 * ipif. For multicast/broadcast we only handle onlink
1767 		 * senders, and use the source address to pick an ipif.
1768 		 */
1769 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1770 		if (ipif == NULL) {
1771 			/* Broadcast or multicast */
1772 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1773 			if (ipif == NULL) {
1774 				freemsg(mp);
1775 				return (NULL);
1776 			}
1777 		}
1778 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1779 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1780 		ipif_refrele(ipif);
1781 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1782 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1783 		return (NULL);
1784 
1785 	case ICMP_ADDRESS_MASK_REPLY:
1786 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1787 		break;
1788 	default:
1789 		interested = B_TRUE;	/* Pass up to transport */
1790 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1791 		break;
1792 	}
1793 	/*
1794 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1795 	 * if there isn't one.
1796 	 */
1797 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1798 		/* If there is an ICMP client and we want one too, copy it. */
1799 
1800 		if (!interested) {
1801 			/* Caller will deliver to RAW sockets */
1802 			return (mp);
1803 		}
1804 		mp_ret = copymsg(mp);
1805 		if (mp_ret == NULL) {
1806 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1807 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1808 		}
1809 	} else if (!interested) {
1810 		/* Neither we nor raw sockets are interested. Drop packet now */
1811 		freemsg(mp);
1812 		return (NULL);
1813 	}
1814 
1815 	/*
1816 	 * ICMP error or redirect packet. Make sure we have enough of
1817 	 * the header and that db_ref == 1 since we might end up modifying
1818 	 * the packet.
1819 	 */
1820 	if (mp->b_cont != NULL) {
1821 		if (ip_pullup(mp, -1, ira) == NULL) {
1822 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1823 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1824 			    mp, ill);
1825 			freemsg(mp);
1826 			return (mp_ret);
1827 		}
1828 	}
1829 
1830 	if (mp->b_datap->db_ref > 1) {
1831 		mblk_t	*mp1;
1832 
1833 		mp1 = copymsg(mp);
1834 		if (mp1 == NULL) {
1835 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1836 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1837 			freemsg(mp);
1838 			return (mp_ret);
1839 		}
1840 		freemsg(mp);
1841 		mp = mp1;
1842 	}
1843 
1844 	/*
1845 	 * In case mp has changed, verify the message before any further
1846 	 * processes.
1847 	 */
1848 	ipha = (ipha_t *)mp->b_rptr;
1849 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1850 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1851 		freemsg(mp);
1852 		return (mp_ret);
1853 	}
1854 
1855 	switch (icmph->icmph_type) {
1856 	case ICMP_REDIRECT:
1857 		icmp_redirect_v4(mp, ipha, icmph, ira);
1858 		break;
1859 	case ICMP_DEST_UNREACHABLE:
1860 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1861 			/* Update DCE and adjust MTU is icmp header if needed */
1862 			icmp_inbound_too_big_v4(icmph, ira);
1863 		}
1864 		/* FALLTHRU */
1865 	default:
1866 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1867 		break;
1868 	}
1869 	return (mp_ret);
1870 }
1871 
1872 /*
1873  * Send an ICMP echo, timestamp or address mask reply.
1874  * The caller has already updated the payload part of the packet.
1875  * We handle the ICMP checksum, IP source address selection and feed
1876  * the packet into ip_output_simple.
1877  */
1878 static void
1879 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1880     ip_recv_attr_t *ira)
1881 {
1882 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1883 	ill_t		*ill = ira->ira_ill;
1884 	ip_stack_t	*ipst = ill->ill_ipst;
1885 	ip_xmit_attr_t	ixas;
1886 
1887 	/* Send out an ICMP packet */
1888 	icmph->icmph_checksum = 0;
1889 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1890 	/* Reset time to live. */
1891 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1892 	{
1893 		/* Swap source and destination addresses */
1894 		ipaddr_t tmp;
1895 
1896 		tmp = ipha->ipha_src;
1897 		ipha->ipha_src = ipha->ipha_dst;
1898 		ipha->ipha_dst = tmp;
1899 	}
1900 	ipha->ipha_ident = 0;
1901 	if (!IS_SIMPLE_IPH(ipha))
1902 		icmp_options_update(ipha);
1903 
1904 	bzero(&ixas, sizeof (ixas));
1905 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1906 	ixas.ixa_zoneid = ira->ira_zoneid;
1907 	ixas.ixa_cred = kcred;
1908 	ixas.ixa_cpid = NOPID;
1909 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1910 	ixas.ixa_ifindex = 0;
1911 	ixas.ixa_ipst = ipst;
1912 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1913 
1914 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1915 		/*
1916 		 * This packet should go out the same way as it
1917 		 * came in i.e in clear, independent of the IPsec policy
1918 		 * for transmitting packets.
1919 		 */
1920 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1921 	} else {
1922 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1923 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1924 			/* Note: mp already consumed and ip_drop_packet done */
1925 			return;
1926 		}
1927 	}
1928 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1929 		/*
1930 		 * Not one or our addresses (IRE_LOCALs), thus we let
1931 		 * ip_output_simple pick the source.
1932 		 */
1933 		ipha->ipha_src = INADDR_ANY;
1934 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1935 	}
1936 	/* Should we send with DF and use dce_pmtu? */
1937 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1938 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1939 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1940 	}
1941 
1942 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1943 
1944 	(void) ip_output_simple(mp, &ixas);
1945 	ixa_cleanup(&ixas);
1946 }
1947 
1948 /*
1949  * Verify the ICMP messages for either for ICMP error or redirect packet.
1950  * The caller should have fully pulled up the message. If it's a redirect
1951  * packet, only basic checks on IP header will be done; otherwise, verify
1952  * the packet by looking at the included ULP header.
1953  *
1954  * Called before icmp_inbound_error_fanout_v4 is called.
1955  */
1956 static boolean_t
1957 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1958 {
1959 	ill_t		*ill = ira->ira_ill;
1960 	int		hdr_length;
1961 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1962 	conn_t		*connp;
1963 	ipha_t		*ipha;	/* Inner IP header */
1964 
1965 	ipha = (ipha_t *)&icmph[1];
1966 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1967 		goto truncated;
1968 
1969 	hdr_length = IPH_HDR_LENGTH(ipha);
1970 
1971 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1972 		goto discard_pkt;
1973 
1974 	if (hdr_length < sizeof (ipha_t))
1975 		goto truncated;
1976 
1977 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1978 		goto truncated;
1979 
1980 	/*
1981 	 * Stop here for ICMP_REDIRECT.
1982 	 */
1983 	if (icmph->icmph_type == ICMP_REDIRECT)
1984 		return (B_TRUE);
1985 
1986 	/*
1987 	 * ICMP errors only.
1988 	 */
1989 	switch (ipha->ipha_protocol) {
1990 	case IPPROTO_UDP:
1991 		/*
1992 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1993 		 * transport header.
1994 		 */
1995 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1996 		    mp->b_wptr)
1997 			goto truncated;
1998 		break;
1999 	case IPPROTO_TCP: {
2000 		tcpha_t		*tcpha;
2001 
2002 		/*
2003 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2004 		 * transport header.
2005 		 */
2006 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2007 		    mp->b_wptr)
2008 			goto truncated;
2009 
2010 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2011 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2012 		    ipst);
2013 		if (connp == NULL)
2014 			goto discard_pkt;
2015 
2016 		if ((connp->conn_verifyicmp != NULL) &&
2017 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
2018 			CONN_DEC_REF(connp);
2019 			goto discard_pkt;
2020 		}
2021 		CONN_DEC_REF(connp);
2022 		break;
2023 	}
2024 	case IPPROTO_SCTP:
2025 		/*
2026 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2027 		 * transport header.
2028 		 */
2029 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2030 		    mp->b_wptr)
2031 			goto truncated;
2032 		break;
2033 	case IPPROTO_ESP:
2034 	case IPPROTO_AH:
2035 		break;
2036 	case IPPROTO_ENCAP:
2037 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2038 		    mp->b_wptr)
2039 			goto truncated;
2040 		break;
2041 	default:
2042 		break;
2043 	}
2044 
2045 	return (B_TRUE);
2046 
2047 discard_pkt:
2048 	/* Bogus ICMP error. */
2049 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2050 	return (B_FALSE);
2051 
2052 truncated:
2053 	/* We pulled up everthing already. Must be truncated */
2054 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2055 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2056 	return (B_FALSE);
2057 }
2058 
2059 /* Table from RFC 1191 */
2060 static int icmp_frag_size_table[] =
2061 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2062 
2063 /*
2064  * Process received ICMP Packet too big.
2065  * Just handles the DCE create/update, including using the above table of
2066  * PMTU guesses. The caller is responsible for validating the packet before
2067  * passing it in and also to fanout the ICMP error to any matching transport
2068  * conns. Assumes the message has been fully pulled up and verified.
2069  *
2070  * Before getting here, the caller has called icmp_inbound_verify_v4()
2071  * that should have verified with ULP to prevent undoing the changes we're
2072  * going to make to DCE. For example, TCP might have verified that the packet
2073  * which generated error is in the send window.
2074  *
2075  * In some cases modified this MTU in the ICMP header packet; the caller
2076  * should pass to the matching ULP after this returns.
2077  */
2078 static void
2079 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
2080 {
2081 	dce_t		*dce;
2082 	int		old_mtu;
2083 	int		mtu, orig_mtu;
2084 	ipaddr_t	dst;
2085 	boolean_t	disable_pmtud;
2086 	ill_t		*ill = ira->ira_ill;
2087 	ip_stack_t	*ipst = ill->ill_ipst;
2088 	uint_t		hdr_length;
2089 	ipha_t		*ipha;
2090 
2091 	/* Caller already pulled up everything. */
2092 	ipha = (ipha_t *)&icmph[1];
2093 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2094 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2095 	ASSERT(ill != NULL);
2096 
2097 	hdr_length = IPH_HDR_LENGTH(ipha);
2098 
2099 	/*
2100 	 * We handle path MTU for source routed packets since the DCE
2101 	 * is looked up using the final destination.
2102 	 */
2103 	dst = ip_get_dst(ipha);
2104 
2105 	dce = dce_lookup_and_add_v4(dst, ipst);
2106 	if (dce == NULL) {
2107 		/* Couldn't add a unique one - ENOMEM */
2108 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
2109 		    ntohl(dst)));
2110 		return;
2111 	}
2112 
2113 	/* Check for MTU discovery advice as described in RFC 1191 */
2114 	mtu = ntohs(icmph->icmph_du_mtu);
2115 	orig_mtu = mtu;
2116 	disable_pmtud = B_FALSE;
2117 
2118 	mutex_enter(&dce->dce_lock);
2119 	if (dce->dce_flags & DCEF_PMTU)
2120 		old_mtu = dce->dce_pmtu;
2121 	else
2122 		old_mtu = ill->ill_mtu;
2123 
2124 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2125 		uint32_t length;
2126 		int	i;
2127 
2128 		/*
2129 		 * Use the table from RFC 1191 to figure out
2130 		 * the next "plateau" based on the length in
2131 		 * the original IP packet.
2132 		 */
2133 		length = ntohs(ipha->ipha_length);
2134 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
2135 		    uint32_t, length);
2136 		if (old_mtu <= length &&
2137 		    old_mtu >= length - hdr_length) {
2138 			/*
2139 			 * Handle broken BSD 4.2 systems that
2140 			 * return the wrong ipha_length in ICMP
2141 			 * errors.
2142 			 */
2143 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
2144 			    length, old_mtu));
2145 			length -= hdr_length;
2146 		}
2147 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2148 			if (length > icmp_frag_size_table[i])
2149 				break;
2150 		}
2151 		if (i == A_CNT(icmp_frag_size_table)) {
2152 			/* Smaller than IP_MIN_MTU! */
2153 			ip1dbg(("Too big for packet size %d\n",
2154 			    length));
2155 			disable_pmtud = B_TRUE;
2156 			mtu = ipst->ips_ip_pmtu_min;
2157 		} else {
2158 			mtu = icmp_frag_size_table[i];
2159 			ip1dbg(("Calculated mtu %d, packet size %d, "
2160 			    "before %d\n", mtu, length, old_mtu));
2161 			if (mtu < ipst->ips_ip_pmtu_min) {
2162 				mtu = ipst->ips_ip_pmtu_min;
2163 				disable_pmtud = B_TRUE;
2164 			}
2165 		}
2166 	}
2167 	if (disable_pmtud)
2168 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
2169 	else
2170 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
2171 
2172 	dce->dce_pmtu = MIN(old_mtu, mtu);
2173 	/* Prepare to send the new max frag size for the ULP. */
2174 	icmph->icmph_du_zero = 0;
2175 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
2176 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
2177 	    dce, int, orig_mtu, int, mtu);
2178 
2179 	/* We now have a PMTU for sure */
2180 	dce->dce_flags |= DCEF_PMTU;
2181 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
2182 	mutex_exit(&dce->dce_lock);
2183 	/*
2184 	 * After dropping the lock the new value is visible to everyone.
2185 	 * Then we bump the generation number so any cached values reinspect
2186 	 * the dce_t.
2187 	 */
2188 	dce_increment_generation(dce);
2189 	dce_refrele(dce);
2190 }
2191 
2192 /*
2193  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
2194  * calls this function.
2195  */
2196 static mblk_t *
2197 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
2198 {
2199 	int length;
2200 
2201 	ASSERT(mp->b_datap->db_type == M_DATA);
2202 
2203 	/* icmp_inbound_v4 has already pulled up the whole error packet */
2204 	ASSERT(mp->b_cont == NULL);
2205 
2206 	/*
2207 	 * The length that we want to overlay is the inner header
2208 	 * and what follows it.
2209 	 */
2210 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
2211 
2212 	/*
2213 	 * Overlay the inner header and whatever follows it over the
2214 	 * outer header.
2215 	 */
2216 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2217 
2218 	/* Adjust for what we removed */
2219 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2220 	return (mp);
2221 }
2222 
2223 /*
2224  * Try to pass the ICMP message upstream in case the ULP cares.
2225  *
2226  * If the packet that caused the ICMP error is secure, we send
2227  * it to AH/ESP to make sure that the attached packet has a
2228  * valid association. ipha in the code below points to the
2229  * IP header of the packet that caused the error.
2230  *
2231  * For IPsec cases, we let the next-layer-up (which has access to
2232  * cached policy on the conn_t, or can query the SPD directly)
2233  * subtract out any IPsec overhead if they must.  We therefore make no
2234  * adjustments here for IPsec overhead.
2235  *
2236  * IFN could have been generated locally or by some router.
2237  *
2238  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2239  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2240  *	    This happens because IP adjusted its value of MTU on an
2241  *	    earlier IFN message and could not tell the upper layer,
2242  *	    the new adjusted value of MTU e.g. Packet was encrypted
2243  *	    or there was not enough information to fanout to upper
2244  *	    layers. Thus on the next outbound datagram, ire_send_wire
2245  *	    generates the IFN, where IPsec processing has *not* been
2246  *	    done.
2247  *
2248  *	    Note that we retain ixa_fragsize across IPsec thus once
2249  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2250  *	    no change the fragsize even if the path MTU changes before
2251  *	    we reach ip_output_post_ipsec.
2252  *
2253  *	    In the local case, IRAF_LOOPBACK will be set indicating
2254  *	    that IFN was generated locally.
2255  *
2256  * ROUTER : IFN could be secure or non-secure.
2257  *
2258  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2259  *	      packet in error has AH/ESP headers to validate the AH/ESP
2260  *	      headers. AH/ESP will verify whether there is a valid SA or
2261  *	      not and send it back. We will fanout again if we have more
2262  *	      data in the packet.
2263  *
2264  *	      If the packet in error does not have AH/ESP, we handle it
2265  *	      like any other case.
2266  *
2267  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2268  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2269  *	      valid SA or not and send it back. We will fanout again if
2270  *	      we have more data in the packet.
2271  *
2272  *	      If the packet in error does not have AH/ESP, we handle it
2273  *	      like any other case.
2274  *
2275  * The caller must have called icmp_inbound_verify_v4.
2276  */
2277 static void
2278 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2279 {
2280 	uint16_t	*up;	/* Pointer to ports in ULP header */
2281 	uint32_t	ports;	/* reversed ports for fanout */
2282 	ipha_t		ripha;	/* With reversed addresses */
2283 	ipha_t		*ipha;  /* Inner IP header */
2284 	uint_t		hdr_length; /* Inner IP header length */
2285 	tcpha_t		*tcpha;
2286 	conn_t		*connp;
2287 	ill_t		*ill = ira->ira_ill;
2288 	ip_stack_t	*ipst = ill->ill_ipst;
2289 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2290 	ill_t		*rill = ira->ira_rill;
2291 
2292 	/* Caller already pulled up everything. */
2293 	ipha = (ipha_t *)&icmph[1];
2294 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2295 	ASSERT(mp->b_cont == NULL);
2296 
2297 	hdr_length = IPH_HDR_LENGTH(ipha);
2298 	ira->ira_protocol = ipha->ipha_protocol;
2299 
2300 	/*
2301 	 * We need a separate IP header with the source and destination
2302 	 * addresses reversed to do fanout/classification because the ipha in
2303 	 * the ICMP error is in the form we sent it out.
2304 	 */
2305 	ripha.ipha_src = ipha->ipha_dst;
2306 	ripha.ipha_dst = ipha->ipha_src;
2307 	ripha.ipha_protocol = ipha->ipha_protocol;
2308 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2309 
2310 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2311 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2312 	    ntohl(ipha->ipha_dst),
2313 	    icmph->icmph_type, icmph->icmph_code));
2314 
2315 	switch (ipha->ipha_protocol) {
2316 	case IPPROTO_UDP:
2317 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2318 
2319 		/* Attempt to find a client stream based on port. */
2320 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2321 		    ntohs(up[0]), ntohs(up[1])));
2322 
2323 		/* Note that we send error to all matches. */
2324 		ira->ira_flags |= IRAF_ICMP_ERROR;
2325 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2326 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2327 		return;
2328 
2329 	case IPPROTO_TCP:
2330 		/*
2331 		 * Find a TCP client stream for this packet.
2332 		 * Note that we do a reverse lookup since the header is
2333 		 * in the form we sent it out.
2334 		 */
2335 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2336 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2337 		    ipst);
2338 		if (connp == NULL)
2339 			goto discard_pkt;
2340 
2341 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2342 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2343 			mp = ipsec_check_inbound_policy(mp, connp,
2344 			    ipha, NULL, ira);
2345 			if (mp == NULL) {
2346 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2347 				/* Note that mp is NULL */
2348 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2349 				CONN_DEC_REF(connp);
2350 				return;
2351 			}
2352 		}
2353 
2354 		ira->ira_flags |= IRAF_ICMP_ERROR;
2355 		ira->ira_ill = ira->ira_rill = NULL;
2356 		if (IPCL_IS_TCP(connp)) {
2357 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2358 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2359 			    SQTAG_TCP_INPUT_ICMP_ERR);
2360 		} else {
2361 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2362 			(connp->conn_recv)(connp, mp, NULL, ira);
2363 			CONN_DEC_REF(connp);
2364 		}
2365 		ira->ira_ill = ill;
2366 		ira->ira_rill = rill;
2367 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2368 		return;
2369 
2370 	case IPPROTO_SCTP:
2371 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2372 		/* Find a SCTP client stream for this packet. */
2373 		((uint16_t *)&ports)[0] = up[1];
2374 		((uint16_t *)&ports)[1] = up[0];
2375 
2376 		ira->ira_flags |= IRAF_ICMP_ERROR;
2377 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2378 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2379 		return;
2380 
2381 	case IPPROTO_ESP:
2382 	case IPPROTO_AH:
2383 		if (!ipsec_loaded(ipss)) {
2384 			ip_proto_not_sup(mp, ira);
2385 			return;
2386 		}
2387 
2388 		if (ipha->ipha_protocol == IPPROTO_ESP)
2389 			mp = ipsecesp_icmp_error(mp, ira);
2390 		else
2391 			mp = ipsecah_icmp_error(mp, ira);
2392 		if (mp == NULL)
2393 			return;
2394 
2395 		/* Just in case ipsec didn't preserve the NULL b_cont */
2396 		if (mp->b_cont != NULL) {
2397 			if (!pullupmsg(mp, -1))
2398 				goto discard_pkt;
2399 		}
2400 
2401 		/*
2402 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2403 		 * correct, but we don't use them any more here.
2404 		 *
2405 		 * If succesful, the mp has been modified to not include
2406 		 * the ESP/AH header so we can fanout to the ULP's icmp
2407 		 * error handler.
2408 		 */
2409 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2410 			goto truncated;
2411 
2412 		/* Verify the modified message before any further processes. */
2413 		ipha = (ipha_t *)mp->b_rptr;
2414 		hdr_length = IPH_HDR_LENGTH(ipha);
2415 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2416 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2417 			freemsg(mp);
2418 			return;
2419 		}
2420 
2421 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2422 		return;
2423 
2424 	case IPPROTO_ENCAP: {
2425 		/* Look for self-encapsulated packets that caused an error */
2426 		ipha_t *in_ipha;
2427 
2428 		/*
2429 		 * Caller has verified that length has to be
2430 		 * at least the size of IP header.
2431 		 */
2432 		ASSERT(hdr_length >= sizeof (ipha_t));
2433 		/*
2434 		 * Check the sanity of the inner IP header like
2435 		 * we did for the outer header.
2436 		 */
2437 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2438 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2439 			goto discard_pkt;
2440 		}
2441 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2442 			goto discard_pkt;
2443 		}
2444 		/* Check for Self-encapsulated tunnels */
2445 		if (in_ipha->ipha_src == ipha->ipha_src &&
2446 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2447 
2448 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2449 			    in_ipha);
2450 			if (mp == NULL)
2451 				goto discard_pkt;
2452 
2453 			/*
2454 			 * Just in case self_encap didn't preserve the NULL
2455 			 * b_cont
2456 			 */
2457 			if (mp->b_cont != NULL) {
2458 				if (!pullupmsg(mp, -1))
2459 					goto discard_pkt;
2460 			}
2461 			/*
2462 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2463 			 * longer correct, but we don't use them any more here.
2464 			 */
2465 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2466 				goto truncated;
2467 
2468 			/*
2469 			 * Verify the modified message before any further
2470 			 * processes.
2471 			 */
2472 			ipha = (ipha_t *)mp->b_rptr;
2473 			hdr_length = IPH_HDR_LENGTH(ipha);
2474 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2475 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2476 				freemsg(mp);
2477 				return;
2478 			}
2479 
2480 			/*
2481 			 * The packet in error is self-encapsualted.
2482 			 * And we are finding it further encapsulated
2483 			 * which we could not have possibly generated.
2484 			 */
2485 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2486 				goto discard_pkt;
2487 			}
2488 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2489 			return;
2490 		}
2491 		/* No self-encapsulated */
2492 		/* FALLTHRU */
2493 	}
2494 	case IPPROTO_IPV6:
2495 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2496 		    &ripha.ipha_dst, ipst)) != NULL) {
2497 			ira->ira_flags |= IRAF_ICMP_ERROR;
2498 			connp->conn_recvicmp(connp, mp, NULL, ira);
2499 			CONN_DEC_REF(connp);
2500 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2501 			return;
2502 		}
2503 		/*
2504 		 * No IP tunnel is interested, fallthrough and see
2505 		 * if a raw socket will want it.
2506 		 */
2507 		/* FALLTHRU */
2508 	default:
2509 		ira->ira_flags |= IRAF_ICMP_ERROR;
2510 		ip_fanout_proto_v4(mp, &ripha, ira);
2511 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2512 		return;
2513 	}
2514 	/* NOTREACHED */
2515 discard_pkt:
2516 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2517 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2518 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2519 	freemsg(mp);
2520 	return;
2521 
2522 truncated:
2523 	/* We pulled up everthing already. Must be truncated */
2524 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2525 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2526 	freemsg(mp);
2527 }
2528 
2529 /*
2530  * Common IP options parser.
2531  *
2532  * Setup routine: fill in *optp with options-parsing state, then
2533  * tail-call ipoptp_next to return the first option.
2534  */
2535 uint8_t
2536 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2537 {
2538 	uint32_t totallen; /* total length of all options */
2539 
2540 	totallen = ipha->ipha_version_and_hdr_length -
2541 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2542 	totallen <<= 2;
2543 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2544 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2545 	optp->ipoptp_flags = 0;
2546 	return (ipoptp_next(optp));
2547 }
2548 
2549 /* Like above but without an ipha_t */
2550 uint8_t
2551 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2552 {
2553 	optp->ipoptp_next = opt;
2554 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2555 	optp->ipoptp_flags = 0;
2556 	return (ipoptp_next(optp));
2557 }
2558 
2559 /*
2560  * Common IP options parser: extract next option.
2561  */
2562 uint8_t
2563 ipoptp_next(ipoptp_t *optp)
2564 {
2565 	uint8_t *end = optp->ipoptp_end;
2566 	uint8_t *cur = optp->ipoptp_next;
2567 	uint8_t opt, len, pointer;
2568 
2569 	/*
2570 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2571 	 * has been corrupted.
2572 	 */
2573 	ASSERT(cur <= end);
2574 
2575 	if (cur == end)
2576 		return (IPOPT_EOL);
2577 
2578 	opt = cur[IPOPT_OPTVAL];
2579 
2580 	/*
2581 	 * Skip any NOP options.
2582 	 */
2583 	while (opt == IPOPT_NOP) {
2584 		cur++;
2585 		if (cur == end)
2586 			return (IPOPT_EOL);
2587 		opt = cur[IPOPT_OPTVAL];
2588 	}
2589 
2590 	if (opt == IPOPT_EOL)
2591 		return (IPOPT_EOL);
2592 
2593 	/*
2594 	 * Option requiring a length.
2595 	 */
2596 	if ((cur + 1) >= end) {
2597 		optp->ipoptp_flags |= IPOPTP_ERROR;
2598 		return (IPOPT_EOL);
2599 	}
2600 	len = cur[IPOPT_OLEN];
2601 	if (len < 2) {
2602 		optp->ipoptp_flags |= IPOPTP_ERROR;
2603 		return (IPOPT_EOL);
2604 	}
2605 	optp->ipoptp_cur = cur;
2606 	optp->ipoptp_len = len;
2607 	optp->ipoptp_next = cur + len;
2608 	if (cur + len > end) {
2609 		optp->ipoptp_flags |= IPOPTP_ERROR;
2610 		return (IPOPT_EOL);
2611 	}
2612 
2613 	/*
2614 	 * For the options which require a pointer field, make sure
2615 	 * its there, and make sure it points to either something
2616 	 * inside this option, or the end of the option.
2617 	 */
2618 	switch (opt) {
2619 	case IPOPT_RR:
2620 	case IPOPT_TS:
2621 	case IPOPT_LSRR:
2622 	case IPOPT_SSRR:
2623 		if (len <= IPOPT_OFFSET) {
2624 			optp->ipoptp_flags |= IPOPTP_ERROR;
2625 			return (opt);
2626 		}
2627 		pointer = cur[IPOPT_OFFSET];
2628 		if (pointer - 1 > len) {
2629 			optp->ipoptp_flags |= IPOPTP_ERROR;
2630 			return (opt);
2631 		}
2632 		break;
2633 	}
2634 
2635 	/*
2636 	 * Sanity check the pointer field based on the type of the
2637 	 * option.
2638 	 */
2639 	switch (opt) {
2640 	case IPOPT_RR:
2641 	case IPOPT_SSRR:
2642 	case IPOPT_LSRR:
2643 		if (pointer < IPOPT_MINOFF_SR)
2644 			optp->ipoptp_flags |= IPOPTP_ERROR;
2645 		break;
2646 	case IPOPT_TS:
2647 		if (pointer < IPOPT_MINOFF_IT)
2648 			optp->ipoptp_flags |= IPOPTP_ERROR;
2649 		/*
2650 		 * Note that the Internet Timestamp option also
2651 		 * contains two four bit fields (the Overflow field,
2652 		 * and the Flag field), which follow the pointer
2653 		 * field.  We don't need to check that these fields
2654 		 * fall within the length of the option because this
2655 		 * was implicitely done above.  We've checked that the
2656 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2657 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2658 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2659 		 */
2660 		ASSERT(len > IPOPT_POS_OV_FLG);
2661 		break;
2662 	}
2663 
2664 	return (opt);
2665 }
2666 
2667 /*
2668  * Use the outgoing IP header to create an IP_OPTIONS option the way
2669  * it was passed down from the application.
2670  *
2671  * This is compatible with BSD in that it returns
2672  * the reverse source route with the final destination
2673  * as the last entry. The first 4 bytes of the option
2674  * will contain the final destination.
2675  */
2676 int
2677 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2678 {
2679 	ipoptp_t	opts;
2680 	uchar_t		*opt;
2681 	uint8_t		optval;
2682 	uint8_t		optlen;
2683 	uint32_t	len = 0;
2684 	uchar_t		*buf1 = buf;
2685 	uint32_t	totallen;
2686 	ipaddr_t	dst;
2687 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2688 
2689 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2690 		return (0);
2691 
2692 	totallen = ipp->ipp_ipv4_options_len;
2693 	if (totallen & 0x3)
2694 		return (0);
2695 
2696 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2697 	len += IP_ADDR_LEN;
2698 	bzero(buf1, IP_ADDR_LEN);
2699 
2700 	dst = connp->conn_faddr_v4;
2701 
2702 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2703 	    optval != IPOPT_EOL;
2704 	    optval = ipoptp_next(&opts)) {
2705 		int	off;
2706 
2707 		opt = opts.ipoptp_cur;
2708 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2709 			break;
2710 		}
2711 		optlen = opts.ipoptp_len;
2712 
2713 		switch (optval) {
2714 		case IPOPT_SSRR:
2715 		case IPOPT_LSRR:
2716 
2717 			/*
2718 			 * Insert destination as the first entry in the source
2719 			 * route and move down the entries on step.
2720 			 * The last entry gets placed at buf1.
2721 			 */
2722 			buf[IPOPT_OPTVAL] = optval;
2723 			buf[IPOPT_OLEN] = optlen;
2724 			buf[IPOPT_OFFSET] = optlen;
2725 
2726 			off = optlen - IP_ADDR_LEN;
2727 			if (off < 0) {
2728 				/* No entries in source route */
2729 				break;
2730 			}
2731 			/* Last entry in source route if not already set */
2732 			if (dst == INADDR_ANY)
2733 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2734 			off -= IP_ADDR_LEN;
2735 
2736 			while (off > 0) {
2737 				bcopy(opt + off,
2738 				    buf + off + IP_ADDR_LEN,
2739 				    IP_ADDR_LEN);
2740 				off -= IP_ADDR_LEN;
2741 			}
2742 			/* ipha_dst into first slot */
2743 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2744 			    IP_ADDR_LEN);
2745 			buf += optlen;
2746 			len += optlen;
2747 			break;
2748 
2749 		default:
2750 			bcopy(opt, buf, optlen);
2751 			buf += optlen;
2752 			len += optlen;
2753 			break;
2754 		}
2755 	}
2756 done:
2757 	/* Pad the resulting options */
2758 	while (len & 0x3) {
2759 		*buf++ = IPOPT_EOL;
2760 		len++;
2761 	}
2762 	return (len);
2763 }
2764 
2765 /*
2766  * Update any record route or timestamp options to include this host.
2767  * Reverse any source route option.
2768  * This routine assumes that the options are well formed i.e. that they
2769  * have already been checked.
2770  */
2771 static void
2772 icmp_options_update(ipha_t *ipha)
2773 {
2774 	ipoptp_t	opts;
2775 	uchar_t		*opt;
2776 	uint8_t		optval;
2777 	ipaddr_t	src;		/* Our local address */
2778 	ipaddr_t	dst;
2779 
2780 	ip2dbg(("icmp_options_update\n"));
2781 	src = ipha->ipha_src;
2782 	dst = ipha->ipha_dst;
2783 
2784 	for (optval = ipoptp_first(&opts, ipha);
2785 	    optval != IPOPT_EOL;
2786 	    optval = ipoptp_next(&opts)) {
2787 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2788 		opt = opts.ipoptp_cur;
2789 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2790 		    optval, opts.ipoptp_len));
2791 		switch (optval) {
2792 			int off1, off2;
2793 		case IPOPT_SSRR:
2794 		case IPOPT_LSRR:
2795 			/*
2796 			 * Reverse the source route.  The first entry
2797 			 * should be the next to last one in the current
2798 			 * source route (the last entry is our address).
2799 			 * The last entry should be the final destination.
2800 			 */
2801 			off1 = IPOPT_MINOFF_SR - 1;
2802 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2803 			if (off2 < 0) {
2804 				/* No entries in source route */
2805 				ip1dbg((
2806 				    "icmp_options_update: bad src route\n"));
2807 				break;
2808 			}
2809 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2810 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2811 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2812 			off2 -= IP_ADDR_LEN;
2813 
2814 			while (off1 < off2) {
2815 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2816 				bcopy((char *)opt + off2, (char *)opt + off1,
2817 				    IP_ADDR_LEN);
2818 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2819 				off1 += IP_ADDR_LEN;
2820 				off2 -= IP_ADDR_LEN;
2821 			}
2822 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2823 			break;
2824 		}
2825 	}
2826 }
2827 
2828 /*
2829  * Process received ICMP Redirect messages.
2830  * Assumes the caller has verified that the headers are in the pulled up mblk.
2831  * Consumes mp.
2832  */
2833 static void
2834 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2835 {
2836 	ire_t		*ire, *nire;
2837 	ire_t		*prev_ire;
2838 	ipaddr_t  	src, dst, gateway;
2839 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2840 	ipha_t		*inner_ipha;	/* Inner IP header */
2841 
2842 	/* Caller already pulled up everything. */
2843 	inner_ipha = (ipha_t *)&icmph[1];
2844 	src = ipha->ipha_src;
2845 	dst = inner_ipha->ipha_dst;
2846 	gateway = icmph->icmph_rd_gateway;
2847 	/* Make sure the new gateway is reachable somehow. */
2848 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2849 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2850 	/*
2851 	 * Make sure we had a route for the dest in question and that
2852 	 * that route was pointing to the old gateway (the source of the
2853 	 * redirect packet.)
2854 	 * We do longest match and then compare ire_gateway_addr below.
2855 	 */
2856 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2857 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2858 	/*
2859 	 * Check that
2860 	 *	the redirect was not from ourselves
2861 	 *	the new gateway and the old gateway are directly reachable
2862 	 */
2863 	if (prev_ire == NULL || ire == NULL ||
2864 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2865 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2866 	    !(ire->ire_type & IRE_IF_ALL) ||
2867 	    prev_ire->ire_gateway_addr != src) {
2868 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2869 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2870 		freemsg(mp);
2871 		if (ire != NULL)
2872 			ire_refrele(ire);
2873 		if (prev_ire != NULL)
2874 			ire_refrele(prev_ire);
2875 		return;
2876 	}
2877 
2878 	ire_refrele(prev_ire);
2879 	ire_refrele(ire);
2880 
2881 	/*
2882 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2883 	 * require TOS routing
2884 	 */
2885 	switch (icmph->icmph_code) {
2886 	case 0:
2887 	case 1:
2888 		/* TODO: TOS specificity for cases 2 and 3 */
2889 	case 2:
2890 	case 3:
2891 		break;
2892 	default:
2893 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2894 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2895 		freemsg(mp);
2896 		return;
2897 	}
2898 	/*
2899 	 * Create a Route Association.  This will allow us to remember that
2900 	 * someone we believe told us to use the particular gateway.
2901 	 */
2902 	ire = ire_create(
2903 	    (uchar_t *)&dst,			/* dest addr */
2904 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2905 	    (uchar_t *)&gateway,		/* gateway addr */
2906 	    IRE_HOST,
2907 	    NULL,				/* ill */
2908 	    ALL_ZONES,
2909 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2910 	    NULL,				/* tsol_gc_t */
2911 	    ipst);
2912 
2913 	if (ire == NULL) {
2914 		freemsg(mp);
2915 		return;
2916 	}
2917 	nire = ire_add(ire);
2918 	/* Check if it was a duplicate entry */
2919 	if (nire != NULL && nire != ire) {
2920 		ASSERT(nire->ire_identical_ref > 1);
2921 		ire_delete(nire);
2922 		ire_refrele(nire);
2923 		nire = NULL;
2924 	}
2925 	ire = nire;
2926 	if (ire != NULL) {
2927 		ire_refrele(ire);		/* Held in ire_add */
2928 
2929 		/* tell routing sockets that we received a redirect */
2930 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2931 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2932 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2933 	}
2934 
2935 	/*
2936 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2937 	 * This together with the added IRE has the effect of
2938 	 * modifying an existing redirect.
2939 	 */
2940 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2941 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2942 	if (prev_ire != NULL) {
2943 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2944 			ire_delete(prev_ire);
2945 		ire_refrele(prev_ire);
2946 	}
2947 
2948 	freemsg(mp);
2949 }
2950 
2951 /*
2952  * Generate an ICMP parameter problem message.
2953  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2954  * constructed by the caller.
2955  */
2956 static void
2957 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2958 {
2959 	icmph_t	icmph;
2960 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2961 
2962 	mp = icmp_pkt_err_ok(mp, ira);
2963 	if (mp == NULL)
2964 		return;
2965 
2966 	bzero(&icmph, sizeof (icmph_t));
2967 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2968 	icmph.icmph_pp_ptr = ptr;
2969 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2970 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2971 }
2972 
2973 /*
2974  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2975  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2976  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2977  * an icmp error packet can be sent.
2978  * Assigns an appropriate source address to the packet. If ipha_dst is
2979  * one of our addresses use it for source. Otherwise let ip_output_simple
2980  * pick the source address.
2981  */
2982 static void
2983 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2984 {
2985 	ipaddr_t dst;
2986 	icmph_t	*icmph;
2987 	ipha_t	*ipha;
2988 	uint_t	len_needed;
2989 	size_t	msg_len;
2990 	mblk_t	*mp1;
2991 	ipaddr_t src;
2992 	ire_t	*ire;
2993 	ip_xmit_attr_t ixas;
2994 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2995 
2996 	ipha = (ipha_t *)mp->b_rptr;
2997 
2998 	bzero(&ixas, sizeof (ixas));
2999 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
3000 	ixas.ixa_zoneid = ira->ira_zoneid;
3001 	ixas.ixa_ifindex = 0;
3002 	ixas.ixa_ipst = ipst;
3003 	ixas.ixa_cred = kcred;
3004 	ixas.ixa_cpid = NOPID;
3005 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
3006 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
3007 
3008 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
3009 		/*
3010 		 * Apply IPsec based on how IPsec was applied to
3011 		 * the packet that had the error.
3012 		 *
3013 		 * If it was an outbound packet that caused the ICMP
3014 		 * error, then the caller will have setup the IRA
3015 		 * appropriately.
3016 		 */
3017 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
3018 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3019 			/* Note: mp already consumed and ip_drop_packet done */
3020 			return;
3021 		}
3022 	} else {
3023 		/*
3024 		 * This is in clear. The icmp message we are building
3025 		 * here should go out in clear, independent of our policy.
3026 		 */
3027 		ixas.ixa_flags |= IXAF_NO_IPSEC;
3028 	}
3029 
3030 	/* Remember our eventual destination */
3031 	dst = ipha->ipha_src;
3032 
3033 	/*
3034 	 * If the packet was for one of our unicast addresses, make
3035 	 * sure we respond with that as the source. Otherwise
3036 	 * have ip_output_simple pick the source address.
3037 	 */
3038 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
3039 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
3040 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3041 	if (ire != NULL) {
3042 		ire_refrele(ire);
3043 		src = ipha->ipha_dst;
3044 	} else {
3045 		src = INADDR_ANY;
3046 		ixas.ixa_flags |= IXAF_SET_SOURCE;
3047 	}
3048 
3049 	/*
3050 	 * Check if we can send back more then 8 bytes in addition to
3051 	 * the IP header.  We try to send 64 bytes of data and the internal
3052 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3053 	 */
3054 	len_needed = IPH_HDR_LENGTH(ipha);
3055 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3056 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3057 		if (!pullupmsg(mp, -1)) {
3058 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3059 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
3060 			freemsg(mp);
3061 			return;
3062 		}
3063 		ipha = (ipha_t *)mp->b_rptr;
3064 
3065 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3066 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3067 			    len_needed));
3068 		} else {
3069 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3070 
3071 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3072 			len_needed += ip_hdr_length_v6(mp, ip6h);
3073 		}
3074 	}
3075 	len_needed += ipst->ips_ip_icmp_return;
3076 	msg_len = msgdsize(mp);
3077 	if (msg_len > len_needed) {
3078 		(void) adjmsg(mp, len_needed - msg_len);
3079 		msg_len = len_needed;
3080 	}
3081 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
3082 	if (mp1 == NULL) {
3083 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3084 		freemsg(mp);
3085 		return;
3086 	}
3087 	mp1->b_cont = mp;
3088 	mp = mp1;
3089 
3090 	/*
3091 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
3092 	 * node generates be accepted in peace by all on-host destinations.
3093 	 * If we do NOT assume that all on-host destinations trust
3094 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3095 	 * (Look for IXAF_TRUSTED_ICMP).
3096 	 */
3097 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
3098 
3099 	ipha = (ipha_t *)mp->b_rptr;
3100 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3101 	*ipha = icmp_ipha;
3102 	ipha->ipha_src = src;
3103 	ipha->ipha_dst = dst;
3104 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3105 	msg_len += sizeof (icmp_ipha) + len;
3106 	if (msg_len > IP_MAXPACKET) {
3107 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3108 		msg_len = IP_MAXPACKET;
3109 	}
3110 	ipha->ipha_length = htons((uint16_t)msg_len);
3111 	icmph = (icmph_t *)&ipha[1];
3112 	bcopy(stuff, icmph, len);
3113 	icmph->icmph_checksum = 0;
3114 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3115 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3116 
3117 	(void) ip_output_simple(mp, &ixas);
3118 	ixa_cleanup(&ixas);
3119 }
3120 
3121 /*
3122  * Determine if an ICMP error packet can be sent given the rate limit.
3123  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3124  * in milliseconds) and a burst size. Burst size number of packets can
3125  * be sent arbitrarely closely spaced.
3126  * The state is tracked using two variables to implement an approximate
3127  * token bucket filter:
3128  *	icmp_pkt_err_last - lbolt value when the last burst started
3129  *	icmp_pkt_err_sent - number of packets sent in current burst
3130  */
3131 boolean_t
3132 icmp_err_rate_limit(ip_stack_t *ipst)
3133 {
3134 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
3135 	uint_t refilled; /* Number of packets refilled in tbf since last */
3136 	/* Guard against changes by loading into local variable */
3137 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3138 
3139 	if (err_interval == 0)
3140 		return (B_FALSE);
3141 
3142 	if (ipst->ips_icmp_pkt_err_last > now) {
3143 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3144 		ipst->ips_icmp_pkt_err_last = 0;
3145 		ipst->ips_icmp_pkt_err_sent = 0;
3146 	}
3147 	/*
3148 	 * If we are in a burst update the token bucket filter.
3149 	 * Update the "last" time to be close to "now" but make sure
3150 	 * we don't loose precision.
3151 	 */
3152 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3153 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3154 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3155 			ipst->ips_icmp_pkt_err_sent = 0;
3156 		} else {
3157 			ipst->ips_icmp_pkt_err_sent -= refilled;
3158 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3159 		}
3160 	}
3161 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3162 		/* Start of new burst */
3163 		ipst->ips_icmp_pkt_err_last = now;
3164 	}
3165 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3166 		ipst->ips_icmp_pkt_err_sent++;
3167 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3168 		    ipst->ips_icmp_pkt_err_sent));
3169 		return (B_FALSE);
3170 	}
3171 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3172 	return (B_TRUE);
3173 }
3174 
3175 /*
3176  * Check if it is ok to send an IPv4 ICMP error packet in
3177  * response to the IPv4 packet in mp.
3178  * Free the message and return null if no
3179  * ICMP error packet should be sent.
3180  */
3181 static mblk_t *
3182 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
3183 {
3184 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3185 	icmph_t	*icmph;
3186 	ipha_t	*ipha;
3187 	uint_t	len_needed;
3188 
3189 	if (!mp)
3190 		return (NULL);
3191 	ipha = (ipha_t *)mp->b_rptr;
3192 	if (ip_csum_hdr(ipha)) {
3193 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3194 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
3195 		freemsg(mp);
3196 		return (NULL);
3197 	}
3198 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
3199 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
3200 	    CLASSD(ipha->ipha_dst) ||
3201 	    CLASSD(ipha->ipha_src) ||
3202 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3203 		/* Note: only errors to the fragment with offset 0 */
3204 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3205 		freemsg(mp);
3206 		return (NULL);
3207 	}
3208 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3209 		/*
3210 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3211 		 * errors in response to any ICMP errors.
3212 		 */
3213 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3214 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3215 			if (!pullupmsg(mp, len_needed)) {
3216 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3217 				freemsg(mp);
3218 				return (NULL);
3219 			}
3220 			ipha = (ipha_t *)mp->b_rptr;
3221 		}
3222 		icmph = (icmph_t *)
3223 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3224 		switch (icmph->icmph_type) {
3225 		case ICMP_DEST_UNREACHABLE:
3226 		case ICMP_SOURCE_QUENCH:
3227 		case ICMP_TIME_EXCEEDED:
3228 		case ICMP_PARAM_PROBLEM:
3229 		case ICMP_REDIRECT:
3230 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3231 			freemsg(mp);
3232 			return (NULL);
3233 		default:
3234 			break;
3235 		}
3236 	}
3237 	/*
3238 	 * If this is a labeled system, then check to see if we're allowed to
3239 	 * send a response to this particular sender.  If not, then just drop.
3240 	 */
3241 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3242 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3243 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3244 		freemsg(mp);
3245 		return (NULL);
3246 	}
3247 	if (icmp_err_rate_limit(ipst)) {
3248 		/*
3249 		 * Only send ICMP error packets every so often.
3250 		 * This should be done on a per port/source basis,
3251 		 * but for now this will suffice.
3252 		 */
3253 		freemsg(mp);
3254 		return (NULL);
3255 	}
3256 	return (mp);
3257 }
3258 
3259 /*
3260  * Called when a packet was sent out the same link that it arrived on.
3261  * Check if it is ok to send a redirect and then send it.
3262  */
3263 void
3264 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3265     ip_recv_attr_t *ira)
3266 {
3267 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3268 	ipaddr_t	src, nhop;
3269 	mblk_t		*mp1;
3270 	ire_t		*nhop_ire;
3271 
3272 	/*
3273 	 * Check the source address to see if it originated
3274 	 * on the same logical subnet it is going back out on.
3275 	 * If so, we should be able to send it a redirect.
3276 	 * Avoid sending a redirect if the destination
3277 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3278 	 * or if the packet was source routed out this interface.
3279 	 *
3280 	 * We avoid sending a redirect if the
3281 	 * destination is directly connected
3282 	 * because it is possible that multiple
3283 	 * IP subnets may have been configured on
3284 	 * the link, and the source may not
3285 	 * be on the same subnet as ip destination,
3286 	 * even though they are on the same
3287 	 * physical link.
3288 	 */
3289 	if ((ire->ire_type & IRE_ONLINK) ||
3290 	    ip_source_routed(ipha, ipst))
3291 		return;
3292 
3293 	nhop_ire = ire_nexthop(ire);
3294 	if (nhop_ire == NULL)
3295 		return;
3296 
3297 	nhop = nhop_ire->ire_addr;
3298 
3299 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3300 		ire_t	*ire2;
3301 
3302 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3303 		mutex_enter(&nhop_ire->ire_lock);
3304 		ire2 = nhop_ire->ire_dep_parent;
3305 		if (ire2 != NULL)
3306 			ire_refhold(ire2);
3307 		mutex_exit(&nhop_ire->ire_lock);
3308 		ire_refrele(nhop_ire);
3309 		nhop_ire = ire2;
3310 	}
3311 	if (nhop_ire == NULL)
3312 		return;
3313 
3314 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3315 
3316 	src = ipha->ipha_src;
3317 
3318 	/*
3319 	 * We look at the interface ire for the nexthop,
3320 	 * to see if ipha_src is in the same subnet
3321 	 * as the nexthop.
3322 	 */
3323 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3324 		/*
3325 		 * The source is directly connected.
3326 		 */
3327 		mp1 = copymsg(mp);
3328 		if (mp1 != NULL) {
3329 			icmp_send_redirect(mp1, nhop, ira);
3330 		}
3331 	}
3332 	ire_refrele(nhop_ire);
3333 }
3334 
3335 /*
3336  * Generate an ICMP redirect message.
3337  */
3338 static void
3339 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3340 {
3341 	icmph_t	icmph;
3342 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3343 
3344 	mp = icmp_pkt_err_ok(mp, ira);
3345 	if (mp == NULL)
3346 		return;
3347 
3348 	bzero(&icmph, sizeof (icmph_t));
3349 	icmph.icmph_type = ICMP_REDIRECT;
3350 	icmph.icmph_code = 1;
3351 	icmph.icmph_rd_gateway = gateway;
3352 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3353 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3354 }
3355 
3356 /*
3357  * Generate an ICMP time exceeded message.
3358  */
3359 void
3360 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3361 {
3362 	icmph_t	icmph;
3363 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3364 
3365 	mp = icmp_pkt_err_ok(mp, ira);
3366 	if (mp == NULL)
3367 		return;
3368 
3369 	bzero(&icmph, sizeof (icmph_t));
3370 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3371 	icmph.icmph_code = code;
3372 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3373 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3374 }
3375 
3376 /*
3377  * Generate an ICMP unreachable message.
3378  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3379  * constructed by the caller.
3380  */
3381 void
3382 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3383 {
3384 	icmph_t	icmph;
3385 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3386 
3387 	mp = icmp_pkt_err_ok(mp, ira);
3388 	if (mp == NULL)
3389 		return;
3390 
3391 	bzero(&icmph, sizeof (icmph_t));
3392 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3393 	icmph.icmph_code = code;
3394 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3395 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3396 }
3397 
3398 /*
3399  * Latch in the IPsec state for a stream based the policy in the listener
3400  * and the actions in the ip_recv_attr_t.
3401  * Called directly from TCP and SCTP.
3402  */
3403 boolean_t
3404 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3405 {
3406 	ASSERT(lconnp->conn_policy != NULL);
3407 	ASSERT(connp->conn_policy == NULL);
3408 
3409 	IPPH_REFHOLD(lconnp->conn_policy);
3410 	connp->conn_policy = lconnp->conn_policy;
3411 
3412 	if (ira->ira_ipsec_action != NULL) {
3413 		if (connp->conn_latch == NULL) {
3414 			connp->conn_latch = iplatch_create();
3415 			if (connp->conn_latch == NULL)
3416 				return (B_FALSE);
3417 		}
3418 		ipsec_latch_inbound(connp, ira);
3419 	}
3420 	return (B_TRUE);
3421 }
3422 
3423 /*
3424  * Verify whether or not the IP address is a valid local address.
3425  * Could be a unicast, including one for a down interface.
3426  * If allow_mcbc then a multicast or broadcast address is also
3427  * acceptable.
3428  *
3429  * In the case of a broadcast/multicast address, however, the
3430  * upper protocol is expected to reset the src address
3431  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3432  * no packets are emitted with broadcast/multicast address as
3433  * source address (that violates hosts requirements RFC 1122)
3434  * The addresses valid for bind are:
3435  *	(1) - INADDR_ANY (0)
3436  *	(2) - IP address of an UP interface
3437  *	(3) - IP address of a DOWN interface
3438  *	(4) - valid local IP broadcast addresses. In this case
3439  *	the conn will only receive packets destined to
3440  *	the specified broadcast address.
3441  *	(5) - a multicast address. In this case
3442  *	the conn will only receive packets destined to
3443  *	the specified multicast address. Note: the
3444  *	application still has to issue an
3445  *	IP_ADD_MEMBERSHIP socket option.
3446  *
3447  * In all the above cases, the bound address must be valid in the current zone.
3448  * When the address is loopback, multicast or broadcast, there might be many
3449  * matching IREs so bind has to look up based on the zone.
3450  */
3451 ip_laddr_t
3452 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3453     ip_stack_t *ipst, boolean_t allow_mcbc)
3454 {
3455 	ire_t *src_ire;
3456 
3457 	ASSERT(src_addr != INADDR_ANY);
3458 
3459 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3460 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3461 
3462 	/*
3463 	 * If an address other than in6addr_any is requested,
3464 	 * we verify that it is a valid address for bind
3465 	 * Note: Following code is in if-else-if form for
3466 	 * readability compared to a condition check.
3467 	 */
3468 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3469 		/*
3470 		 * (2) Bind to address of local UP interface
3471 		 */
3472 		ire_refrele(src_ire);
3473 		return (IPVL_UNICAST_UP);
3474 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3475 		/*
3476 		 * (4) Bind to broadcast address
3477 		 */
3478 		ire_refrele(src_ire);
3479 		if (allow_mcbc)
3480 			return (IPVL_BCAST);
3481 		else
3482 			return (IPVL_BAD);
3483 	} else if (CLASSD(src_addr)) {
3484 		/* (5) bind to multicast address. */
3485 		if (src_ire != NULL)
3486 			ire_refrele(src_ire);
3487 
3488 		if (allow_mcbc)
3489 			return (IPVL_MCAST);
3490 		else
3491 			return (IPVL_BAD);
3492 	} else {
3493 		ipif_t *ipif;
3494 
3495 		/*
3496 		 * (3) Bind to address of local DOWN interface?
3497 		 * (ipif_lookup_addr() looks up all interfaces
3498 		 * but we do not get here for UP interfaces
3499 		 * - case (2) above)
3500 		 */
3501 		if (src_ire != NULL)
3502 			ire_refrele(src_ire);
3503 
3504 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3505 		if (ipif == NULL)
3506 			return (IPVL_BAD);
3507 
3508 		/* Not a useful source? */
3509 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3510 			ipif_refrele(ipif);
3511 			return (IPVL_BAD);
3512 		}
3513 		ipif_refrele(ipif);
3514 		return (IPVL_UNICAST_DOWN);
3515 	}
3516 }
3517 
3518 /*
3519  * Insert in the bind fanout for IPv4 and IPv6.
3520  * The caller should already have used ip_laddr_verify_v*() before calling
3521  * this.
3522  */
3523 int
3524 ip_laddr_fanout_insert(conn_t *connp)
3525 {
3526 	int		error;
3527 
3528 	/*
3529 	 * Allow setting new policies. For example, disconnects result
3530 	 * in us being called. As we would have set conn_policy_cached
3531 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3532 	 * can change after the disconnect.
3533 	 */
3534 	connp->conn_policy_cached = B_FALSE;
3535 
3536 	error = ipcl_bind_insert(connp);
3537 	if (error != 0) {
3538 		if (connp->conn_anon_port) {
3539 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3540 			    connp->conn_mlp_type, connp->conn_proto,
3541 			    ntohs(connp->conn_lport), B_FALSE);
3542 		}
3543 		connp->conn_mlp_type = mlptSingle;
3544 	}
3545 	return (error);
3546 }
3547 
3548 /*
3549  * Verify that both the source and destination addresses are valid. If
3550  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3551  * i.e. have no route to it.  Protocols like TCP want to verify destination
3552  * reachability, while tunnels do not.
3553  *
3554  * Determine the route, the interface, and (optionally) the source address
3555  * to use to reach a given destination.
3556  * Note that we allow connect to broadcast and multicast addresses when
3557  * IPDF_ALLOW_MCBC is set.
3558  * first_hop and dst_addr are normally the same, but if source routing
3559  * they will differ; in that case the first_hop is what we'll use for the
3560  * routing lookup but the dce and label checks will be done on dst_addr,
3561  *
3562  * If uinfo is set, then we fill in the best available information
3563  * we have for the destination. This is based on (in priority order) any
3564  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3565  * ill_mtu.
3566  *
3567  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3568  * always do the label check on dst_addr.
3569  */
3570 int
3571 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3572     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3573 {
3574 	ire_t		*ire = NULL;
3575 	int		error = 0;
3576 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3577 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3578 	ip_stack_t	*ipst = ixa->ixa_ipst;
3579 	dce_t		*dce;
3580 	uint_t		pmtu;
3581 	uint_t		generation;
3582 	nce_t		*nce;
3583 	ill_t		*ill = NULL;
3584 	boolean_t	multirt = B_FALSE;
3585 
3586 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3587 
3588 	/*
3589 	 * We never send to zero; the ULPs map it to the loopback address.
3590 	 * We can't allow it since we use zero to mean unitialized in some
3591 	 * places.
3592 	 */
3593 	ASSERT(dst_addr != INADDR_ANY);
3594 
3595 	if (is_system_labeled()) {
3596 		ts_label_t *tsl = NULL;
3597 
3598 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3599 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3600 		if (error != 0)
3601 			return (error);
3602 		if (tsl != NULL) {
3603 			/* Update the label */
3604 			ip_xmit_attr_replace_tsl(ixa, tsl);
3605 		}
3606 	}
3607 
3608 	setsrc = INADDR_ANY;
3609 	/*
3610 	 * Select a route; For IPMP interfaces, we would only select
3611 	 * a "hidden" route (i.e., going through a specific under_ill)
3612 	 * if ixa_ifindex has been specified.
3613 	 */
3614 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3615 	    &generation, &setsrc, &error, &multirt);
3616 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3617 	if (error != 0)
3618 		goto bad_addr;
3619 
3620 	/*
3621 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3622 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3623 	 * Otherwise the destination needn't be reachable.
3624 	 *
3625 	 * If we match on a reject or black hole, then we've got a
3626 	 * local failure.  May as well fail out the connect() attempt,
3627 	 * since it's never going to succeed.
3628 	 */
3629 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3630 		/*
3631 		 * If we're verifying destination reachability, we always want
3632 		 * to complain here.
3633 		 *
3634 		 * If we're not verifying destination reachability but the
3635 		 * destination has a route, we still want to fail on the
3636 		 * temporary address and broadcast address tests.
3637 		 *
3638 		 * In both cases do we let the code continue so some reasonable
3639 		 * information is returned to the caller. That enables the
3640 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3641 		 * use the generation mismatch path to check for the unreachable
3642 		 * case thereby avoiding any specific check in the main path.
3643 		 */
3644 		ASSERT(generation == IRE_GENERATION_VERIFY);
3645 		if (flags & IPDF_VERIFY_DST) {
3646 			/*
3647 			 * Set errno but continue to set up ixa_ire to be
3648 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3649 			 * That allows callers to use ip_output to get an
3650 			 * ICMP error back.
3651 			 */
3652 			if (!(ire->ire_type & IRE_HOST))
3653 				error = ENETUNREACH;
3654 			else
3655 				error = EHOSTUNREACH;
3656 		}
3657 	}
3658 
3659 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3660 	    !(flags & IPDF_ALLOW_MCBC)) {
3661 		ire_refrele(ire);
3662 		ire = ire_reject(ipst, B_FALSE);
3663 		generation = IRE_GENERATION_VERIFY;
3664 		error = ENETUNREACH;
3665 	}
3666 
3667 	/* Cache things */
3668 	if (ixa->ixa_ire != NULL)
3669 		ire_refrele_notr(ixa->ixa_ire);
3670 #ifdef DEBUG
3671 	ire_refhold_notr(ire);
3672 	ire_refrele(ire);
3673 #endif
3674 	ixa->ixa_ire = ire;
3675 	ixa->ixa_ire_generation = generation;
3676 
3677 	/*
3678 	 * For multicast with multirt we have a flag passed back from
3679 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3680 	 * possible multicast address.
3681 	 * We also need a flag for multicast since we can't check
3682 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3683 	 */
3684 	if (multirt) {
3685 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3686 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3687 	} else {
3688 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3689 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3690 	}
3691 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3692 		/* Get an nce to cache. */
3693 		nce = ire_to_nce(ire, firsthop, NULL);
3694 		if (nce == NULL) {
3695 			/* Allocation failure? */
3696 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3697 		} else {
3698 			if (ixa->ixa_nce != NULL)
3699 				nce_refrele(ixa->ixa_nce);
3700 			ixa->ixa_nce = nce;
3701 		}
3702 	}
3703 
3704 	/*
3705 	 * If the source address is a loopback address, the
3706 	 * destination had best be local or multicast.
3707 	 * If we are sending to an IRE_LOCAL using a loopback source then
3708 	 * it had better be the same zoneid.
3709 	 */
3710 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3711 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3712 			ire = NULL;	/* Stored in ixa_ire */
3713 			error = EADDRNOTAVAIL;
3714 			goto bad_addr;
3715 		}
3716 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3717 			ire = NULL;	/* Stored in ixa_ire */
3718 			error = EADDRNOTAVAIL;
3719 			goto bad_addr;
3720 		}
3721 	}
3722 	if (ire->ire_type & IRE_BROADCAST) {
3723 		/*
3724 		 * If the ULP didn't have a specified source, then we
3725 		 * make sure we reselect the source when sending
3726 		 * broadcasts out different interfaces.
3727 		 */
3728 		if (flags & IPDF_SELECT_SRC)
3729 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3730 		else
3731 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3732 	}
3733 
3734 	/*
3735 	 * Does the caller want us to pick a source address?
3736 	 */
3737 	if (flags & IPDF_SELECT_SRC) {
3738 		ipaddr_t	src_addr;
3739 
3740 		/*
3741 		 * We use use ire_nexthop_ill to avoid the under ipmp
3742 		 * interface for source address selection. Note that for ipmp
3743 		 * probe packets, ixa_ifindex would have been specified, and
3744 		 * the ip_select_route() invocation would have picked an ire
3745 		 * will ire_ill pointing at an under interface.
3746 		 */
3747 		ill = ire_nexthop_ill(ire);
3748 
3749 		/* If unreachable we have no ill but need some source */
3750 		if (ill == NULL) {
3751 			src_addr = htonl(INADDR_LOOPBACK);
3752 			/* Make sure we look for a better source address */
3753 			generation = SRC_GENERATION_VERIFY;
3754 		} else {
3755 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3756 			    ixa->ixa_multicast_ifaddr, zoneid,
3757 			    ipst, &src_addr, &generation, NULL);
3758 			if (error != 0) {
3759 				ire = NULL;	/* Stored in ixa_ire */
3760 				goto bad_addr;
3761 			}
3762 		}
3763 
3764 		/*
3765 		 * We allow the source address to to down.
3766 		 * However, we check that we don't use the loopback address
3767 		 * as a source when sending out on the wire.
3768 		 */
3769 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3770 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3771 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3772 			ire = NULL;	/* Stored in ixa_ire */
3773 			error = EADDRNOTAVAIL;
3774 			goto bad_addr;
3775 		}
3776 
3777 		*src_addrp = src_addr;
3778 		ixa->ixa_src_generation = generation;
3779 	}
3780 
3781 	if (flags & IPDF_UNIQUE_DCE) {
3782 		/* Fallback to the default dce if allocation fails */
3783 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3784 		if (dce != NULL)
3785 			generation = dce->dce_generation;
3786 		else
3787 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3788 	} else {
3789 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3790 	}
3791 	ASSERT(dce != NULL);
3792 	if (ixa->ixa_dce != NULL)
3793 		dce_refrele_notr(ixa->ixa_dce);
3794 #ifdef DEBUG
3795 	dce_refhold_notr(dce);
3796 	dce_refrele(dce);
3797 #endif
3798 	ixa->ixa_dce = dce;
3799 	ixa->ixa_dce_generation = generation;
3800 
3801 	/*
3802 	 * Make sure we don't leave an unreachable ixa_nce in place
3803 	 * since ip_select_route is used when we unplumb i.e., remove
3804 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3805 	 */
3806 	nce = ixa->ixa_nce;
3807 	if (nce != NULL && nce->nce_is_condemned) {
3808 		nce_refrele(nce);
3809 		ixa->ixa_nce = NULL;
3810 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3811 	}
3812 
3813 	/*
3814 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3815 	 * However, we can't do it for IPv4 multicast or broadcast.
3816 	 */
3817 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3818 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3819 
3820 	/*
3821 	 * Set initial value for fragmentation limit. Either conn_ip_output
3822 	 * or ULP might updates it when there are routing changes.
3823 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3824 	 */
3825 	pmtu = ip_get_pmtu(ixa);
3826 	ixa->ixa_fragsize = pmtu;
3827 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3828 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3829 		ixa->ixa_pmtu = pmtu;
3830 
3831 	/*
3832 	 * Extract information useful for some transports.
3833 	 * First we look for DCE metrics. Then we take what we have in
3834 	 * the metrics in the route, where the offlink is used if we have
3835 	 * one.
3836 	 */
3837 	if (uinfo != NULL) {
3838 		bzero(uinfo, sizeof (*uinfo));
3839 
3840 		if (dce->dce_flags & DCEF_UINFO)
3841 			*uinfo = dce->dce_uinfo;
3842 
3843 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3844 
3845 		/* Allow ire_metrics to decrease the path MTU from above */
3846 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3847 			uinfo->iulp_mtu = pmtu;
3848 
3849 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3850 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3851 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3852 	}
3853 
3854 	if (ill != NULL)
3855 		ill_refrele(ill);
3856 
3857 	return (error);
3858 
3859 bad_addr:
3860 	if (ire != NULL)
3861 		ire_refrele(ire);
3862 
3863 	if (ill != NULL)
3864 		ill_refrele(ill);
3865 
3866 	/*
3867 	 * Make sure we don't leave an unreachable ixa_nce in place
3868 	 * since ip_select_route is used when we unplumb i.e., remove
3869 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3870 	 */
3871 	nce = ixa->ixa_nce;
3872 	if (nce != NULL && nce->nce_is_condemned) {
3873 		nce_refrele(nce);
3874 		ixa->ixa_nce = NULL;
3875 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3876 	}
3877 
3878 	return (error);
3879 }
3880 
3881 
3882 /*
3883  * Get the base MTU for the case when path MTU discovery is not used.
3884  * Takes the MTU of the IRE into account.
3885  */
3886 uint_t
3887 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3888 {
3889 	uint_t mtu = ill->ill_mtu;
3890 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3891 
3892 	if (iremtu != 0 && iremtu < mtu)
3893 		mtu = iremtu;
3894 
3895 	return (mtu);
3896 }
3897 
3898 /*
3899  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3900  * Assumes that ixa_ire, dce, and nce have already been set up.
3901  *
3902  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3903  * We avoid path MTU discovery if it is disabled with ndd.
3904  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3905  *
3906  * NOTE: We also used to turn it off for source routed packets. That
3907  * is no longer required since the dce is per final destination.
3908  */
3909 uint_t
3910 ip_get_pmtu(ip_xmit_attr_t *ixa)
3911 {
3912 	ip_stack_t	*ipst = ixa->ixa_ipst;
3913 	dce_t		*dce;
3914 	nce_t		*nce;
3915 	ire_t		*ire;
3916 	uint_t		pmtu;
3917 
3918 	ire = ixa->ixa_ire;
3919 	dce = ixa->ixa_dce;
3920 	nce = ixa->ixa_nce;
3921 
3922 	/*
3923 	 * If path MTU discovery has been turned off by ndd, then we ignore
3924 	 * any dce_pmtu and for IPv4 we will not set DF.
3925 	 */
3926 	if (!ipst->ips_ip_path_mtu_discovery)
3927 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3928 
3929 	pmtu = IP_MAXPACKET;
3930 	/*
3931 	 * Decide whether whether IPv4 sets DF
3932 	 * For IPv6 "no DF" means to use the 1280 mtu
3933 	 */
3934 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3935 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3936 	} else {
3937 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3938 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3939 			pmtu = IPV6_MIN_MTU;
3940 	}
3941 
3942 	/* Check if the PMTU is to old before we use it */
3943 	if ((dce->dce_flags & DCEF_PMTU) &&
3944 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3945 	    ipst->ips_ip_pathmtu_interval) {
3946 		/*
3947 		 * Older than 20 minutes. Drop the path MTU information.
3948 		 */
3949 		mutex_enter(&dce->dce_lock);
3950 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3951 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3952 		mutex_exit(&dce->dce_lock);
3953 		dce_increment_generation(dce);
3954 	}
3955 
3956 	/* The metrics on the route can lower the path MTU */
3957 	if (ire->ire_metrics.iulp_mtu != 0 &&
3958 	    ire->ire_metrics.iulp_mtu < pmtu)
3959 		pmtu = ire->ire_metrics.iulp_mtu;
3960 
3961 	/*
3962 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3963 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3964 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3965 	 */
3966 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3967 		if (dce->dce_flags & DCEF_PMTU) {
3968 			if (dce->dce_pmtu < pmtu)
3969 				pmtu = dce->dce_pmtu;
3970 
3971 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3972 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3973 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3974 			} else {
3975 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3976 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3977 			}
3978 		} else {
3979 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3980 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3981 		}
3982 	}
3983 
3984 	/*
3985 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3986 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3987 	 * mtu as IRE_LOOPBACK.
3988 	 */
3989 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3990 		uint_t loopback_mtu;
3991 
3992 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3993 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3994 
3995 		if (loopback_mtu < pmtu)
3996 			pmtu = loopback_mtu;
3997 	} else if (nce != NULL) {
3998 		/*
3999 		 * Make sure we don't exceed the interface MTU.
4000 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
4001 		 * an ill. We'd use the above IP_MAXPACKET in that case just
4002 		 * to tell the transport something larger than zero.
4003 		 */
4004 		if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
4005 			pmtu = nce->nce_common->ncec_ill->ill_mtu;
4006 		if (nce->nce_common->ncec_ill != nce->nce_ill &&
4007 		    nce->nce_ill->ill_mtu < pmtu) {
4008 			/*
4009 			 * for interfaces in an IPMP group, the mtu of
4010 			 * the nce_ill (under_ill) could be different
4011 			 * from the mtu of the ncec_ill, so we take the
4012 			 * min of the two.
4013 			 */
4014 			pmtu = nce->nce_ill->ill_mtu;
4015 		}
4016 	}
4017 
4018 	/*
4019 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
4020 	 * Only applies to IPv6.
4021 	 */
4022 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
4023 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
4024 			switch (ixa->ixa_use_min_mtu) {
4025 			case IPV6_USE_MIN_MTU_MULTICAST:
4026 				if (ire->ire_type & IRE_MULTICAST)
4027 					pmtu = IPV6_MIN_MTU;
4028 				break;
4029 			case IPV6_USE_MIN_MTU_ALWAYS:
4030 				pmtu = IPV6_MIN_MTU;
4031 				break;
4032 			case IPV6_USE_MIN_MTU_NEVER:
4033 				break;
4034 			}
4035 		} else {
4036 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
4037 			if (ire->ire_type & IRE_MULTICAST)
4038 				pmtu = IPV6_MIN_MTU;
4039 		}
4040 	}
4041 
4042 	/*
4043 	 * After receiving an ICMPv6 "packet too big" message with a
4044 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
4045 	 * will insert a 8-byte fragment header in every packet. We compensate
4046 	 * for those cases by returning a smaller path MTU to the ULP.
4047 	 *
4048 	 * In the case of CGTP then ip_output will add a fragment header.
4049 	 * Make sure there is room for it by telling a smaller number
4050 	 * to the transport.
4051 	 *
4052 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
4053 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
4054 	 * which is the size of the packets it can send.
4055 	 */
4056 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
4057 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
4058 		    (ire->ire_flags & RTF_MULTIRT) ||
4059 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
4060 			pmtu -= sizeof (ip6_frag_t);
4061 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
4062 		}
4063 	}
4064 
4065 	return (pmtu);
4066 }
4067 
4068 /*
4069  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4070  * the final piece where we don't.  Return a pointer to the first mblk in the
4071  * result, and update the pointer to the next mblk to chew on.  If anything
4072  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4073  * NULL pointer.
4074  */
4075 mblk_t *
4076 ip_carve_mp(mblk_t **mpp, ssize_t len)
4077 {
4078 	mblk_t	*mp0;
4079 	mblk_t	*mp1;
4080 	mblk_t	*mp2;
4081 
4082 	if (!len || !mpp || !(mp0 = *mpp))
4083 		return (NULL);
4084 	/* If we aren't going to consume the first mblk, we need a dup. */
4085 	if (mp0->b_wptr - mp0->b_rptr > len) {
4086 		mp1 = dupb(mp0);
4087 		if (mp1) {
4088 			/* Partition the data between the two mblks. */
4089 			mp1->b_wptr = mp1->b_rptr + len;
4090 			mp0->b_rptr = mp1->b_wptr;
4091 			/*
4092 			 * after adjustments if mblk not consumed is now
4093 			 * unaligned, try to align it. If this fails free
4094 			 * all messages and let upper layer recover.
4095 			 */
4096 			if (!OK_32PTR(mp0->b_rptr)) {
4097 				if (!pullupmsg(mp0, -1)) {
4098 					freemsg(mp0);
4099 					freemsg(mp1);
4100 					*mpp = NULL;
4101 					return (NULL);
4102 				}
4103 			}
4104 		}
4105 		return (mp1);
4106 	}
4107 	/* Eat through as many mblks as we need to get len bytes. */
4108 	len -= mp0->b_wptr - mp0->b_rptr;
4109 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4110 		if (mp2->b_wptr - mp2->b_rptr > len) {
4111 			/*
4112 			 * We won't consume the entire last mblk.  Like
4113 			 * above, dup and partition it.
4114 			 */
4115 			mp1->b_cont = dupb(mp2);
4116 			mp1 = mp1->b_cont;
4117 			if (!mp1) {
4118 				/*
4119 				 * Trouble.  Rather than go to a lot of
4120 				 * trouble to clean up, we free the messages.
4121 				 * This won't be any worse than losing it on
4122 				 * the wire.
4123 				 */
4124 				freemsg(mp0);
4125 				freemsg(mp2);
4126 				*mpp = NULL;
4127 				return (NULL);
4128 			}
4129 			mp1->b_wptr = mp1->b_rptr + len;
4130 			mp2->b_rptr = mp1->b_wptr;
4131 			/*
4132 			 * after adjustments if mblk not consumed is now
4133 			 * unaligned, try to align it. If this fails free
4134 			 * all messages and let upper layer recover.
4135 			 */
4136 			if (!OK_32PTR(mp2->b_rptr)) {
4137 				if (!pullupmsg(mp2, -1)) {
4138 					freemsg(mp0);
4139 					freemsg(mp2);
4140 					*mpp = NULL;
4141 					return (NULL);
4142 				}
4143 			}
4144 			*mpp = mp2;
4145 			return (mp0);
4146 		}
4147 		/* Decrement len by the amount we just got. */
4148 		len -= mp2->b_wptr - mp2->b_rptr;
4149 	}
4150 	/*
4151 	 * len should be reduced to zero now.  If not our caller has
4152 	 * screwed up.
4153 	 */
4154 	if (len) {
4155 		/* Shouldn't happen! */
4156 		freemsg(mp0);
4157 		*mpp = NULL;
4158 		return (NULL);
4159 	}
4160 	/*
4161 	 * We consumed up to exactly the end of an mblk.  Detach the part
4162 	 * we are returning from the rest of the chain.
4163 	 */
4164 	mp1->b_cont = NULL;
4165 	*mpp = mp2;
4166 	return (mp0);
4167 }
4168 
4169 /* The ill stream is being unplumbed. Called from ip_close */
4170 int
4171 ip_modclose(ill_t *ill)
4172 {
4173 	boolean_t success;
4174 	ipsq_t	*ipsq;
4175 	ipif_t	*ipif;
4176 	queue_t	*q = ill->ill_rq;
4177 	ip_stack_t	*ipst = ill->ill_ipst;
4178 	int	i;
4179 	arl_ill_common_t *ai = ill->ill_common;
4180 
4181 	/*
4182 	 * The punlink prior to this may have initiated a capability
4183 	 * negotiation. But ipsq_enter will block until that finishes or
4184 	 * times out.
4185 	 */
4186 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
4187 
4188 	/*
4189 	 * Open/close/push/pop is guaranteed to be single threaded
4190 	 * per stream by STREAMS. FS guarantees that all references
4191 	 * from top are gone before close is called. So there can't
4192 	 * be another close thread that has set CONDEMNED on this ill.
4193 	 * and cause ipsq_enter to return failure.
4194 	 */
4195 	ASSERT(success);
4196 	ipsq = ill->ill_phyint->phyint_ipsq;
4197 
4198 	/*
4199 	 * Mark it condemned. No new reference will be made to this ill.
4200 	 * Lookup functions will return an error. Threads that try to
4201 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4202 	 * that the refcnt will drop down to zero.
4203 	 */
4204 	mutex_enter(&ill->ill_lock);
4205 	ill->ill_state_flags |= ILL_CONDEMNED;
4206 	for (ipif = ill->ill_ipif; ipif != NULL;
4207 	    ipif = ipif->ipif_next) {
4208 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4209 	}
4210 	/*
4211 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4212 	 * returns  error if ILL_CONDEMNED is set
4213 	 */
4214 	cv_broadcast(&ill->ill_cv);
4215 	mutex_exit(&ill->ill_lock);
4216 
4217 	/*
4218 	 * Send all the deferred DLPI messages downstream which came in
4219 	 * during the small window right before ipsq_enter(). We do this
4220 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4221 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4222 	 */
4223 	ill_dlpi_send_deferred(ill);
4224 
4225 	/*
4226 	 * Shut down fragmentation reassembly.
4227 	 * ill_frag_timer won't start a timer again.
4228 	 * Now cancel any existing timer
4229 	 */
4230 	(void) untimeout(ill->ill_frag_timer_id);
4231 	(void) ill_frag_timeout(ill, 0);
4232 
4233 	/*
4234 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4235 	 * this ill. Then wait for the refcnts to drop to zero.
4236 	 * ill_is_freeable checks whether the ill is really quiescent.
4237 	 * Then make sure that threads that are waiting to enter the
4238 	 * ipsq have seen the error returned by ipsq_enter and have
4239 	 * gone away. Then we call ill_delete_tail which does the
4240 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4241 	 */
4242 	ill_delete(ill);
4243 	mutex_enter(&ill->ill_lock);
4244 	while (!ill_is_freeable(ill))
4245 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4246 
4247 	while (ill->ill_waiters)
4248 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4249 
4250 	mutex_exit(&ill->ill_lock);
4251 
4252 	/*
4253 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4254 	 * it held until the end of the function since the cleanup
4255 	 * below needs to be able to use the ip_stack_t.
4256 	 */
4257 	netstack_hold(ipst->ips_netstack);
4258 
4259 	/* qprocsoff is done via ill_delete_tail */
4260 	ill_delete_tail(ill);
4261 	/*
4262 	 * synchronously wait for arp stream to unbind. After this, we
4263 	 * cannot get any data packets up from the driver.
4264 	 */
4265 	arp_unbind_complete(ill);
4266 	ASSERT(ill->ill_ipst == NULL);
4267 
4268 	/*
4269 	 * Walk through all conns and qenable those that have queued data.
4270 	 * Close synchronization needs this to
4271 	 * be done to ensure that all upper layers blocked
4272 	 * due to flow control to the closing device
4273 	 * get unblocked.
4274 	 */
4275 	ip1dbg(("ip_wsrv: walking\n"));
4276 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4277 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4278 	}
4279 
4280 	/*
4281 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4282 	 * stream is being torn down before ARP was plumbed (e.g.,
4283 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4284 	 * an error
4285 	 */
4286 	if (ai != NULL) {
4287 		ASSERT(!ill->ill_isv6);
4288 		mutex_enter(&ai->ai_lock);
4289 		ai->ai_ill = NULL;
4290 		if (ai->ai_arl == NULL) {
4291 			mutex_destroy(&ai->ai_lock);
4292 			kmem_free(ai, sizeof (*ai));
4293 		} else {
4294 			cv_signal(&ai->ai_ill_unplumb_done);
4295 			mutex_exit(&ai->ai_lock);
4296 		}
4297 	}
4298 
4299 	mutex_enter(&ipst->ips_ip_mi_lock);
4300 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4301 	mutex_exit(&ipst->ips_ip_mi_lock);
4302 
4303 	/*
4304 	 * credp could be null if the open didn't succeed and ip_modopen
4305 	 * itself calls ip_close.
4306 	 */
4307 	if (ill->ill_credp != NULL)
4308 		crfree(ill->ill_credp);
4309 
4310 	mutex_destroy(&ill->ill_saved_ire_lock);
4311 	mutex_destroy(&ill->ill_lock);
4312 	rw_destroy(&ill->ill_mcast_lock);
4313 	mutex_destroy(&ill->ill_mcast_serializer);
4314 	list_destroy(&ill->ill_nce);
4315 
4316 	/*
4317 	 * Now we are done with the module close pieces that
4318 	 * need the netstack_t.
4319 	 */
4320 	netstack_rele(ipst->ips_netstack);
4321 
4322 	mi_close_free((IDP)ill);
4323 	q->q_ptr = WR(q)->q_ptr = NULL;
4324 
4325 	ipsq_exit(ipsq);
4326 
4327 	return (0);
4328 }
4329 
4330 /*
4331  * This is called as part of close() for IP, UDP, ICMP, and RTS
4332  * in order to quiesce the conn.
4333  */
4334 void
4335 ip_quiesce_conn(conn_t *connp)
4336 {
4337 	boolean_t	drain_cleanup_reqd = B_FALSE;
4338 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4339 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4340 	ip_stack_t	*ipst;
4341 
4342 	ASSERT(!IPCL_IS_TCP(connp));
4343 	ipst = connp->conn_netstack->netstack_ip;
4344 
4345 	/*
4346 	 * Mark the conn as closing, and this conn must not be
4347 	 * inserted in future into any list. Eg. conn_drain_insert(),
4348 	 * won't insert this conn into the conn_drain_list.
4349 	 *
4350 	 * conn_idl, and conn_ilg cannot get set henceforth.
4351 	 */
4352 	mutex_enter(&connp->conn_lock);
4353 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4354 	connp->conn_state_flags |= CONN_CLOSING;
4355 	if (connp->conn_idl != NULL)
4356 		drain_cleanup_reqd = B_TRUE;
4357 	if (connp->conn_oper_pending_ill != NULL)
4358 		conn_ioctl_cleanup_reqd = B_TRUE;
4359 	if (connp->conn_dhcpinit_ill != NULL) {
4360 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4361 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4362 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4363 		connp->conn_dhcpinit_ill = NULL;
4364 	}
4365 	if (connp->conn_ilg != NULL)
4366 		ilg_cleanup_reqd = B_TRUE;
4367 	mutex_exit(&connp->conn_lock);
4368 
4369 	if (conn_ioctl_cleanup_reqd)
4370 		conn_ioctl_cleanup(connp);
4371 
4372 	if (is_system_labeled() && connp->conn_anon_port) {
4373 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4374 		    connp->conn_mlp_type, connp->conn_proto,
4375 		    ntohs(connp->conn_lport), B_FALSE);
4376 		connp->conn_anon_port = 0;
4377 	}
4378 	connp->conn_mlp_type = mlptSingle;
4379 
4380 	/*
4381 	 * Remove this conn from any fanout list it is on.
4382 	 * and then wait for any threads currently operating
4383 	 * on this endpoint to finish
4384 	 */
4385 	ipcl_hash_remove(connp);
4386 
4387 	/*
4388 	 * Remove this conn from the drain list, and do
4389 	 * any other cleanup that may be required.
4390 	 * (Only non-tcp conns may have a non-null conn_idl.
4391 	 * TCP conns are never flow controlled, and
4392 	 * conn_idl will be null)
4393 	 */
4394 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4395 		mutex_enter(&connp->conn_idl->idl_lock);
4396 		conn_drain_tail(connp, B_TRUE);
4397 		mutex_exit(&connp->conn_idl->idl_lock);
4398 	}
4399 
4400 	if (connp == ipst->ips_ip_g_mrouter)
4401 		(void) ip_mrouter_done(ipst);
4402 
4403 	if (ilg_cleanup_reqd)
4404 		ilg_delete_all(connp);
4405 
4406 	/*
4407 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4408 	 * callers from write side can't be there now because close
4409 	 * is in progress. The only other caller is ipcl_walk
4410 	 * which checks for the condemned flag.
4411 	 */
4412 	mutex_enter(&connp->conn_lock);
4413 	connp->conn_state_flags |= CONN_CONDEMNED;
4414 	while (connp->conn_ref != 1)
4415 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4416 	connp->conn_state_flags |= CONN_QUIESCED;
4417 	mutex_exit(&connp->conn_lock);
4418 }
4419 
4420 /* ARGSUSED */
4421 int
4422 ip_close(queue_t *q, int flags)
4423 {
4424 	conn_t		*connp;
4425 
4426 	/*
4427 	 * Call the appropriate delete routine depending on whether this is
4428 	 * a module or device.
4429 	 */
4430 	if (WR(q)->q_next != NULL) {
4431 		/* This is a module close */
4432 		return (ip_modclose((ill_t *)q->q_ptr));
4433 	}
4434 
4435 	connp = q->q_ptr;
4436 	ip_quiesce_conn(connp);
4437 
4438 	qprocsoff(q);
4439 
4440 	/*
4441 	 * Now we are truly single threaded on this stream, and can
4442 	 * delete the things hanging off the connp, and finally the connp.
4443 	 * We removed this connp from the fanout list, it cannot be
4444 	 * accessed thru the fanouts, and we already waited for the
4445 	 * conn_ref to drop to 0. We are already in close, so
4446 	 * there cannot be any other thread from the top. qprocsoff
4447 	 * has completed, and service has completed or won't run in
4448 	 * future.
4449 	 */
4450 	ASSERT(connp->conn_ref == 1);
4451 
4452 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4453 
4454 	connp->conn_ref--;
4455 	ipcl_conn_destroy(connp);
4456 
4457 	q->q_ptr = WR(q)->q_ptr = NULL;
4458 	return (0);
4459 }
4460 
4461 /*
4462  * Wapper around putnext() so that ip_rts_request can merely use
4463  * conn_recv.
4464  */
4465 /*ARGSUSED2*/
4466 static void
4467 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4468 {
4469 	conn_t *connp = (conn_t *)arg1;
4470 
4471 	putnext(connp->conn_rq, mp);
4472 }
4473 
4474 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4475 /* ARGSUSED */
4476 static void
4477 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4478 {
4479 	freemsg(mp);
4480 }
4481 
4482 /*
4483  * Called when the module is about to be unloaded
4484  */
4485 void
4486 ip_ddi_destroy(void)
4487 {
4488 	tnet_fini();
4489 
4490 	icmp_ddi_g_destroy();
4491 	rts_ddi_g_destroy();
4492 	udp_ddi_g_destroy();
4493 	sctp_ddi_g_destroy();
4494 	tcp_ddi_g_destroy();
4495 	ilb_ddi_g_destroy();
4496 	dce_g_destroy();
4497 	ipsec_policy_g_destroy();
4498 	ipcl_g_destroy();
4499 	ip_net_g_destroy();
4500 	ip_ire_g_fini();
4501 	inet_minor_destroy(ip_minor_arena_sa);
4502 #if defined(_LP64)
4503 	inet_minor_destroy(ip_minor_arena_la);
4504 #endif
4505 
4506 #ifdef DEBUG
4507 	list_destroy(&ip_thread_list);
4508 	rw_destroy(&ip_thread_rwlock);
4509 	tsd_destroy(&ip_thread_data);
4510 #endif
4511 
4512 	netstack_unregister(NS_IP);
4513 }
4514 
4515 /*
4516  * First step in cleanup.
4517  */
4518 /* ARGSUSED */
4519 static void
4520 ip_stack_shutdown(netstackid_t stackid, void *arg)
4521 {
4522 	ip_stack_t *ipst = (ip_stack_t *)arg;
4523 
4524 #ifdef NS_DEBUG
4525 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4526 #endif
4527 
4528 	/*
4529 	 * Perform cleanup for special interfaces (loopback and IPMP).
4530 	 */
4531 	ip_interface_cleanup(ipst);
4532 
4533 	/*
4534 	 * The *_hook_shutdown()s start the process of notifying any
4535 	 * consumers that things are going away.... nothing is destroyed.
4536 	 */
4537 	ipv4_hook_shutdown(ipst);
4538 	ipv6_hook_shutdown(ipst);
4539 	arp_hook_shutdown(ipst);
4540 
4541 	mutex_enter(&ipst->ips_capab_taskq_lock);
4542 	ipst->ips_capab_taskq_quit = B_TRUE;
4543 	cv_signal(&ipst->ips_capab_taskq_cv);
4544 	mutex_exit(&ipst->ips_capab_taskq_lock);
4545 }
4546 
4547 /*
4548  * Free the IP stack instance.
4549  */
4550 static void
4551 ip_stack_fini(netstackid_t stackid, void *arg)
4552 {
4553 	ip_stack_t *ipst = (ip_stack_t *)arg;
4554 	int ret;
4555 
4556 #ifdef NS_DEBUG
4557 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4558 #endif
4559 	/*
4560 	 * At this point, all of the notifications that the events and
4561 	 * protocols are going away have been run, meaning that we can
4562 	 * now set about starting to clean things up.
4563 	 */
4564 	ipobs_fini(ipst);
4565 	ipv4_hook_destroy(ipst);
4566 	ipv6_hook_destroy(ipst);
4567 	arp_hook_destroy(ipst);
4568 	ip_net_destroy(ipst);
4569 
4570 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4571 	cv_destroy(&ipst->ips_capab_taskq_cv);
4572 
4573 	ipmp_destroy(ipst);
4574 	rw_destroy(&ipst->ips_srcid_lock);
4575 
4576 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4577 	ipst->ips_ip_mibkp = NULL;
4578 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4579 	ipst->ips_icmp_mibkp = NULL;
4580 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4581 	ipst->ips_ip_kstat = NULL;
4582 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4583 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4584 	ipst->ips_ip6_kstat = NULL;
4585 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4586 
4587 	nd_free(&ipst->ips_ip_g_nd);
4588 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
4589 	ipst->ips_param_arr = NULL;
4590 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
4591 	ipst->ips_ndp_arr = NULL;
4592 
4593 	dce_stack_destroy(ipst);
4594 	ip_mrouter_stack_destroy(ipst);
4595 
4596 	mutex_destroy(&ipst->ips_ip_mi_lock);
4597 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4598 	rw_destroy(&ipst->ips_ip_g_nd_lock);
4599 
4600 	ret = untimeout(ipst->ips_igmp_timeout_id);
4601 	if (ret == -1) {
4602 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4603 	} else {
4604 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4605 		ipst->ips_igmp_timeout_id = 0;
4606 	}
4607 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4608 	if (ret == -1) {
4609 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4610 	} else {
4611 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4612 		ipst->ips_igmp_slowtimeout_id = 0;
4613 	}
4614 	ret = untimeout(ipst->ips_mld_timeout_id);
4615 	if (ret == -1) {
4616 		ASSERT(ipst->ips_mld_timeout_id == 0);
4617 	} else {
4618 		ASSERT(ipst->ips_mld_timeout_id != 0);
4619 		ipst->ips_mld_timeout_id = 0;
4620 	}
4621 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4622 	if (ret == -1) {
4623 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4624 	} else {
4625 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4626 		ipst->ips_mld_slowtimeout_id = 0;
4627 	}
4628 
4629 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4630 	mutex_destroy(&ipst->ips_mld_timer_lock);
4631 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4632 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4633 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4634 	rw_destroy(&ipst->ips_ill_g_lock);
4635 
4636 	ip_ire_fini(ipst);
4637 	ip6_asp_free(ipst);
4638 	conn_drain_fini(ipst);
4639 	ipcl_destroy(ipst);
4640 
4641 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4642 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4643 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4644 	ipst->ips_ndp4 = NULL;
4645 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4646 	ipst->ips_ndp6 = NULL;
4647 
4648 	if (ipst->ips_loopback_ksp != NULL) {
4649 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4650 		ipst->ips_loopback_ksp = NULL;
4651 	}
4652 
4653 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4654 	ipst->ips_phyint_g_list = NULL;
4655 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4656 	ipst->ips_ill_g_heads = NULL;
4657 
4658 	ldi_ident_release(ipst->ips_ldi_ident);
4659 	kmem_free(ipst, sizeof (*ipst));
4660 }
4661 
4662 /*
4663  * This function is called from the TSD destructor, and is used to debug
4664  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4665  * details.
4666  */
4667 static void
4668 ip_thread_exit(void *phash)
4669 {
4670 	th_hash_t *thh = phash;
4671 
4672 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4673 	list_remove(&ip_thread_list, thh);
4674 	rw_exit(&ip_thread_rwlock);
4675 	mod_hash_destroy_hash(thh->thh_hash);
4676 	kmem_free(thh, sizeof (*thh));
4677 }
4678 
4679 /*
4680  * Called when the IP kernel module is loaded into the kernel
4681  */
4682 void
4683 ip_ddi_init(void)
4684 {
4685 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4686 
4687 	/*
4688 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4689 	 * initial devices: ip, ip6, tcp, tcp6.
4690 	 */
4691 	/*
4692 	 * If this is a 64-bit kernel, then create two separate arenas -
4693 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4694 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4695 	 */
4696 	ip_minor_arena_la = NULL;
4697 	ip_minor_arena_sa = NULL;
4698 #if defined(_LP64)
4699 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4700 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4701 		cmn_err(CE_PANIC,
4702 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4703 	}
4704 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4705 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4706 		cmn_err(CE_PANIC,
4707 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4708 	}
4709 #else
4710 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4711 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4712 		cmn_err(CE_PANIC,
4713 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4714 	}
4715 #endif
4716 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4717 
4718 	ipcl_g_init();
4719 	ip_ire_g_init();
4720 	ip_net_g_init();
4721 
4722 #ifdef DEBUG
4723 	tsd_create(&ip_thread_data, ip_thread_exit);
4724 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4725 	list_create(&ip_thread_list, sizeof (th_hash_t),
4726 	    offsetof(th_hash_t, thh_link));
4727 #endif
4728 	ipsec_policy_g_init();
4729 	tcp_ddi_g_init();
4730 	sctp_ddi_g_init();
4731 	dce_g_init();
4732 
4733 	/*
4734 	 * We want to be informed each time a stack is created or
4735 	 * destroyed in the kernel, so we can maintain the
4736 	 * set of udp_stack_t's.
4737 	 */
4738 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4739 	    ip_stack_fini);
4740 
4741 	tnet_init();
4742 
4743 	udp_ddi_g_init();
4744 	rts_ddi_g_init();
4745 	icmp_ddi_g_init();
4746 	ilb_ddi_g_init();
4747 }
4748 
4749 /*
4750  * Initialize the IP stack instance.
4751  */
4752 static void *
4753 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4754 {
4755 	ip_stack_t	*ipst;
4756 	ipparam_t	*pa;
4757 	ipndp_t		*na;
4758 	major_t		major;
4759 
4760 #ifdef NS_DEBUG
4761 	printf("ip_stack_init(stack %d)\n", stackid);
4762 #endif
4763 
4764 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4765 	ipst->ips_netstack = ns;
4766 
4767 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4768 	    KM_SLEEP);
4769 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4770 	    KM_SLEEP);
4771 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4772 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4773 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4774 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4775 
4776 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
4777 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4778 	ipst->ips_igmp_deferred_next = INFINITY;
4779 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4780 	ipst->ips_mld_deferred_next = INFINITY;
4781 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4782 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4783 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4784 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4785 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4786 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4787 
4788 	ipcl_init(ipst);
4789 	ip_ire_init(ipst);
4790 	ip6_asp_init(ipst);
4791 	ipif_init(ipst);
4792 	conn_drain_init(ipst);
4793 	ip_mrouter_stack_init(ipst);
4794 	dce_stack_init(ipst);
4795 
4796 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
4797 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
4798 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
4799 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
4800 
4801 	ipst->ips_ip_multirt_log_interval = 1000;
4802 
4803 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
4804 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
4805 	ipst->ips_ill_index = 1;
4806 
4807 	ipst->ips_saved_ip_g_forward = -1;
4808 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4809 
4810 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
4811 	ipst->ips_param_arr = pa;
4812 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
4813 
4814 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
4815 	ipst->ips_ndp_arr = na;
4816 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
4817 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
4818 	    (caddr_t)&ipst->ips_ip_g_forward;
4819 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
4820 	    (caddr_t)&ipst->ips_ipv6_forward;
4821 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
4822 	    "ip_cgtp_filter") == 0);
4823 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
4824 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
4825 
4826 	(void) ip_param_register(&ipst->ips_ip_g_nd,
4827 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
4828 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
4829 
4830 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4831 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4832 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4833 	ipst->ips_ip6_kstat =
4834 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4835 
4836 	ipst->ips_ip_src_id = 1;
4837 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4838 
4839 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4840 
4841 	ip_net_init(ipst, ns);
4842 	ipv4_hook_init(ipst);
4843 	ipv6_hook_init(ipst);
4844 	arp_hook_init(ipst);
4845 	ipmp_init(ipst);
4846 	ipobs_init(ipst);
4847 
4848 	/*
4849 	 * Create the taskq dispatcher thread and initialize related stuff.
4850 	 */
4851 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4852 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4853 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4854 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4855 
4856 	major = mod_name_to_major(INET_NAME);
4857 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4858 	return (ipst);
4859 }
4860 
4861 /*
4862  * Allocate and initialize a DLPI template of the specified length.  (May be
4863  * called as writer.)
4864  */
4865 mblk_t *
4866 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4867 {
4868 	mblk_t	*mp;
4869 
4870 	mp = allocb(len, BPRI_MED);
4871 	if (!mp)
4872 		return (NULL);
4873 
4874 	/*
4875 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4876 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4877 	 * that other DLPI are M_PROTO.
4878 	 */
4879 	if (prim == DL_INFO_REQ) {
4880 		mp->b_datap->db_type = M_PCPROTO;
4881 	} else {
4882 		mp->b_datap->db_type = M_PROTO;
4883 	}
4884 
4885 	mp->b_wptr = mp->b_rptr + len;
4886 	bzero(mp->b_rptr, len);
4887 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4888 	return (mp);
4889 }
4890 
4891 /*
4892  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4893  */
4894 mblk_t *
4895 ip_dlnotify_alloc(uint_t notification, uint_t data)
4896 {
4897 	dl_notify_ind_t	*notifyp;
4898 	mblk_t		*mp;
4899 
4900 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4901 		return (NULL);
4902 
4903 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4904 	notifyp->dl_notification = notification;
4905 	notifyp->dl_data = data;
4906 	return (mp);
4907 }
4908 
4909 /*
4910  * Debug formatting routine.  Returns a character string representation of the
4911  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4912  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4913  *
4914  * Once the ndd table-printing interfaces are removed, this can be changed to
4915  * standard dotted-decimal form.
4916  */
4917 char *
4918 ip_dot_addr(ipaddr_t addr, char *buf)
4919 {
4920 	uint8_t *ap = (uint8_t *)&addr;
4921 
4922 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4923 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4924 	return (buf);
4925 }
4926 
4927 /*
4928  * Write the given MAC address as a printable string in the usual colon-
4929  * separated format.
4930  */
4931 const char *
4932 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4933 {
4934 	char *bp;
4935 
4936 	if (alen == 0 || buflen < 4)
4937 		return ("?");
4938 	bp = buf;
4939 	for (;;) {
4940 		/*
4941 		 * If there are more MAC address bytes available, but we won't
4942 		 * have any room to print them, then add "..." to the string
4943 		 * instead.  See below for the 'magic number' explanation.
4944 		 */
4945 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4946 			(void) strcpy(bp, "...");
4947 			break;
4948 		}
4949 		(void) sprintf(bp, "%02x", *addr++);
4950 		bp += 2;
4951 		if (--alen == 0)
4952 			break;
4953 		*bp++ = ':';
4954 		buflen -= 3;
4955 		/*
4956 		 * At this point, based on the first 'if' statement above,
4957 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4958 		 * buflen >= 4.  The first case leaves room for the final "xx"
4959 		 * number and trailing NUL byte.  The second leaves room for at
4960 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4961 		 * that statement.
4962 		 */
4963 	}
4964 	return (buf);
4965 }
4966 
4967 /*
4968  * Called when it is conceptually a ULP that would sent the packet
4969  * e.g., port unreachable and protocol unreachable. Check that the packet
4970  * would have passed the IPsec global policy before sending the error.
4971  *
4972  * Send an ICMP error after patching up the packet appropriately.
4973  * Uses ip_drop_input and bumps the appropriate MIB.
4974  */
4975 void
4976 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4977     ip_recv_attr_t *ira)
4978 {
4979 	ipha_t		*ipha;
4980 	boolean_t	secure;
4981 	ill_t		*ill = ira->ira_ill;
4982 	ip_stack_t	*ipst = ill->ill_ipst;
4983 	netstack_t	*ns = ipst->ips_netstack;
4984 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4985 
4986 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4987 
4988 	/*
4989 	 * We are generating an icmp error for some inbound packet.
4990 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4991 	 * Before we generate an error, check with global policy
4992 	 * to see whether this is allowed to enter the system. As
4993 	 * there is no "conn", we are checking with global policy.
4994 	 */
4995 	ipha = (ipha_t *)mp->b_rptr;
4996 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4997 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4998 		if (mp == NULL)
4999 			return;
5000 	}
5001 
5002 	/* We never send errors for protocols that we do implement */
5003 	if (ira->ira_protocol == IPPROTO_ICMP ||
5004 	    ira->ira_protocol == IPPROTO_IGMP) {
5005 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5006 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
5007 		freemsg(mp);
5008 		return;
5009 	}
5010 	/*
5011 	 * Have to correct checksum since
5012 	 * the packet might have been
5013 	 * fragmented and the reassembly code in ip_rput
5014 	 * does not restore the IP checksum.
5015 	 */
5016 	ipha->ipha_hdr_checksum = 0;
5017 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5018 
5019 	switch (icmp_type) {
5020 	case ICMP_DEST_UNREACHABLE:
5021 		switch (icmp_code) {
5022 		case ICMP_PROTOCOL_UNREACHABLE:
5023 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
5024 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
5025 			break;
5026 		case ICMP_PORT_UNREACHABLE:
5027 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5028 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
5029 			break;
5030 		}
5031 
5032 		icmp_unreachable(mp, icmp_code, ira);
5033 		break;
5034 	default:
5035 #ifdef DEBUG
5036 		panic("ip_fanout_send_icmp_v4: wrong type");
5037 		/*NOTREACHED*/
5038 #else
5039 		freemsg(mp);
5040 		break;
5041 #endif
5042 	}
5043 }
5044 
5045 /*
5046  * Used to send an ICMP error message when a packet is received for
5047  * a protocol that is not supported. The mblk passed as argument
5048  * is consumed by this function.
5049  */
5050 void
5051 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
5052 {
5053 	ipha_t		*ipha;
5054 
5055 	ipha = (ipha_t *)mp->b_rptr;
5056 	if (ira->ira_flags & IRAF_IS_IPV4) {
5057 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
5058 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5059 		    ICMP_PROTOCOL_UNREACHABLE, ira);
5060 	} else {
5061 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
5062 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
5063 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
5064 	}
5065 }
5066 
5067 /*
5068  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
5069  * Handles IPv4 and IPv6.
5070  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5071  * Caller is responsible for dropping references to the conn.
5072  */
5073 void
5074 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5075     ip_recv_attr_t *ira)
5076 {
5077 	ill_t		*ill = ira->ira_ill;
5078 	ip_stack_t	*ipst = ill->ill_ipst;
5079 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5080 	boolean_t	secure;
5081 	uint_t		protocol = ira->ira_protocol;
5082 	iaflags_t	iraflags = ira->ira_flags;
5083 	queue_t		*rq;
5084 
5085 	secure = iraflags & IRAF_IPSEC_SECURE;
5086 
5087 	rq = connp->conn_rq;
5088 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
5089 		switch (protocol) {
5090 		case IPPROTO_ICMPV6:
5091 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
5092 			break;
5093 		case IPPROTO_ICMP:
5094 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
5095 			break;
5096 		default:
5097 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
5098 			break;
5099 		}
5100 		freemsg(mp);
5101 		return;
5102 	}
5103 
5104 	ASSERT(!(IPCL_IS_IPTUN(connp)));
5105 
5106 	if (((iraflags & IRAF_IS_IPV4) ?
5107 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5108 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5109 	    secure) {
5110 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5111 		    ip6h, ira);
5112 		if (mp == NULL) {
5113 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5114 			/* Note that mp is NULL */
5115 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5116 			return;
5117 		}
5118 	}
5119 
5120 	if (iraflags & IRAF_ICMP_ERROR) {
5121 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5122 	} else {
5123 		ill_t *rill = ira->ira_rill;
5124 
5125 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5126 		ira->ira_ill = ira->ira_rill = NULL;
5127 		/* Send it upstream */
5128 		(connp->conn_recv)(connp, mp, NULL, ira);
5129 		ira->ira_ill = ill;
5130 		ira->ira_rill = rill;
5131 	}
5132 }
5133 
5134 /*
5135  * Handle protocols with which IP is less intimate.  There
5136  * can be more than one stream bound to a particular
5137  * protocol.  When this is the case, normally each one gets a copy
5138  * of any incoming packets.
5139  *
5140  * IPsec NOTE :
5141  *
5142  * Don't allow a secure packet going up a non-secure connection.
5143  * We don't allow this because
5144  *
5145  * 1) Reply might go out in clear which will be dropped at
5146  *    the sending side.
5147  * 2) If the reply goes out in clear it will give the
5148  *    adversary enough information for getting the key in
5149  *    most of the cases.
5150  *
5151  * Moreover getting a secure packet when we expect clear
5152  * implies that SA's were added without checking for
5153  * policy on both ends. This should not happen once ISAKMP
5154  * is used to negotiate SAs as SAs will be added only after
5155  * verifying the policy.
5156  *
5157  * Zones notes:
5158  * Earlier in ip_input on a system with multiple shared-IP zones we
5159  * duplicate the multicast and broadcast packets and send them up
5160  * with each explicit zoneid that exists on that ill.
5161  * This means that here we can match the zoneid with SO_ALLZONES being special.
5162  */
5163 void
5164 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
5165 {
5166 	mblk_t		*mp1;
5167 	ipaddr_t	laddr;
5168 	conn_t		*connp, *first_connp, *next_connp;
5169 	connf_t		*connfp;
5170 	ill_t		*ill = ira->ira_ill;
5171 	ip_stack_t	*ipst = ill->ill_ipst;
5172 
5173 	laddr = ipha->ipha_dst;
5174 
5175 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
5176 	mutex_enter(&connfp->connf_lock);
5177 	connp = connfp->connf_head;
5178 	for (connp = connfp->connf_head; connp != NULL;
5179 	    connp = connp->conn_next) {
5180 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5181 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5182 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5183 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
5184 			break;
5185 		}
5186 	}
5187 
5188 	if (connp == NULL) {
5189 		/*
5190 		 * No one bound to these addresses.  Is
5191 		 * there a client that wants all
5192 		 * unclaimed datagrams?
5193 		 */
5194 		mutex_exit(&connfp->connf_lock);
5195 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5196 		    ICMP_PROTOCOL_UNREACHABLE, ira);
5197 		return;
5198 	}
5199 
5200 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5201 
5202 	CONN_INC_REF(connp);
5203 	first_connp = connp;
5204 	connp = connp->conn_next;
5205 
5206 	for (;;) {
5207 		while (connp != NULL) {
5208 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5209 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5210 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5211 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5212 			    ira, connp)))
5213 				break;
5214 			connp = connp->conn_next;
5215 		}
5216 
5217 		if (connp == NULL) {
5218 			/* No more interested clients */
5219 			connp = first_connp;
5220 			break;
5221 		}
5222 		if (((mp1 = dupmsg(mp)) == NULL) &&
5223 		    ((mp1 = copymsg(mp)) == NULL)) {
5224 			/* Memory allocation failed */
5225 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5226 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5227 			connp = first_connp;
5228 			break;
5229 		}
5230 
5231 		CONN_INC_REF(connp);
5232 		mutex_exit(&connfp->connf_lock);
5233 
5234 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5235 		    ira);
5236 
5237 		mutex_enter(&connfp->connf_lock);
5238 		/* Follow the next pointer before releasing the conn. */
5239 		next_connp = connp->conn_next;
5240 		CONN_DEC_REF(connp);
5241 		connp = next_connp;
5242 	}
5243 
5244 	/* Last one.  Send it upstream. */
5245 	mutex_exit(&connfp->connf_lock);
5246 
5247 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5248 
5249 	CONN_DEC_REF(connp);
5250 }
5251 
5252 /*
5253  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5254  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5255  * is not consumed.
5256  *
5257  * One of three things can happen, all of which affect the passed-in mblk:
5258  *
5259  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5260  *
5261  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5262  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5263  *
5264  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5265  */
5266 mblk_t *
5267 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5268 {
5269 	int shift, plen, iph_len;
5270 	ipha_t *ipha;
5271 	udpha_t *udpha;
5272 	uint32_t *spi;
5273 	uint32_t esp_ports;
5274 	uint8_t *orptr;
5275 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5276 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5277 
5278 	ipha = (ipha_t *)mp->b_rptr;
5279 	iph_len = ira->ira_ip_hdr_length;
5280 	plen = ira->ira_pktlen;
5281 
5282 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5283 		/*
5284 		 * Most likely a keepalive for the benefit of an intervening
5285 		 * NAT.  These aren't for us, per se, so drop it.
5286 		 *
5287 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5288 		 * byte packets (keepalives are 1-byte), but we'll drop them
5289 		 * also.
5290 		 */
5291 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5292 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5293 		return (NULL);
5294 	}
5295 
5296 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5297 		/* might as well pull it all up - it might be ESP. */
5298 		if (!pullupmsg(mp, -1)) {
5299 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5300 			    DROPPER(ipss, ipds_esp_nomem),
5301 			    &ipss->ipsec_dropper);
5302 			return (NULL);
5303 		}
5304 
5305 		ipha = (ipha_t *)mp->b_rptr;
5306 	}
5307 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5308 	if (*spi == 0) {
5309 		/* UDP packet - remove 0-spi. */
5310 		shift = sizeof (uint32_t);
5311 	} else {
5312 		/* ESP-in-UDP packet - reduce to ESP. */
5313 		ipha->ipha_protocol = IPPROTO_ESP;
5314 		shift = sizeof (udpha_t);
5315 	}
5316 
5317 	/* Fix IP header */
5318 	ira->ira_pktlen = (plen - shift);
5319 	ipha->ipha_length = htons(ira->ira_pktlen);
5320 	ipha->ipha_hdr_checksum = 0;
5321 
5322 	orptr = mp->b_rptr;
5323 	mp->b_rptr += shift;
5324 
5325 	udpha = (udpha_t *)(orptr + iph_len);
5326 	if (*spi == 0) {
5327 		ASSERT((uint8_t *)ipha == orptr);
5328 		udpha->uha_length = htons(plen - shift - iph_len);
5329 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5330 		esp_ports = 0;
5331 	} else {
5332 		esp_ports = *((uint32_t *)udpha);
5333 		ASSERT(esp_ports != 0);
5334 	}
5335 	ovbcopy(orptr, orptr + shift, iph_len);
5336 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5337 		ipha = (ipha_t *)(orptr + shift);
5338 
5339 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5340 		ira->ira_esp_udp_ports = esp_ports;
5341 		ip_fanout_v4(mp, ipha, ira);
5342 		return (NULL);
5343 	}
5344 	return (mp);
5345 }
5346 
5347 /*
5348  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5349  * Handles IPv4 and IPv6.
5350  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5351  * Caller is responsible for dropping references to the conn.
5352  */
5353 void
5354 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5355     ip_recv_attr_t *ira)
5356 {
5357 	ill_t		*ill = ira->ira_ill;
5358 	ip_stack_t	*ipst = ill->ill_ipst;
5359 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5360 	boolean_t	secure;
5361 	iaflags_t	iraflags = ira->ira_flags;
5362 
5363 	secure = iraflags & IRAF_IPSEC_SECURE;
5364 
5365 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5366 	    !canputnext(connp->conn_rq)) {
5367 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5368 		freemsg(mp);
5369 		return;
5370 	}
5371 
5372 	if (((iraflags & IRAF_IS_IPV4) ?
5373 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5374 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5375 	    secure) {
5376 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5377 		    ip6h, ira);
5378 		if (mp == NULL) {
5379 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5380 			/* Note that mp is NULL */
5381 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5382 			return;
5383 		}
5384 	}
5385 
5386 	/*
5387 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5388 	 * check. Only ip_fanout_v4 has that check.
5389 	 */
5390 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5391 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5392 	} else {
5393 		ill_t *rill = ira->ira_rill;
5394 
5395 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5396 		ira->ira_ill = ira->ira_rill = NULL;
5397 		/* Send it upstream */
5398 		(connp->conn_recv)(connp, mp, NULL, ira);
5399 		ira->ira_ill = ill;
5400 		ira->ira_rill = rill;
5401 	}
5402 }
5403 
5404 /*
5405  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5406  * (Unicast fanout is handled in ip_input_v4.)
5407  *
5408  * If SO_REUSEADDR is set all multicast and broadcast packets
5409  * will be delivered to all conns bound to the same port.
5410  *
5411  * If there is at least one matching AF_INET receiver, then we will
5412  * ignore any AF_INET6 receivers.
5413  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5414  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5415  * packets.
5416  *
5417  * Zones notes:
5418  * Earlier in ip_input on a system with multiple shared-IP zones we
5419  * duplicate the multicast and broadcast packets and send them up
5420  * with each explicit zoneid that exists on that ill.
5421  * This means that here we can match the zoneid with SO_ALLZONES being special.
5422  */
5423 void
5424 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5425     ip_recv_attr_t *ira)
5426 {
5427 	ipaddr_t	laddr;
5428 	in6_addr_t	v6faddr;
5429 	conn_t		*connp;
5430 	connf_t		*connfp;
5431 	ipaddr_t	faddr;
5432 	ill_t		*ill = ira->ira_ill;
5433 	ip_stack_t	*ipst = ill->ill_ipst;
5434 
5435 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5436 
5437 	laddr = ipha->ipha_dst;
5438 	faddr = ipha->ipha_src;
5439 
5440 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5441 	mutex_enter(&connfp->connf_lock);
5442 	connp = connfp->connf_head;
5443 
5444 	/*
5445 	 * If SO_REUSEADDR has been set on the first we send the
5446 	 * packet to all clients that have joined the group and
5447 	 * match the port.
5448 	 */
5449 	while (connp != NULL) {
5450 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5451 		    conn_wantpacket(connp, ira, ipha) &&
5452 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5453 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5454 			break;
5455 		connp = connp->conn_next;
5456 	}
5457 
5458 	if (connp == NULL)
5459 		goto notfound;
5460 
5461 	CONN_INC_REF(connp);
5462 
5463 	if (connp->conn_reuseaddr) {
5464 		conn_t		*first_connp = connp;
5465 		conn_t		*next_connp;
5466 		mblk_t		*mp1;
5467 
5468 		connp = connp->conn_next;
5469 		for (;;) {
5470 			while (connp != NULL) {
5471 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5472 				    fport, faddr) &&
5473 				    conn_wantpacket(connp, ira, ipha) &&
5474 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5475 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5476 				    ira, connp)))
5477 					break;
5478 				connp = connp->conn_next;
5479 			}
5480 			if (connp == NULL) {
5481 				/* No more interested clients */
5482 				connp = first_connp;
5483 				break;
5484 			}
5485 			if (((mp1 = dupmsg(mp)) == NULL) &&
5486 			    ((mp1 = copymsg(mp)) == NULL)) {
5487 				/* Memory allocation failed */
5488 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5489 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5490 				connp = first_connp;
5491 				break;
5492 			}
5493 			CONN_INC_REF(connp);
5494 			mutex_exit(&connfp->connf_lock);
5495 
5496 			IP_STAT(ipst, ip_udp_fanmb);
5497 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5498 			    NULL, ira);
5499 			mutex_enter(&connfp->connf_lock);
5500 			/* Follow the next pointer before releasing the conn */
5501 			next_connp = connp->conn_next;
5502 			CONN_DEC_REF(connp);
5503 			connp = next_connp;
5504 		}
5505 	}
5506 
5507 	/* Last one.  Send it upstream. */
5508 	mutex_exit(&connfp->connf_lock);
5509 	IP_STAT(ipst, ip_udp_fanmb);
5510 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5511 	CONN_DEC_REF(connp);
5512 	return;
5513 
5514 notfound:
5515 	mutex_exit(&connfp->connf_lock);
5516 	/*
5517 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5518 	 * have already been matched above, since they live in the IPv4
5519 	 * fanout tables. This implies we only need to
5520 	 * check for IPv6 in6addr_any endpoints here.
5521 	 * Thus we compare using ipv6_all_zeros instead of the destination
5522 	 * address, except for the multicast group membership lookup which
5523 	 * uses the IPv4 destination.
5524 	 */
5525 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5526 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5527 	mutex_enter(&connfp->connf_lock);
5528 	connp = connfp->connf_head;
5529 	/*
5530 	 * IPv4 multicast packet being delivered to an AF_INET6
5531 	 * in6addr_any endpoint.
5532 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5533 	 * and not conn_wantpacket_v6() since any multicast membership is
5534 	 * for an IPv4-mapped multicast address.
5535 	 */
5536 	while (connp != NULL) {
5537 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5538 		    fport, v6faddr) &&
5539 		    conn_wantpacket(connp, ira, ipha) &&
5540 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5541 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5542 			break;
5543 		connp = connp->conn_next;
5544 	}
5545 
5546 	if (connp == NULL) {
5547 		/*
5548 		 * No one bound to this port.  Is
5549 		 * there a client that wants all
5550 		 * unclaimed datagrams?
5551 		 */
5552 		mutex_exit(&connfp->connf_lock);
5553 
5554 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5555 		    NULL) {
5556 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5557 			ip_fanout_proto_v4(mp, ipha, ira);
5558 		} else {
5559 			/*
5560 			 * We used to attempt to send an icmp error here, but
5561 			 * since this is known to be a multicast packet
5562 			 * and we don't send icmp errors in response to
5563 			 * multicast, just drop the packet and give up sooner.
5564 			 */
5565 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5566 			freemsg(mp);
5567 		}
5568 		return;
5569 	}
5570 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5571 
5572 	/*
5573 	 * If SO_REUSEADDR has been set on the first we send the
5574 	 * packet to all clients that have joined the group and
5575 	 * match the port.
5576 	 */
5577 	if (connp->conn_reuseaddr) {
5578 		conn_t		*first_connp = connp;
5579 		conn_t		*next_connp;
5580 		mblk_t		*mp1;
5581 
5582 		CONN_INC_REF(connp);
5583 		connp = connp->conn_next;
5584 		for (;;) {
5585 			while (connp != NULL) {
5586 				if (IPCL_UDP_MATCH_V6(connp, lport,
5587 				    ipv6_all_zeros, fport, v6faddr) &&
5588 				    conn_wantpacket(connp, ira, ipha) &&
5589 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5590 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5591 				    ira, connp)))
5592 					break;
5593 				connp = connp->conn_next;
5594 			}
5595 			if (connp == NULL) {
5596 				/* No more interested clients */
5597 				connp = first_connp;
5598 				break;
5599 			}
5600 			if (((mp1 = dupmsg(mp)) == NULL) &&
5601 			    ((mp1 = copymsg(mp)) == NULL)) {
5602 				/* Memory allocation failed */
5603 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5604 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5605 				connp = first_connp;
5606 				break;
5607 			}
5608 			CONN_INC_REF(connp);
5609 			mutex_exit(&connfp->connf_lock);
5610 
5611 			IP_STAT(ipst, ip_udp_fanmb);
5612 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5613 			    NULL, ira);
5614 			mutex_enter(&connfp->connf_lock);
5615 			/* Follow the next pointer before releasing the conn */
5616 			next_connp = connp->conn_next;
5617 			CONN_DEC_REF(connp);
5618 			connp = next_connp;
5619 		}
5620 	}
5621 
5622 	/* Last one.  Send it upstream. */
5623 	mutex_exit(&connfp->connf_lock);
5624 	IP_STAT(ipst, ip_udp_fanmb);
5625 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5626 	CONN_DEC_REF(connp);
5627 }
5628 
5629 /*
5630  * Split an incoming packet's IPv4 options into the label and the other options.
5631  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5632  * clearing out any leftover label or options.
5633  * Otherwise it just makes ipp point into the packet.
5634  *
5635  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5636  */
5637 int
5638 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5639 {
5640 	uchar_t		*opt;
5641 	uint32_t	totallen;
5642 	uint32_t	optval;
5643 	uint32_t	optlen;
5644 
5645 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5646 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5647 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5648 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5649 
5650 	/*
5651 	 * Get length (in 4 byte octets) of IP header options.
5652 	 */
5653 	totallen = ipha->ipha_version_and_hdr_length -
5654 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5655 
5656 	if (totallen == 0) {
5657 		if (!allocate)
5658 			return (0);
5659 
5660 		/* Clear out anything from a previous packet */
5661 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5662 			kmem_free(ipp->ipp_ipv4_options,
5663 			    ipp->ipp_ipv4_options_len);
5664 			ipp->ipp_ipv4_options = NULL;
5665 			ipp->ipp_ipv4_options_len = 0;
5666 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5667 		}
5668 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5669 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5670 			ipp->ipp_label_v4 = NULL;
5671 			ipp->ipp_label_len_v4 = 0;
5672 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5673 		}
5674 		return (0);
5675 	}
5676 
5677 	totallen <<= 2;
5678 	opt = (uchar_t *)&ipha[1];
5679 	if (!is_system_labeled()) {
5680 
5681 	copyall:
5682 		if (!allocate) {
5683 			if (totallen != 0) {
5684 				ipp->ipp_ipv4_options = opt;
5685 				ipp->ipp_ipv4_options_len = totallen;
5686 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5687 			}
5688 			return (0);
5689 		}
5690 		/* Just copy all of options */
5691 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5692 			if (totallen == ipp->ipp_ipv4_options_len) {
5693 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5694 				return (0);
5695 			}
5696 			kmem_free(ipp->ipp_ipv4_options,
5697 			    ipp->ipp_ipv4_options_len);
5698 			ipp->ipp_ipv4_options = NULL;
5699 			ipp->ipp_ipv4_options_len = 0;
5700 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5701 		}
5702 		if (totallen == 0)
5703 			return (0);
5704 
5705 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5706 		if (ipp->ipp_ipv4_options == NULL)
5707 			return (ENOMEM);
5708 		ipp->ipp_ipv4_options_len = totallen;
5709 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5710 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5711 		return (0);
5712 	}
5713 
5714 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5715 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5716 		ipp->ipp_label_v4 = NULL;
5717 		ipp->ipp_label_len_v4 = 0;
5718 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5719 	}
5720 
5721 	/*
5722 	 * Search for CIPSO option.
5723 	 * We assume CIPSO is first in options if it is present.
5724 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5725 	 * prior to the CIPSO option.
5726 	 */
5727 	while (totallen != 0) {
5728 		switch (optval = opt[IPOPT_OPTVAL]) {
5729 		case IPOPT_EOL:
5730 			return (0);
5731 		case IPOPT_NOP:
5732 			optlen = 1;
5733 			break;
5734 		default:
5735 			if (totallen <= IPOPT_OLEN)
5736 				return (EINVAL);
5737 			optlen = opt[IPOPT_OLEN];
5738 			if (optlen < 2)
5739 				return (EINVAL);
5740 		}
5741 		if (optlen > totallen)
5742 			return (EINVAL);
5743 
5744 		switch (optval) {
5745 		case IPOPT_COMSEC:
5746 			if (!allocate) {
5747 				ipp->ipp_label_v4 = opt;
5748 				ipp->ipp_label_len_v4 = optlen;
5749 				ipp->ipp_fields |= IPPF_LABEL_V4;
5750 			} else {
5751 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5752 				    KM_NOSLEEP);
5753 				if (ipp->ipp_label_v4 == NULL)
5754 					return (ENOMEM);
5755 				ipp->ipp_label_len_v4 = optlen;
5756 				ipp->ipp_fields |= IPPF_LABEL_V4;
5757 				bcopy(opt, ipp->ipp_label_v4, optlen);
5758 			}
5759 			totallen -= optlen;
5760 			opt += optlen;
5761 
5762 			/* Skip padding bytes until we get to a multiple of 4 */
5763 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5764 				totallen--;
5765 				opt++;
5766 			}
5767 			/* Remaining as ipp_ipv4_options */
5768 			goto copyall;
5769 		}
5770 		totallen -= optlen;
5771 		opt += optlen;
5772 	}
5773 	/* No CIPSO found; return everything as ipp_ipv4_options */
5774 	totallen = ipha->ipha_version_and_hdr_length -
5775 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5776 	totallen <<= 2;
5777 	opt = (uchar_t *)&ipha[1];
5778 	goto copyall;
5779 }
5780 
5781 /*
5782  * Efficient versions of lookup for an IRE when we only
5783  * match the address.
5784  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5785  * Does not handle multicast addresses.
5786  */
5787 uint_t
5788 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5789 {
5790 	ire_t *ire;
5791 	uint_t result;
5792 
5793 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5794 	ASSERT(ire != NULL);
5795 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5796 		result = IRE_NOROUTE;
5797 	else
5798 		result = ire->ire_type;
5799 	ire_refrele(ire);
5800 	return (result);
5801 }
5802 
5803 /*
5804  * Efficient versions of lookup for an IRE when we only
5805  * match the address.
5806  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5807  * Does not handle multicast addresses.
5808  */
5809 uint_t
5810 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5811 {
5812 	ire_t *ire;
5813 	uint_t result;
5814 
5815 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5816 	ASSERT(ire != NULL);
5817 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5818 		result = IRE_NOROUTE;
5819 	else
5820 		result = ire->ire_type;
5821 	ire_refrele(ire);
5822 	return (result);
5823 }
5824 
5825 /*
5826  * Nobody should be sending
5827  * packets up this stream
5828  */
5829 static void
5830 ip_lrput(queue_t *q, mblk_t *mp)
5831 {
5832 	switch (mp->b_datap->db_type) {
5833 	case M_FLUSH:
5834 		/* Turn around */
5835 		if (*mp->b_rptr & FLUSHW) {
5836 			*mp->b_rptr &= ~FLUSHR;
5837 			qreply(q, mp);
5838 			return;
5839 		}
5840 		break;
5841 	}
5842 	freemsg(mp);
5843 }
5844 
5845 /* Nobody should be sending packets down this stream */
5846 /* ARGSUSED */
5847 void
5848 ip_lwput(queue_t *q, mblk_t *mp)
5849 {
5850 	freemsg(mp);
5851 }
5852 
5853 /*
5854  * Move the first hop in any source route to ipha_dst and remove that part of
5855  * the source route.  Called by other protocols.  Errors in option formatting
5856  * are ignored - will be handled by ip_output_options. Return the final
5857  * destination (either ipha_dst or the last entry in a source route.)
5858  */
5859 ipaddr_t
5860 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5861 {
5862 	ipoptp_t	opts;
5863 	uchar_t		*opt;
5864 	uint8_t		optval;
5865 	uint8_t		optlen;
5866 	ipaddr_t	dst;
5867 	int		i;
5868 	ip_stack_t	*ipst = ns->netstack_ip;
5869 
5870 	ip2dbg(("ip_massage_options\n"));
5871 	dst = ipha->ipha_dst;
5872 	for (optval = ipoptp_first(&opts, ipha);
5873 	    optval != IPOPT_EOL;
5874 	    optval = ipoptp_next(&opts)) {
5875 		opt = opts.ipoptp_cur;
5876 		switch (optval) {
5877 			uint8_t off;
5878 		case IPOPT_SSRR:
5879 		case IPOPT_LSRR:
5880 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5881 				ip1dbg(("ip_massage_options: bad src route\n"));
5882 				break;
5883 			}
5884 			optlen = opts.ipoptp_len;
5885 			off = opt[IPOPT_OFFSET];
5886 			off--;
5887 		redo_srr:
5888 			if (optlen < IP_ADDR_LEN ||
5889 			    off > optlen - IP_ADDR_LEN) {
5890 				/* End of source route */
5891 				ip1dbg(("ip_massage_options: end of SR\n"));
5892 				break;
5893 			}
5894 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5895 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5896 			    ntohl(dst)));
5897 			/*
5898 			 * Check if our address is present more than
5899 			 * once as consecutive hops in source route.
5900 			 * XXX verify per-interface ip_forwarding
5901 			 * for source route?
5902 			 */
5903 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5904 				off += IP_ADDR_LEN;
5905 				goto redo_srr;
5906 			}
5907 			if (dst == htonl(INADDR_LOOPBACK)) {
5908 				ip1dbg(("ip_massage_options: loopback addr in "
5909 				    "source route!\n"));
5910 				break;
5911 			}
5912 			/*
5913 			 * Update ipha_dst to be the first hop and remove the
5914 			 * first hop from the source route (by overwriting
5915 			 * part of the option with NOP options).
5916 			 */
5917 			ipha->ipha_dst = dst;
5918 			/* Put the last entry in dst */
5919 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5920 			    3;
5921 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5922 
5923 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5924 			    ntohl(dst)));
5925 			/* Move down and overwrite */
5926 			opt[IP_ADDR_LEN] = opt[0];
5927 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5928 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5929 			for (i = 0; i < IP_ADDR_LEN; i++)
5930 				opt[i] = IPOPT_NOP;
5931 			break;
5932 		}
5933 	}
5934 	return (dst);
5935 }
5936 
5937 /*
5938  * Return the network mask
5939  * associated with the specified address.
5940  */
5941 ipaddr_t
5942 ip_net_mask(ipaddr_t addr)
5943 {
5944 	uchar_t	*up = (uchar_t *)&addr;
5945 	ipaddr_t mask = 0;
5946 	uchar_t	*maskp = (uchar_t *)&mask;
5947 
5948 #if defined(__i386) || defined(__amd64)
5949 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5950 #endif
5951 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5952 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5953 #endif
5954 	if (CLASSD(addr)) {
5955 		maskp[0] = 0xF0;
5956 		return (mask);
5957 	}
5958 
5959 	/* We assume Class E default netmask to be 32 */
5960 	if (CLASSE(addr))
5961 		return (0xffffffffU);
5962 
5963 	if (addr == 0)
5964 		return (0);
5965 	maskp[0] = 0xFF;
5966 	if ((up[0] & 0x80) == 0)
5967 		return (mask);
5968 
5969 	maskp[1] = 0xFF;
5970 	if ((up[0] & 0xC0) == 0x80)
5971 		return (mask);
5972 
5973 	maskp[2] = 0xFF;
5974 	if ((up[0] & 0xE0) == 0xC0)
5975 		return (mask);
5976 
5977 	/* Otherwise return no mask */
5978 	return ((ipaddr_t)0);
5979 }
5980 
5981 /* Name/Value Table Lookup Routine */
5982 char *
5983 ip_nv_lookup(nv_t *nv, int value)
5984 {
5985 	if (!nv)
5986 		return (NULL);
5987 	for (; nv->nv_name; nv++) {
5988 		if (nv->nv_value == value)
5989 			return (nv->nv_name);
5990 	}
5991 	return ("unknown");
5992 }
5993 
5994 static int
5995 ip_wait_for_info_ack(ill_t *ill)
5996 {
5997 	int err;
5998 
5999 	mutex_enter(&ill->ill_lock);
6000 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
6001 		/*
6002 		 * Return value of 0 indicates a pending signal.
6003 		 */
6004 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
6005 		if (err == 0) {
6006 			mutex_exit(&ill->ill_lock);
6007 			return (EINTR);
6008 		}
6009 	}
6010 	mutex_exit(&ill->ill_lock);
6011 	/*
6012 	 * ip_rput_other could have set an error  in ill_error on
6013 	 * receipt of M_ERROR.
6014 	 */
6015 	return (ill->ill_error);
6016 }
6017 
6018 /*
6019  * This is a module open, i.e. this is a control stream for access
6020  * to a DLPI device.  We allocate an ill_t as the instance data in
6021  * this case.
6022  */
6023 static int
6024 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
6025 {
6026 	ill_t	*ill;
6027 	int	err;
6028 	zoneid_t zoneid;
6029 	netstack_t *ns;
6030 	ip_stack_t *ipst;
6031 
6032 	/*
6033 	 * Prevent unprivileged processes from pushing IP so that
6034 	 * they can't send raw IP.
6035 	 */
6036 	if (secpolicy_net_rawaccess(credp) != 0)
6037 		return (EPERM);
6038 
6039 	ns = netstack_find_by_cred(credp);
6040 	ASSERT(ns != NULL);
6041 	ipst = ns->netstack_ip;
6042 	ASSERT(ipst != NULL);
6043 
6044 	/*
6045 	 * For exclusive stacks we set the zoneid to zero
6046 	 * to make IP operate as if in the global zone.
6047 	 */
6048 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
6049 		zoneid = GLOBAL_ZONEID;
6050 	else
6051 		zoneid = crgetzoneid(credp);
6052 
6053 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
6054 	q->q_ptr = WR(q)->q_ptr = ill;
6055 	ill->ill_ipst = ipst;
6056 	ill->ill_zoneid = zoneid;
6057 
6058 	/*
6059 	 * ill_init initializes the ill fields and then sends down
6060 	 * down a DL_INFO_REQ after calling qprocson.
6061 	 */
6062 	err = ill_init(q, ill);
6063 
6064 	if (err != 0) {
6065 		mi_free(ill);
6066 		netstack_rele(ipst->ips_netstack);
6067 		q->q_ptr = NULL;
6068 		WR(q)->q_ptr = NULL;
6069 		return (err);
6070 	}
6071 
6072 	/*
6073 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
6074 	 *
6075 	 * ill_init initializes the ipsq marking this thread as
6076 	 * writer
6077 	 */
6078 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
6079 	err = ip_wait_for_info_ack(ill);
6080 	if (err == 0)
6081 		ill->ill_credp = credp;
6082 	else
6083 		goto fail;
6084 
6085 	crhold(credp);
6086 
6087 	mutex_enter(&ipst->ips_ip_mi_lock);
6088 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
6089 	    sflag, credp);
6090 	mutex_exit(&ipst->ips_ip_mi_lock);
6091 fail:
6092 	if (err) {
6093 		(void) ip_close(q, 0);
6094 		return (err);
6095 	}
6096 	return (0);
6097 }
6098 
6099 /* For /dev/ip aka AF_INET open */
6100 int
6101 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
6102 {
6103 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
6104 }
6105 
6106 /* For /dev/ip6 aka AF_INET6 open */
6107 int
6108 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
6109 {
6110 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
6111 }
6112 
6113 /* IP open routine. */
6114 int
6115 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
6116     boolean_t isv6)
6117 {
6118 	conn_t 		*connp;
6119 	major_t		maj;
6120 	zoneid_t	zoneid;
6121 	netstack_t	*ns;
6122 	ip_stack_t	*ipst;
6123 
6124 	/* Allow reopen. */
6125 	if (q->q_ptr != NULL)
6126 		return (0);
6127 
6128 	if (sflag & MODOPEN) {
6129 		/* This is a module open */
6130 		return (ip_modopen(q, devp, flag, sflag, credp));
6131 	}
6132 
6133 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
6134 		/*
6135 		 * Non streams based socket looking for a stream
6136 		 * to access IP
6137 		 */
6138 		return (ip_helper_stream_setup(q, devp, flag, sflag,
6139 		    credp, isv6));
6140 	}
6141 
6142 	ns = netstack_find_by_cred(credp);
6143 	ASSERT(ns != NULL);
6144 	ipst = ns->netstack_ip;
6145 	ASSERT(ipst != NULL);
6146 
6147 	/*
6148 	 * For exclusive stacks we set the zoneid to zero
6149 	 * to make IP operate as if in the global zone.
6150 	 */
6151 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
6152 		zoneid = GLOBAL_ZONEID;
6153 	else
6154 		zoneid = crgetzoneid(credp);
6155 
6156 	/*
6157 	 * We are opening as a device. This is an IP client stream, and we
6158 	 * allocate an conn_t as the instance data.
6159 	 */
6160 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
6161 
6162 	/*
6163 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
6164 	 * done by netstack_find_by_cred()
6165 	 */
6166 	netstack_rele(ipst->ips_netstack);
6167 
6168 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
6169 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
6170 	connp->conn_ixa->ixa_zoneid = zoneid;
6171 	connp->conn_zoneid = zoneid;
6172 
6173 	connp->conn_rq = q;
6174 	q->q_ptr = WR(q)->q_ptr = connp;
6175 
6176 	/* Minor tells us which /dev entry was opened */
6177 	if (isv6) {
6178 		connp->conn_family = AF_INET6;
6179 		connp->conn_ipversion = IPV6_VERSION;
6180 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
6181 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
6182 	} else {
6183 		connp->conn_family = AF_INET;
6184 		connp->conn_ipversion = IPV4_VERSION;
6185 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
6186 	}
6187 
6188 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
6189 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
6190 		connp->conn_minor_arena = ip_minor_arena_la;
6191 	} else {
6192 		/*
6193 		 * Either minor numbers in the large arena were exhausted
6194 		 * or a non socket application is doing the open.
6195 		 * Try to allocate from the small arena.
6196 		 */
6197 		if ((connp->conn_dev =
6198 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
6199 			/* CONN_DEC_REF takes care of netstack_rele() */
6200 			q->q_ptr = WR(q)->q_ptr = NULL;
6201 			CONN_DEC_REF(connp);
6202 			return (EBUSY);
6203 		}
6204 		connp->conn_minor_arena = ip_minor_arena_sa;
6205 	}
6206 
6207 	maj = getemajor(*devp);
6208 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
6209 
6210 	/*
6211 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
6212 	 */
6213 	connp->conn_cred = credp;
6214 	connp->conn_cpid = curproc->p_pid;
6215 	/* Cache things in ixa without an extra refhold */
6216 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
6217 	connp->conn_ixa->ixa_cred = connp->conn_cred;
6218 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6219 	if (is_system_labeled())
6220 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6221 
6222 	/*
6223 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6224 	 */
6225 	connp->conn_recv = ip_conn_input;
6226 	connp->conn_recvicmp = ip_conn_input_icmp;
6227 
6228 	crhold(connp->conn_cred);
6229 
6230 	/*
6231 	 * If the caller has the process-wide flag set, then default to MAC
6232 	 * exempt mode.  This allows read-down to unlabeled hosts.
6233 	 */
6234 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6235 		connp->conn_mac_mode = CONN_MAC_AWARE;
6236 
6237 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6238 
6239 	connp->conn_rq = q;
6240 	connp->conn_wq = WR(q);
6241 
6242 	/* Non-zero default values */
6243 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6244 
6245 	/*
6246 	 * Make the conn globally visible to walkers
6247 	 */
6248 	ASSERT(connp->conn_ref == 1);
6249 	mutex_enter(&connp->conn_lock);
6250 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6251 	mutex_exit(&connp->conn_lock);
6252 
6253 	qprocson(q);
6254 
6255 	return (0);
6256 }
6257 
6258 /*
6259  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6260  * all of them are copied to the conn_t. If the req is "zero", the policy is
6261  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6262  * fields.
6263  * We keep only the latest setting of the policy and thus policy setting
6264  * is not incremental/cumulative.
6265  *
6266  * Requests to set policies with multiple alternative actions will
6267  * go through a different API.
6268  */
6269 int
6270 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6271 {
6272 	uint_t ah_req = 0;
6273 	uint_t esp_req = 0;
6274 	uint_t se_req = 0;
6275 	ipsec_act_t *actp = NULL;
6276 	uint_t nact;
6277 	ipsec_policy_head_t *ph;
6278 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6279 	int error = 0;
6280 	netstack_t	*ns = connp->conn_netstack;
6281 	ip_stack_t	*ipst = ns->netstack_ip;
6282 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6283 
6284 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6285 
6286 	/*
6287 	 * The IP_SEC_OPT option does not allow variable length parameters,
6288 	 * hence a request cannot be NULL.
6289 	 */
6290 	if (req == NULL)
6291 		return (EINVAL);
6292 
6293 	ah_req = req->ipsr_ah_req;
6294 	esp_req = req->ipsr_esp_req;
6295 	se_req = req->ipsr_self_encap_req;
6296 
6297 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6298 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6299 		return (EINVAL);
6300 
6301 	/*
6302 	 * Are we dealing with a request to reset the policy (i.e.
6303 	 * zero requests).
6304 	 */
6305 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6306 	    (esp_req & REQ_MASK) == 0 &&
6307 	    (se_req & REQ_MASK) == 0);
6308 
6309 	if (!is_pol_reset) {
6310 		/*
6311 		 * If we couldn't load IPsec, fail with "protocol
6312 		 * not supported".
6313 		 * IPsec may not have been loaded for a request with zero
6314 		 * policies, so we don't fail in this case.
6315 		 */
6316 		mutex_enter(&ipss->ipsec_loader_lock);
6317 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6318 			mutex_exit(&ipss->ipsec_loader_lock);
6319 			return (EPROTONOSUPPORT);
6320 		}
6321 		mutex_exit(&ipss->ipsec_loader_lock);
6322 
6323 		/*
6324 		 * Test for valid requests. Invalid algorithms
6325 		 * need to be tested by IPsec code because new
6326 		 * algorithms can be added dynamically.
6327 		 */
6328 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6329 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6330 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6331 			return (EINVAL);
6332 		}
6333 
6334 		/*
6335 		 * Only privileged users can issue these
6336 		 * requests.
6337 		 */
6338 		if (((ah_req & IPSEC_PREF_NEVER) ||
6339 		    (esp_req & IPSEC_PREF_NEVER) ||
6340 		    (se_req & IPSEC_PREF_NEVER)) &&
6341 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6342 			return (EPERM);
6343 		}
6344 
6345 		/*
6346 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6347 		 * are mutually exclusive.
6348 		 */
6349 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6350 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6351 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6352 			/* Both of them are set */
6353 			return (EINVAL);
6354 		}
6355 	}
6356 
6357 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6358 
6359 	/*
6360 	 * If we have already cached policies in conn_connect(), don't
6361 	 * let them change now. We cache policies for connections
6362 	 * whose src,dst [addr, port] is known.
6363 	 */
6364 	if (connp->conn_policy_cached) {
6365 		return (EINVAL);
6366 	}
6367 
6368 	/*
6369 	 * We have a zero policies, reset the connection policy if already
6370 	 * set. This will cause the connection to inherit the
6371 	 * global policy, if any.
6372 	 */
6373 	if (is_pol_reset) {
6374 		if (connp->conn_policy != NULL) {
6375 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6376 			connp->conn_policy = NULL;
6377 		}
6378 		connp->conn_in_enforce_policy = B_FALSE;
6379 		connp->conn_out_enforce_policy = B_FALSE;
6380 		return (0);
6381 	}
6382 
6383 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6384 	    ipst->ips_netstack);
6385 	if (ph == NULL)
6386 		goto enomem;
6387 
6388 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6389 	if (actp == NULL)
6390 		goto enomem;
6391 
6392 	/*
6393 	 * Always insert IPv4 policy entries, since they can also apply to
6394 	 * ipv6 sockets being used in ipv4-compat mode.
6395 	 */
6396 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6397 	    IPSEC_TYPE_INBOUND, ns))
6398 		goto enomem;
6399 	is_pol_inserted = B_TRUE;
6400 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6401 	    IPSEC_TYPE_OUTBOUND, ns))
6402 		goto enomem;
6403 
6404 	/*
6405 	 * We're looking at a v6 socket, also insert the v6-specific
6406 	 * entries.
6407 	 */
6408 	if (connp->conn_family == AF_INET6) {
6409 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6410 		    IPSEC_TYPE_INBOUND, ns))
6411 			goto enomem;
6412 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6413 		    IPSEC_TYPE_OUTBOUND, ns))
6414 			goto enomem;
6415 	}
6416 
6417 	ipsec_actvec_free(actp, nact);
6418 
6419 	/*
6420 	 * If the requests need security, set enforce_policy.
6421 	 * If the requests are IPSEC_PREF_NEVER, one should
6422 	 * still set conn_out_enforce_policy so that ip_set_destination
6423 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6424 	 * for connections that we don't cache policy in at connect time,
6425 	 * if global policy matches in ip_output_attach_policy, we
6426 	 * don't wrongly inherit global policy. Similarly, we need
6427 	 * to set conn_in_enforce_policy also so that we don't verify
6428 	 * policy wrongly.
6429 	 */
6430 	if ((ah_req & REQ_MASK) != 0 ||
6431 	    (esp_req & REQ_MASK) != 0 ||
6432 	    (se_req & REQ_MASK) != 0) {
6433 		connp->conn_in_enforce_policy = B_TRUE;
6434 		connp->conn_out_enforce_policy = B_TRUE;
6435 	}
6436 
6437 	return (error);
6438 #undef REQ_MASK
6439 
6440 	/*
6441 	 * Common memory-allocation-failure exit path.
6442 	 */
6443 enomem:
6444 	if (actp != NULL)
6445 		ipsec_actvec_free(actp, nact);
6446 	if (is_pol_inserted)
6447 		ipsec_polhead_flush(ph, ns);
6448 	return (ENOMEM);
6449 }
6450 
6451 /*
6452  * Set socket options for joining and leaving multicast groups.
6453  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6454  * The caller has already check that the option name is consistent with
6455  * the address family of the socket.
6456  */
6457 int
6458 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6459     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6460 {
6461 	int		*i1 = (int *)invalp;
6462 	int		error = 0;
6463 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6464 	struct ip_mreq	*v4_mreqp;
6465 	struct ipv6_mreq *v6_mreqp;
6466 	struct group_req *greqp;
6467 	ire_t *ire;
6468 	boolean_t done = B_FALSE;
6469 	ipaddr_t ifaddr;
6470 	in6_addr_t v6group;
6471 	uint_t ifindex;
6472 	boolean_t mcast_opt = B_TRUE;
6473 	mcast_record_t fmode;
6474 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6475 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6476 
6477 	switch (name) {
6478 	case IP_ADD_MEMBERSHIP:
6479 	case IPV6_JOIN_GROUP:
6480 		mcast_opt = B_FALSE;
6481 		/* FALLTHRU */
6482 	case MCAST_JOIN_GROUP:
6483 		fmode = MODE_IS_EXCLUDE;
6484 		optfn = ip_opt_add_group;
6485 		break;
6486 
6487 	case IP_DROP_MEMBERSHIP:
6488 	case IPV6_LEAVE_GROUP:
6489 		mcast_opt = B_FALSE;
6490 		/* FALLTHRU */
6491 	case MCAST_LEAVE_GROUP:
6492 		fmode = MODE_IS_INCLUDE;
6493 		optfn = ip_opt_delete_group;
6494 		break;
6495 	default:
6496 		ASSERT(0);
6497 	}
6498 
6499 	if (mcast_opt) {
6500 		struct sockaddr_in *sin;
6501 		struct sockaddr_in6 *sin6;
6502 
6503 		greqp = (struct group_req *)i1;
6504 		if (greqp->gr_group.ss_family == AF_INET) {
6505 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6506 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6507 		} else {
6508 			if (!inet6)
6509 				return (EINVAL);	/* Not on INET socket */
6510 
6511 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6512 			v6group = sin6->sin6_addr;
6513 		}
6514 		ifaddr = INADDR_ANY;
6515 		ifindex = greqp->gr_interface;
6516 	} else if (inet6) {
6517 		v6_mreqp = (struct ipv6_mreq *)i1;
6518 		v6group = v6_mreqp->ipv6mr_multiaddr;
6519 		ifaddr = INADDR_ANY;
6520 		ifindex = v6_mreqp->ipv6mr_interface;
6521 	} else {
6522 		v4_mreqp = (struct ip_mreq *)i1;
6523 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6524 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6525 		ifindex = 0;
6526 	}
6527 
6528 	/*
6529 	 * In the multirouting case, we need to replicate
6530 	 * the request on all interfaces that will take part
6531 	 * in replication.  We do so because multirouting is
6532 	 * reflective, thus we will probably receive multi-
6533 	 * casts on those interfaces.
6534 	 * The ip_multirt_apply_membership() succeeds if
6535 	 * the operation succeeds on at least one interface.
6536 	 */
6537 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6538 		ipaddr_t group;
6539 
6540 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6541 
6542 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6543 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6544 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6545 	} else {
6546 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6547 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6548 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6549 	}
6550 	if (ire != NULL) {
6551 		if (ire->ire_flags & RTF_MULTIRT) {
6552 			error = ip_multirt_apply_membership(optfn, ire, connp,
6553 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6554 			done = B_TRUE;
6555 		}
6556 		ire_refrele(ire);
6557 	}
6558 
6559 	if (!done) {
6560 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6561 		    fmode, &ipv6_all_zeros);
6562 	}
6563 	return (error);
6564 }
6565 
6566 /*
6567  * Set socket options for joining and leaving multicast groups
6568  * for specific sources.
6569  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6570  * The caller has already check that the option name is consistent with
6571  * the address family of the socket.
6572  */
6573 int
6574 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6575     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6576 {
6577 	int		*i1 = (int *)invalp;
6578 	int		error = 0;
6579 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6580 	struct ip_mreq_source *imreqp;
6581 	struct group_source_req *gsreqp;
6582 	in6_addr_t v6group, v6src;
6583 	uint32_t ifindex;
6584 	ipaddr_t ifaddr;
6585 	boolean_t mcast_opt = B_TRUE;
6586 	mcast_record_t fmode;
6587 	ire_t *ire;
6588 	boolean_t done = B_FALSE;
6589 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6590 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6591 
6592 	switch (name) {
6593 	case IP_BLOCK_SOURCE:
6594 		mcast_opt = B_FALSE;
6595 		/* FALLTHRU */
6596 	case MCAST_BLOCK_SOURCE:
6597 		fmode = MODE_IS_EXCLUDE;
6598 		optfn = ip_opt_add_group;
6599 		break;
6600 
6601 	case IP_UNBLOCK_SOURCE:
6602 		mcast_opt = B_FALSE;
6603 		/* FALLTHRU */
6604 	case MCAST_UNBLOCK_SOURCE:
6605 		fmode = MODE_IS_EXCLUDE;
6606 		optfn = ip_opt_delete_group;
6607 		break;
6608 
6609 	case IP_ADD_SOURCE_MEMBERSHIP:
6610 		mcast_opt = B_FALSE;
6611 		/* FALLTHRU */
6612 	case MCAST_JOIN_SOURCE_GROUP:
6613 		fmode = MODE_IS_INCLUDE;
6614 		optfn = ip_opt_add_group;
6615 		break;
6616 
6617 	case IP_DROP_SOURCE_MEMBERSHIP:
6618 		mcast_opt = B_FALSE;
6619 		/* FALLTHRU */
6620 	case MCAST_LEAVE_SOURCE_GROUP:
6621 		fmode = MODE_IS_INCLUDE;
6622 		optfn = ip_opt_delete_group;
6623 		break;
6624 	default:
6625 		ASSERT(0);
6626 	}
6627 
6628 	if (mcast_opt) {
6629 		gsreqp = (struct group_source_req *)i1;
6630 		ifindex = gsreqp->gsr_interface;
6631 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6632 			struct sockaddr_in *s;
6633 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6634 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6635 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6636 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6637 		} else {
6638 			struct sockaddr_in6 *s6;
6639 
6640 			if (!inet6)
6641 				return (EINVAL);	/* Not on INET socket */
6642 
6643 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6644 			v6group = s6->sin6_addr;
6645 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6646 			v6src = s6->sin6_addr;
6647 		}
6648 		ifaddr = INADDR_ANY;
6649 	} else {
6650 		imreqp = (struct ip_mreq_source *)i1;
6651 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6652 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6653 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6654 		ifindex = 0;
6655 	}
6656 
6657 	/*
6658 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6659 	 */
6660 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6661 		v6src = ipv6_all_zeros;
6662 
6663 	/*
6664 	 * In the multirouting case, we need to replicate
6665 	 * the request as noted in the mcast cases above.
6666 	 */
6667 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6668 		ipaddr_t group;
6669 
6670 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6671 
6672 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6673 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6674 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6675 	} else {
6676 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6677 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6678 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6679 	}
6680 	if (ire != NULL) {
6681 		if (ire->ire_flags & RTF_MULTIRT) {
6682 			error = ip_multirt_apply_membership(optfn, ire, connp,
6683 			    checkonly, &v6group, fmode, &v6src);
6684 			done = B_TRUE;
6685 		}
6686 		ire_refrele(ire);
6687 	}
6688 	if (!done) {
6689 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6690 		    fmode, &v6src);
6691 	}
6692 	return (error);
6693 }
6694 
6695 /*
6696  * Given a destination address and a pointer to where to put the information
6697  * this routine fills in the mtuinfo.
6698  * The socket must be connected.
6699  * For sctp conn_faddr is the primary address.
6700  */
6701 int
6702 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6703 {
6704 	uint32_t	pmtu = IP_MAXPACKET;
6705 	uint_t		scopeid;
6706 
6707 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6708 		return (-1);
6709 
6710 	/* In case we never sent or called ip_set_destination_v4/v6 */
6711 	if (ixa->ixa_ire != NULL)
6712 		pmtu = ip_get_pmtu(ixa);
6713 
6714 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6715 		scopeid = ixa->ixa_scopeid;
6716 	else
6717 		scopeid = 0;
6718 
6719 	bzero(mtuinfo, sizeof (*mtuinfo));
6720 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6721 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6722 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6723 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6724 	mtuinfo->ip6m_mtu = pmtu;
6725 
6726 	return (sizeof (struct ip6_mtuinfo));
6727 }
6728 
6729 /* Named Dispatch routine to get a current value out of our parameter table. */
6730 /* ARGSUSED */
6731 static int
6732 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
6733 {
6734 	ipparam_t *ippa = (ipparam_t *)cp;
6735 
6736 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
6737 	return (0);
6738 }
6739 
6740 /* ARGSUSED */
6741 static int
6742 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
6743 {
6744 
6745 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
6746 	return (0);
6747 }
6748 
6749 /*
6750  * Set ip{,6}_forwarding values.  This means walking through all of the
6751  * ill's and toggling their forwarding values.
6752  */
6753 /* ARGSUSED */
6754 static int
6755 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
6756 {
6757 	long new_value;
6758 	int *forwarding_value = (int *)cp;
6759 	ill_t *ill;
6760 	boolean_t isv6;
6761 	ill_walk_context_t ctx;
6762 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
6763 
6764 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
6765 
6766 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6767 	    new_value < 0 || new_value > 1) {
6768 		return (EINVAL);
6769 	}
6770 
6771 	*forwarding_value = new_value;
6772 
6773 	/*
6774 	 * Regardless of the current value of ip_forwarding, set all per-ill
6775 	 * values of ip_forwarding to the value being set.
6776 	 *
6777 	 * Bring all the ill's up to date with the new global value.
6778 	 */
6779 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
6780 
6781 	if (isv6)
6782 		ill = ILL_START_WALK_V6(&ctx, ipst);
6783 	else
6784 		ill = ILL_START_WALK_V4(&ctx, ipst);
6785 
6786 	for (; ill != NULL; ill = ill_next(&ctx, ill))
6787 		(void) ill_forward_set(ill, new_value != 0);
6788 
6789 	rw_exit(&ipst->ips_ill_g_lock);
6790 	return (0);
6791 }
6792 
6793 /*
6794  * Walk through the param array specified registering each element with the
6795  * Named Dispatch handler. This is called only during init. So it is ok
6796  * not to acquire any locks
6797  */
6798 static boolean_t
6799 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
6800     ipndp_t *ipnd, size_t ipnd_cnt)
6801 {
6802 	for (; ippa_cnt-- > 0; ippa++) {
6803 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
6804 			if (!nd_load(ndp, ippa->ip_param_name,
6805 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
6806 				nd_free(ndp);
6807 				return (B_FALSE);
6808 			}
6809 		}
6810 	}
6811 
6812 	for (; ipnd_cnt-- > 0; ipnd++) {
6813 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
6814 			if (!nd_load(ndp, ipnd->ip_ndp_name,
6815 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
6816 			    ipnd->ip_ndp_data)) {
6817 				nd_free(ndp);
6818 				return (B_FALSE);
6819 			}
6820 		}
6821 	}
6822 
6823 	return (B_TRUE);
6824 }
6825 
6826 /*
6827  * When the src multihoming is changed from weak to [strong, preferred]
6828  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6829  * and identify routes that were created by user-applications in the
6830  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6831  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6832  * is selected by finding an interface route for the gateway.
6833  */
6834 /* ARGSUSED */
6835 static void
6836 ip_ire_rebind_walker(ire_t *ire, void *notused)
6837 {
6838 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6839 		return;
6840 	ire_rebind(ire);
6841 	ire_delete(ire);
6842 }
6843 
6844 /*
6845  * When the src multihoming is changed from  [strong, preferred] to weak,
6846  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6847  * set any entries that were created by user-applications in the unbound state
6848  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6849  */
6850 /* ARGSUSED */
6851 static void
6852 ip_ire_unbind_walker(ire_t *ire, void *notused)
6853 {
6854 	ire_t *new_ire;
6855 
6856 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6857 		return;
6858 	if (ire->ire_ipversion == IPV6_VERSION) {
6859 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6860 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6861 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6862 	} else {
6863 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6864 		    (uchar_t *)&ire->ire_mask,
6865 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6866 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6867 	}
6868 	if (new_ire == NULL)
6869 		return;
6870 	new_ire->ire_unbound = B_TRUE;
6871 	/*
6872 	 * The bound ire must first be deleted so that we don't return
6873 	 * the existing one on the attempt to add the unbound new_ire.
6874 	 */
6875 	ire_delete(ire);
6876 	new_ire = ire_add(new_ire);
6877 	if (new_ire != NULL)
6878 		ire_refrele(new_ire);
6879 }
6880 
6881 /*
6882  * When the settings of ip*_strict_src_multihoming tunables are changed,
6883  * all cached routes need to be recomputed. This recomputation needs to be
6884  * done when going from weaker to stronger modes so that the cached ire
6885  * for the connection does not violate the current ip*_strict_src_multihoming
6886  * setting. It also needs to be done when going from stronger to weaker modes,
6887  * so that we fall back to matching on the longest-matching-route (as opposed
6888  * to a shorter match that may have been selected in the strong mode
6889  * to satisfy src_multihoming settings).
6890  *
6891  * The cached ixa_ire entires for all conn_t entries are marked as
6892  * "verify" so that they will be recomputed for the next packet.
6893  */
6894 static void
6895 conn_ire_revalidate(conn_t *connp, void *arg)
6896 {
6897 	boolean_t isv6 = (boolean_t)arg;
6898 
6899 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6900 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6901 		return;
6902 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6903 }
6904 
6905 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
6906 /* ARGSUSED */
6907 static int
6908 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
6909 {
6910 	long		new_value;
6911 	ipparam_t	*ippa = (ipparam_t *)cp;
6912 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
6913 	int		strict_src4, strict_src6;
6914 
6915 	strict_src4 = ipst->ips_ip_strict_src_multihoming;
6916 	strict_src6 = ipst->ips_ipv6_strict_src_multihoming;
6917 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6918 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
6919 		return (EINVAL);
6920 	}
6921 	ippa->ip_param_value = new_value;
6922 	if (ipst->ips_ip_strict_src_multihoming != strict_src4) {
6923 		if (strict_src4 == 0) {
6924 			ire_walk_v4(ip_ire_rebind_walker, NULL, ALL_ZONES,
6925 			    ipst);
6926 		} else {
6927 			ire_walk_v4(ip_ire_unbind_walker, NULL, ALL_ZONES,
6928 			    ipst);
6929 		}
6930 		ipcl_walk(conn_ire_revalidate, (void *)B_FALSE, ipst);
6931 	} else if (ipst->ips_ipv6_strict_src_multihoming != strict_src6) {
6932 		if (strict_src6 == 0) {
6933 			ire_walk_v6(ip_ire_rebind_walker, NULL, ALL_ZONES,
6934 			    ipst);
6935 		} else {
6936 			ire_walk_v4(ip_ire_unbind_walker, NULL, ALL_ZONES,
6937 			    ipst);
6938 		}
6939 		ipcl_walk(conn_ire_revalidate, (void *)B_TRUE, ipst);
6940 	}
6941 	return (0);
6942 }
6943 
6944 /*
6945  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6946  * When an ipf is passed here for the first time, if
6947  * we already have in-order fragments on the queue, we convert from the fast-
6948  * path reassembly scheme to the hard-case scheme.  From then on, additional
6949  * fragments are reassembled here.  We keep track of the start and end offsets
6950  * of each piece, and the number of holes in the chain.  When the hole count
6951  * goes to zero, we are done!
6952  *
6953  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6954  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6955  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6956  * after the call to ip_reassemble().
6957  */
6958 int
6959 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6960     size_t msg_len)
6961 {
6962 	uint_t	end;
6963 	mblk_t	*next_mp;
6964 	mblk_t	*mp1;
6965 	uint_t	offset;
6966 	boolean_t incr_dups = B_TRUE;
6967 	boolean_t offset_zero_seen = B_FALSE;
6968 	boolean_t pkt_boundary_checked = B_FALSE;
6969 
6970 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6971 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6972 
6973 	/* Add in byte count */
6974 	ipf->ipf_count += msg_len;
6975 	if (ipf->ipf_end) {
6976 		/*
6977 		 * We were part way through in-order reassembly, but now there
6978 		 * is a hole.  We walk through messages already queued, and
6979 		 * mark them for hard case reassembly.  We know that up till
6980 		 * now they were in order starting from offset zero.
6981 		 */
6982 		offset = 0;
6983 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6984 			IP_REASS_SET_START(mp1, offset);
6985 			if (offset == 0) {
6986 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6987 				offset = -ipf->ipf_nf_hdr_len;
6988 			}
6989 			offset += mp1->b_wptr - mp1->b_rptr;
6990 			IP_REASS_SET_END(mp1, offset);
6991 		}
6992 		/* One hole at the end. */
6993 		ipf->ipf_hole_cnt = 1;
6994 		/* Brand it as a hard case, forever. */
6995 		ipf->ipf_end = 0;
6996 	}
6997 	/* Walk through all the new pieces. */
6998 	do {
6999 		end = start + (mp->b_wptr - mp->b_rptr);
7000 		/*
7001 		 * If start is 0, decrease 'end' only for the first mblk of
7002 		 * the fragment. Otherwise 'end' can get wrong value in the
7003 		 * second pass of the loop if first mblk is exactly the
7004 		 * size of ipf_nf_hdr_len.
7005 		 */
7006 		if (start == 0 && !offset_zero_seen) {
7007 			/* First segment */
7008 			ASSERT(ipf->ipf_nf_hdr_len != 0);
7009 			end -= ipf->ipf_nf_hdr_len;
7010 			offset_zero_seen = B_TRUE;
7011 		}
7012 		next_mp = mp->b_cont;
7013 		/*
7014 		 * We are checking to see if there is any interesing data
7015 		 * to process.  If there isn't and the mblk isn't the
7016 		 * one which carries the unfragmentable header then we
7017 		 * drop it.  It's possible to have just the unfragmentable
7018 		 * header come through without any data.  That needs to be
7019 		 * saved.
7020 		 *
7021 		 * If the assert at the top of this function holds then the
7022 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
7023 		 * is infrequently traveled enough that the test is left in
7024 		 * to protect against future code changes which break that
7025 		 * invariant.
7026 		 */
7027 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
7028 			/* Empty.  Blast it. */
7029 			IP_REASS_SET_START(mp, 0);
7030 			IP_REASS_SET_END(mp, 0);
7031 			/*
7032 			 * If the ipf points to the mblk we are about to free,
7033 			 * update ipf to point to the next mblk (or NULL
7034 			 * if none).
7035 			 */
7036 			if (ipf->ipf_mp->b_cont == mp)
7037 				ipf->ipf_mp->b_cont = next_mp;
7038 			freeb(mp);
7039 			continue;
7040 		}
7041 		mp->b_cont = NULL;
7042 		IP_REASS_SET_START(mp, start);
7043 		IP_REASS_SET_END(mp, end);
7044 		if (!ipf->ipf_tail_mp) {
7045 			ipf->ipf_tail_mp = mp;
7046 			ipf->ipf_mp->b_cont = mp;
7047 			if (start == 0 || !more) {
7048 				ipf->ipf_hole_cnt = 1;
7049 				/*
7050 				 * if the first fragment comes in more than one
7051 				 * mblk, this loop will be executed for each
7052 				 * mblk. Need to adjust hole count so exiting
7053 				 * this routine will leave hole count at 1.
7054 				 */
7055 				if (next_mp)
7056 					ipf->ipf_hole_cnt++;
7057 			} else
7058 				ipf->ipf_hole_cnt = 2;
7059 			continue;
7060 		} else if (ipf->ipf_last_frag_seen && !more &&
7061 		    !pkt_boundary_checked) {
7062 			/*
7063 			 * We check datagram boundary only if this fragment
7064 			 * claims to be the last fragment and we have seen a
7065 			 * last fragment in the past too. We do this only
7066 			 * once for a given fragment.
7067 			 *
7068 			 * start cannot be 0 here as fragments with start=0
7069 			 * and MF=0 gets handled as a complete packet. These
7070 			 * fragments should not reach here.
7071 			 */
7072 
7073 			if (start + msgdsize(mp) !=
7074 			    IP_REASS_END(ipf->ipf_tail_mp)) {
7075 				/*
7076 				 * We have two fragments both of which claim
7077 				 * to be the last fragment but gives conflicting
7078 				 * information about the whole datagram size.
7079 				 * Something fishy is going on. Drop the
7080 				 * fragment and free up the reassembly list.
7081 				 */
7082 				return (IP_REASS_FAILED);
7083 			}
7084 
7085 			/*
7086 			 * We shouldn't come to this code block again for this
7087 			 * particular fragment.
7088 			 */
7089 			pkt_boundary_checked = B_TRUE;
7090 		}
7091 
7092 		/* New stuff at or beyond tail? */
7093 		offset = IP_REASS_END(ipf->ipf_tail_mp);
7094 		if (start >= offset) {
7095 			if (ipf->ipf_last_frag_seen) {
7096 				/* current fragment is beyond last fragment */
7097 				return (IP_REASS_FAILED);
7098 			}
7099 			/* Link it on end. */
7100 			ipf->ipf_tail_mp->b_cont = mp;
7101 			ipf->ipf_tail_mp = mp;
7102 			if (more) {
7103 				if (start != offset)
7104 					ipf->ipf_hole_cnt++;
7105 			} else if (start == offset && next_mp == NULL)
7106 					ipf->ipf_hole_cnt--;
7107 			continue;
7108 		}
7109 		mp1 = ipf->ipf_mp->b_cont;
7110 		offset = IP_REASS_START(mp1);
7111 		/* New stuff at the front? */
7112 		if (start < offset) {
7113 			if (start == 0) {
7114 				if (end >= offset) {
7115 					/* Nailed the hole at the begining. */
7116 					ipf->ipf_hole_cnt--;
7117 				}
7118 			} else if (end < offset) {
7119 				/*
7120 				 * A hole, stuff, and a hole where there used
7121 				 * to be just a hole.
7122 				 */
7123 				ipf->ipf_hole_cnt++;
7124 			}
7125 			mp->b_cont = mp1;
7126 			/* Check for overlap. */
7127 			while (end > offset) {
7128 				if (end < IP_REASS_END(mp1)) {
7129 					mp->b_wptr -= end - offset;
7130 					IP_REASS_SET_END(mp, offset);
7131 					BUMP_MIB(ill->ill_ip_mib,
7132 					    ipIfStatsReasmPartDups);
7133 					break;
7134 				}
7135 				/* Did we cover another hole? */
7136 				if ((mp1->b_cont &&
7137 				    IP_REASS_END(mp1) !=
7138 				    IP_REASS_START(mp1->b_cont) &&
7139 				    end >= IP_REASS_START(mp1->b_cont)) ||
7140 				    (!ipf->ipf_last_frag_seen && !more)) {
7141 					ipf->ipf_hole_cnt--;
7142 				}
7143 				/* Clip out mp1. */
7144 				if ((mp->b_cont = mp1->b_cont) == NULL) {
7145 					/*
7146 					 * After clipping out mp1, this guy
7147 					 * is now hanging off the end.
7148 					 */
7149 					ipf->ipf_tail_mp = mp;
7150 				}
7151 				IP_REASS_SET_START(mp1, 0);
7152 				IP_REASS_SET_END(mp1, 0);
7153 				/* Subtract byte count */
7154 				ipf->ipf_count -= mp1->b_datap->db_lim -
7155 				    mp1->b_datap->db_base;
7156 				freeb(mp1);
7157 				BUMP_MIB(ill->ill_ip_mib,
7158 				    ipIfStatsReasmPartDups);
7159 				mp1 = mp->b_cont;
7160 				if (!mp1)
7161 					break;
7162 				offset = IP_REASS_START(mp1);
7163 			}
7164 			ipf->ipf_mp->b_cont = mp;
7165 			continue;
7166 		}
7167 		/*
7168 		 * The new piece starts somewhere between the start of the head
7169 		 * and before the end of the tail.
7170 		 */
7171 		for (; mp1; mp1 = mp1->b_cont) {
7172 			offset = IP_REASS_END(mp1);
7173 			if (start < offset) {
7174 				if (end <= offset) {
7175 					/* Nothing new. */
7176 					IP_REASS_SET_START(mp, 0);
7177 					IP_REASS_SET_END(mp, 0);
7178 					/* Subtract byte count */
7179 					ipf->ipf_count -= mp->b_datap->db_lim -
7180 					    mp->b_datap->db_base;
7181 					if (incr_dups) {
7182 						ipf->ipf_num_dups++;
7183 						incr_dups = B_FALSE;
7184 					}
7185 					freeb(mp);
7186 					BUMP_MIB(ill->ill_ip_mib,
7187 					    ipIfStatsReasmDuplicates);
7188 					break;
7189 				}
7190 				/*
7191 				 * Trim redundant stuff off beginning of new
7192 				 * piece.
7193 				 */
7194 				IP_REASS_SET_START(mp, offset);
7195 				mp->b_rptr += offset - start;
7196 				BUMP_MIB(ill->ill_ip_mib,
7197 				    ipIfStatsReasmPartDups);
7198 				start = offset;
7199 				if (!mp1->b_cont) {
7200 					/*
7201 					 * After trimming, this guy is now
7202 					 * hanging off the end.
7203 					 */
7204 					mp1->b_cont = mp;
7205 					ipf->ipf_tail_mp = mp;
7206 					if (!more) {
7207 						ipf->ipf_hole_cnt--;
7208 					}
7209 					break;
7210 				}
7211 			}
7212 			if (start >= IP_REASS_START(mp1->b_cont))
7213 				continue;
7214 			/* Fill a hole */
7215 			if (start > offset)
7216 				ipf->ipf_hole_cnt++;
7217 			mp->b_cont = mp1->b_cont;
7218 			mp1->b_cont = mp;
7219 			mp1 = mp->b_cont;
7220 			offset = IP_REASS_START(mp1);
7221 			if (end >= offset) {
7222 				ipf->ipf_hole_cnt--;
7223 				/* Check for overlap. */
7224 				while (end > offset) {
7225 					if (end < IP_REASS_END(mp1)) {
7226 						mp->b_wptr -= end - offset;
7227 						IP_REASS_SET_END(mp, offset);
7228 						/*
7229 						 * TODO we might bump
7230 						 * this up twice if there is
7231 						 * overlap at both ends.
7232 						 */
7233 						BUMP_MIB(ill->ill_ip_mib,
7234 						    ipIfStatsReasmPartDups);
7235 						break;
7236 					}
7237 					/* Did we cover another hole? */
7238 					if ((mp1->b_cont &&
7239 					    IP_REASS_END(mp1)
7240 					    != IP_REASS_START(mp1->b_cont) &&
7241 					    end >=
7242 					    IP_REASS_START(mp1->b_cont)) ||
7243 					    (!ipf->ipf_last_frag_seen &&
7244 					    !more)) {
7245 						ipf->ipf_hole_cnt--;
7246 					}
7247 					/* Clip out mp1. */
7248 					if ((mp->b_cont = mp1->b_cont) ==
7249 					    NULL) {
7250 						/*
7251 						 * After clipping out mp1,
7252 						 * this guy is now hanging
7253 						 * off the end.
7254 						 */
7255 						ipf->ipf_tail_mp = mp;
7256 					}
7257 					IP_REASS_SET_START(mp1, 0);
7258 					IP_REASS_SET_END(mp1, 0);
7259 					/* Subtract byte count */
7260 					ipf->ipf_count -=
7261 					    mp1->b_datap->db_lim -
7262 					    mp1->b_datap->db_base;
7263 					freeb(mp1);
7264 					BUMP_MIB(ill->ill_ip_mib,
7265 					    ipIfStatsReasmPartDups);
7266 					mp1 = mp->b_cont;
7267 					if (!mp1)
7268 						break;
7269 					offset = IP_REASS_START(mp1);
7270 				}
7271 			}
7272 			break;
7273 		}
7274 	} while (start = end, mp = next_mp);
7275 
7276 	/* Fragment just processed could be the last one. Remember this fact */
7277 	if (!more)
7278 		ipf->ipf_last_frag_seen = B_TRUE;
7279 
7280 	/* Still got holes? */
7281 	if (ipf->ipf_hole_cnt)
7282 		return (IP_REASS_PARTIAL);
7283 	/* Clean up overloaded fields to avoid upstream disasters. */
7284 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
7285 		IP_REASS_SET_START(mp1, 0);
7286 		IP_REASS_SET_END(mp1, 0);
7287 	}
7288 	return (IP_REASS_COMPLETE);
7289 }
7290 
7291 /*
7292  * Fragmentation reassembly.  Each ILL has a hash table for
7293  * queuing packets undergoing reassembly for all IPIFs
7294  * associated with the ILL.  The hash is based on the packet
7295  * IP ident field.  The ILL frag hash table was allocated
7296  * as a timer block at the time the ILL was created.  Whenever
7297  * there is anything on the reassembly queue, the timer will
7298  * be running.  Returns the reassembled packet if reassembly completes.
7299  */
7300 mblk_t *
7301 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
7302 {
7303 	uint32_t	frag_offset_flags;
7304 	mblk_t		*t_mp;
7305 	ipaddr_t	dst;
7306 	uint8_t		proto = ipha->ipha_protocol;
7307 	uint32_t	sum_val;
7308 	uint16_t	sum_flags;
7309 	ipf_t		*ipf;
7310 	ipf_t		**ipfp;
7311 	ipfb_t		*ipfb;
7312 	uint16_t	ident;
7313 	uint32_t	offset;
7314 	ipaddr_t	src;
7315 	uint_t		hdr_length;
7316 	uint32_t	end;
7317 	mblk_t		*mp1;
7318 	mblk_t		*tail_mp;
7319 	size_t		count;
7320 	size_t		msg_len;
7321 	uint8_t		ecn_info = 0;
7322 	uint32_t	packet_size;
7323 	boolean_t	pruned = B_FALSE;
7324 	ill_t		*ill = ira->ira_ill;
7325 	ip_stack_t	*ipst = ill->ill_ipst;
7326 
7327 	/*
7328 	 * Drop the fragmented as early as possible, if
7329 	 * we don't have resource(s) to re-assemble.
7330 	 */
7331 	if (ipst->ips_ip_reass_queue_bytes == 0) {
7332 		freemsg(mp);
7333 		return (NULL);
7334 	}
7335 
7336 	/* Check for fragmentation offset; return if there's none */
7337 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7338 	    (IPH_MF | IPH_OFFSET)) == 0)
7339 		return (mp);
7340 
7341 	/*
7342 	 * We utilize hardware computed checksum info only for UDP since
7343 	 * IP fragmentation is a normal occurrence for the protocol.  In
7344 	 * addition, checksum offload support for IP fragments carrying
7345 	 * UDP payload is commonly implemented across network adapters.
7346 	 */
7347 	ASSERT(ira->ira_rill != NULL);
7348 	if (proto == IPPROTO_UDP && dohwcksum &&
7349 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7350 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7351 		mblk_t *mp1 = mp->b_cont;
7352 		int32_t len;
7353 
7354 		/* Record checksum information from the packet */
7355 		sum_val = (uint32_t)DB_CKSUM16(mp);
7356 		sum_flags = DB_CKSUMFLAGS(mp);
7357 
7358 		/* IP payload offset from beginning of mblk */
7359 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7360 
7361 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7362 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7363 		    offset >= DB_CKSUMSTART(mp) &&
7364 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7365 			uint32_t adj;
7366 			/*
7367 			 * Partial checksum has been calculated by hardware
7368 			 * and attached to the packet; in addition, any
7369 			 * prepended extraneous data is even byte aligned.
7370 			 * If any such data exists, we adjust the checksum;
7371 			 * this would also handle any postpended data.
7372 			 */
7373 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7374 			    mp, mp1, len, adj);
7375 
7376 			/* One's complement subtract extraneous checksum */
7377 			if (adj >= sum_val)
7378 				sum_val = ~(adj - sum_val) & 0xFFFF;
7379 			else
7380 				sum_val -= adj;
7381 		}
7382 	} else {
7383 		sum_val = 0;
7384 		sum_flags = 0;
7385 	}
7386 
7387 	/* Clear hardware checksumming flag */
7388 	DB_CKSUMFLAGS(mp) = 0;
7389 
7390 	ident = ipha->ipha_ident;
7391 	offset = (frag_offset_flags << 3) & 0xFFFF;
7392 	src = ipha->ipha_src;
7393 	dst = ipha->ipha_dst;
7394 	hdr_length = IPH_HDR_LENGTH(ipha);
7395 	end = ntohs(ipha->ipha_length) - hdr_length;
7396 
7397 	/* If end == 0 then we have a packet with no data, so just free it */
7398 	if (end == 0) {
7399 		freemsg(mp);
7400 		return (NULL);
7401 	}
7402 
7403 	/* Record the ECN field info. */
7404 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7405 	if (offset != 0) {
7406 		/*
7407 		 * If this isn't the first piece, strip the header, and
7408 		 * add the offset to the end value.
7409 		 */
7410 		mp->b_rptr += hdr_length;
7411 		end += offset;
7412 	}
7413 
7414 	/* Handle vnic loopback of fragments */
7415 	if (mp->b_datap->db_ref > 2)
7416 		msg_len = 0;
7417 	else
7418 		msg_len = MBLKSIZE(mp);
7419 
7420 	tail_mp = mp;
7421 	while (tail_mp->b_cont != NULL) {
7422 		tail_mp = tail_mp->b_cont;
7423 		if (tail_mp->b_datap->db_ref <= 2)
7424 			msg_len += MBLKSIZE(tail_mp);
7425 	}
7426 
7427 	/* If the reassembly list for this ILL will get too big, prune it */
7428 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7429 	    ipst->ips_ip_reass_queue_bytes) {
7430 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7431 		    uint_t, ill->ill_frag_count,
7432 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7433 		ill_frag_prune(ill,
7434 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7435 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7436 		pruned = B_TRUE;
7437 	}
7438 
7439 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7440 	mutex_enter(&ipfb->ipfb_lock);
7441 
7442 	ipfp = &ipfb->ipfb_ipf;
7443 	/* Try to find an existing fragment queue for this packet. */
7444 	for (;;) {
7445 		ipf = ipfp[0];
7446 		if (ipf != NULL) {
7447 			/*
7448 			 * It has to match on ident and src/dst address.
7449 			 */
7450 			if (ipf->ipf_ident == ident &&
7451 			    ipf->ipf_src == src &&
7452 			    ipf->ipf_dst == dst &&
7453 			    ipf->ipf_protocol == proto) {
7454 				/*
7455 				 * If we have received too many
7456 				 * duplicate fragments for this packet
7457 				 * free it.
7458 				 */
7459 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7460 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7461 					freemsg(mp);
7462 					mutex_exit(&ipfb->ipfb_lock);
7463 					return (NULL);
7464 				}
7465 				/* Found it. */
7466 				break;
7467 			}
7468 			ipfp = &ipf->ipf_hash_next;
7469 			continue;
7470 		}
7471 
7472 		/*
7473 		 * If we pruned the list, do we want to store this new
7474 		 * fragment?. We apply an optimization here based on the
7475 		 * fact that most fragments will be received in order.
7476 		 * So if the offset of this incoming fragment is zero,
7477 		 * it is the first fragment of a new packet. We will
7478 		 * keep it.  Otherwise drop the fragment, as we have
7479 		 * probably pruned the packet already (since the
7480 		 * packet cannot be found).
7481 		 */
7482 		if (pruned && offset != 0) {
7483 			mutex_exit(&ipfb->ipfb_lock);
7484 			freemsg(mp);
7485 			return (NULL);
7486 		}
7487 
7488 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7489 			/*
7490 			 * Too many fragmented packets in this hash
7491 			 * bucket. Free the oldest.
7492 			 */
7493 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7494 		}
7495 
7496 		/* New guy.  Allocate a frag message. */
7497 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7498 		if (mp1 == NULL) {
7499 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7500 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7501 			freemsg(mp);
7502 reass_done:
7503 			mutex_exit(&ipfb->ipfb_lock);
7504 			return (NULL);
7505 		}
7506 
7507 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7508 		mp1->b_cont = mp;
7509 
7510 		/* Initialize the fragment header. */
7511 		ipf = (ipf_t *)mp1->b_rptr;
7512 		ipf->ipf_mp = mp1;
7513 		ipf->ipf_ptphn = ipfp;
7514 		ipfp[0] = ipf;
7515 		ipf->ipf_hash_next = NULL;
7516 		ipf->ipf_ident = ident;
7517 		ipf->ipf_protocol = proto;
7518 		ipf->ipf_src = src;
7519 		ipf->ipf_dst = dst;
7520 		ipf->ipf_nf_hdr_len = 0;
7521 		/* Record reassembly start time. */
7522 		ipf->ipf_timestamp = gethrestime_sec();
7523 		/* Record ipf generation and account for frag header */
7524 		ipf->ipf_gen = ill->ill_ipf_gen++;
7525 		ipf->ipf_count = MBLKSIZE(mp1);
7526 		ipf->ipf_last_frag_seen = B_FALSE;
7527 		ipf->ipf_ecn = ecn_info;
7528 		ipf->ipf_num_dups = 0;
7529 		ipfb->ipfb_frag_pkts++;
7530 		ipf->ipf_checksum = 0;
7531 		ipf->ipf_checksum_flags = 0;
7532 
7533 		/* Store checksum value in fragment header */
7534 		if (sum_flags != 0) {
7535 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7536 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7537 			ipf->ipf_checksum = sum_val;
7538 			ipf->ipf_checksum_flags = sum_flags;
7539 		}
7540 
7541 		/*
7542 		 * We handle reassembly two ways.  In the easy case,
7543 		 * where all the fragments show up in order, we do
7544 		 * minimal bookkeeping, and just clip new pieces on
7545 		 * the end.  If we ever see a hole, then we go off
7546 		 * to ip_reassemble which has to mark the pieces and
7547 		 * keep track of the number of holes, etc.  Obviously,
7548 		 * the point of having both mechanisms is so we can
7549 		 * handle the easy case as efficiently as possible.
7550 		 */
7551 		if (offset == 0) {
7552 			/* Easy case, in-order reassembly so far. */
7553 			ipf->ipf_count += msg_len;
7554 			ipf->ipf_tail_mp = tail_mp;
7555 			/*
7556 			 * Keep track of next expected offset in
7557 			 * ipf_end.
7558 			 */
7559 			ipf->ipf_end = end;
7560 			ipf->ipf_nf_hdr_len = hdr_length;
7561 		} else {
7562 			/* Hard case, hole at the beginning. */
7563 			ipf->ipf_tail_mp = NULL;
7564 			/*
7565 			 * ipf_end == 0 means that we have given up
7566 			 * on easy reassembly.
7567 			 */
7568 			ipf->ipf_end = 0;
7569 
7570 			/* Forget checksum offload from now on */
7571 			ipf->ipf_checksum_flags = 0;
7572 
7573 			/*
7574 			 * ipf_hole_cnt is set by ip_reassemble.
7575 			 * ipf_count is updated by ip_reassemble.
7576 			 * No need to check for return value here
7577 			 * as we don't expect reassembly to complete
7578 			 * or fail for the first fragment itself.
7579 			 */
7580 			(void) ip_reassemble(mp, ipf,
7581 			    (frag_offset_flags & IPH_OFFSET) << 3,
7582 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7583 		}
7584 		/* Update per ipfb and ill byte counts */
7585 		ipfb->ipfb_count += ipf->ipf_count;
7586 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7587 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7588 		/* If the frag timer wasn't already going, start it. */
7589 		mutex_enter(&ill->ill_lock);
7590 		ill_frag_timer_start(ill);
7591 		mutex_exit(&ill->ill_lock);
7592 		goto reass_done;
7593 	}
7594 
7595 	/*
7596 	 * If the packet's flag has changed (it could be coming up
7597 	 * from an interface different than the previous, therefore
7598 	 * possibly different checksum capability), then forget about
7599 	 * any stored checksum states.  Otherwise add the value to
7600 	 * the existing one stored in the fragment header.
7601 	 */
7602 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7603 		sum_val += ipf->ipf_checksum;
7604 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7605 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7606 		ipf->ipf_checksum = sum_val;
7607 	} else if (ipf->ipf_checksum_flags != 0) {
7608 		/* Forget checksum offload from now on */
7609 		ipf->ipf_checksum_flags = 0;
7610 	}
7611 
7612 	/*
7613 	 * We have a new piece of a datagram which is already being
7614 	 * reassembled.  Update the ECN info if all IP fragments
7615 	 * are ECN capable.  If there is one which is not, clear
7616 	 * all the info.  If there is at least one which has CE
7617 	 * code point, IP needs to report that up to transport.
7618 	 */
7619 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7620 		if (ecn_info == IPH_ECN_CE)
7621 			ipf->ipf_ecn = IPH_ECN_CE;
7622 	} else {
7623 		ipf->ipf_ecn = IPH_ECN_NECT;
7624 	}
7625 	if (offset && ipf->ipf_end == offset) {
7626 		/* The new fragment fits at the end */
7627 		ipf->ipf_tail_mp->b_cont = mp;
7628 		/* Update the byte count */
7629 		ipf->ipf_count += msg_len;
7630 		/* Update per ipfb and ill byte counts */
7631 		ipfb->ipfb_count += msg_len;
7632 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7633 		atomic_add_32(&ill->ill_frag_count, msg_len);
7634 		if (frag_offset_flags & IPH_MF) {
7635 			/* More to come. */
7636 			ipf->ipf_end = end;
7637 			ipf->ipf_tail_mp = tail_mp;
7638 			goto reass_done;
7639 		}
7640 	} else {
7641 		/* Go do the hard cases. */
7642 		int ret;
7643 
7644 		if (offset == 0)
7645 			ipf->ipf_nf_hdr_len = hdr_length;
7646 
7647 		/* Save current byte count */
7648 		count = ipf->ipf_count;
7649 		ret = ip_reassemble(mp, ipf,
7650 		    (frag_offset_flags & IPH_OFFSET) << 3,
7651 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7652 		/* Count of bytes added and subtracted (freeb()ed) */
7653 		count = ipf->ipf_count - count;
7654 		if (count) {
7655 			/* Update per ipfb and ill byte counts */
7656 			ipfb->ipfb_count += count;
7657 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7658 			atomic_add_32(&ill->ill_frag_count, count);
7659 		}
7660 		if (ret == IP_REASS_PARTIAL) {
7661 			goto reass_done;
7662 		} else if (ret == IP_REASS_FAILED) {
7663 			/* Reassembly failed. Free up all resources */
7664 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7665 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7666 				IP_REASS_SET_START(t_mp, 0);
7667 				IP_REASS_SET_END(t_mp, 0);
7668 			}
7669 			freemsg(mp);
7670 			goto reass_done;
7671 		}
7672 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7673 	}
7674 	/*
7675 	 * We have completed reassembly.  Unhook the frag header from
7676 	 * the reassembly list.
7677 	 *
7678 	 * Before we free the frag header, record the ECN info
7679 	 * to report back to the transport.
7680 	 */
7681 	ecn_info = ipf->ipf_ecn;
7682 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7683 	ipfp = ipf->ipf_ptphn;
7684 
7685 	/* We need to supply these to caller */
7686 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7687 		sum_val = ipf->ipf_checksum;
7688 	else
7689 		sum_val = 0;
7690 
7691 	mp1 = ipf->ipf_mp;
7692 	count = ipf->ipf_count;
7693 	ipf = ipf->ipf_hash_next;
7694 	if (ipf != NULL)
7695 		ipf->ipf_ptphn = ipfp;
7696 	ipfp[0] = ipf;
7697 	atomic_add_32(&ill->ill_frag_count, -count);
7698 	ASSERT(ipfb->ipfb_count >= count);
7699 	ipfb->ipfb_count -= count;
7700 	ipfb->ipfb_frag_pkts--;
7701 	mutex_exit(&ipfb->ipfb_lock);
7702 	/* Ditch the frag header. */
7703 	mp = mp1->b_cont;
7704 
7705 	freeb(mp1);
7706 
7707 	/* Restore original IP length in header. */
7708 	packet_size = (uint32_t)msgdsize(mp);
7709 	if (packet_size > IP_MAXPACKET) {
7710 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7711 		ip_drop_input("Reassembled packet too large", mp, ill);
7712 		freemsg(mp);
7713 		return (NULL);
7714 	}
7715 
7716 	if (DB_REF(mp) > 1) {
7717 		mblk_t *mp2 = copymsg(mp);
7718 
7719 		if (mp2 == NULL) {
7720 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7721 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7722 			freemsg(mp);
7723 			return (NULL);
7724 		}
7725 		freemsg(mp);
7726 		mp = mp2;
7727 	}
7728 	ipha = (ipha_t *)mp->b_rptr;
7729 
7730 	ipha->ipha_length = htons((uint16_t)packet_size);
7731 	/* We're now complete, zip the frag state */
7732 	ipha->ipha_fragment_offset_and_flags = 0;
7733 	/* Record the ECN info. */
7734 	ipha->ipha_type_of_service &= 0xFC;
7735 	ipha->ipha_type_of_service |= ecn_info;
7736 
7737 	/* Update the receive attributes */
7738 	ira->ira_pktlen = packet_size;
7739 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7740 
7741 	/* Reassembly is successful; set checksum information in packet */
7742 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7743 	DB_CKSUMFLAGS(mp) = sum_flags;
7744 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7745 
7746 	return (mp);
7747 }
7748 
7749 /*
7750  * Pullup function that should be used for IP input in order to
7751  * ensure we do not loose the L2 source address; we need the l2 source
7752  * address for IP_RECVSLLA and for ndp_input.
7753  *
7754  * We return either NULL or b_rptr.
7755  */
7756 void *
7757 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7758 {
7759 	ill_t		*ill = ira->ira_ill;
7760 
7761 	if (ip_rput_pullups++ == 0) {
7762 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7763 		    "ip_pullup: %s forced us to "
7764 		    " pullup pkt, hdr len %ld, hdr addr %p",
7765 		    ill->ill_name, len, (void *)mp->b_rptr);
7766 	}
7767 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7768 		ip_setl2src(mp, ira, ira->ira_rill);
7769 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7770 	if (!pullupmsg(mp, len))
7771 		return (NULL);
7772 	else
7773 		return (mp->b_rptr);
7774 }
7775 
7776 /*
7777  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7778  * When called from the ULP ira_rill will be NULL hence the caller has to
7779  * pass in the ill.
7780  */
7781 /* ARGSUSED */
7782 void
7783 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7784 {
7785 	const uchar_t *addr;
7786 	int alen;
7787 
7788 	if (ira->ira_flags & IRAF_L2SRC_SET)
7789 		return;
7790 
7791 	ASSERT(ill != NULL);
7792 	alen = ill->ill_phys_addr_length;
7793 	ASSERT(alen <= sizeof (ira->ira_l2src));
7794 	if (ira->ira_mhip != NULL &&
7795 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7796 		bcopy(addr, ira->ira_l2src, alen);
7797 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7798 	    (addr = ill->ill_phys_addr) != NULL) {
7799 		bcopy(addr, ira->ira_l2src, alen);
7800 	} else {
7801 		bzero(ira->ira_l2src, alen);
7802 	}
7803 	ira->ira_flags |= IRAF_L2SRC_SET;
7804 }
7805 
7806 /*
7807  * check ip header length and align it.
7808  */
7809 mblk_t *
7810 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7811 {
7812 	ill_t	*ill = ira->ira_ill;
7813 	ssize_t len;
7814 
7815 	len = MBLKL(mp);
7816 
7817 	if (!OK_32PTR(mp->b_rptr))
7818 		IP_STAT(ill->ill_ipst, ip_notaligned);
7819 	else
7820 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7821 
7822 	/* Guard against bogus device drivers */
7823 	if (len < 0) {
7824 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7825 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7826 		freemsg(mp);
7827 		return (NULL);
7828 	}
7829 
7830 	if (len == 0) {
7831 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7832 		mblk_t *mp1 = mp->b_cont;
7833 
7834 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7835 			ip_setl2src(mp, ira, ira->ira_rill);
7836 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7837 
7838 		freeb(mp);
7839 		mp = mp1;
7840 		if (mp == NULL)
7841 			return (NULL);
7842 
7843 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7844 			return (mp);
7845 	}
7846 	if (ip_pullup(mp, min_size, ira) == NULL) {
7847 		if (msgdsize(mp) < min_size) {
7848 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7849 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7850 		} else {
7851 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7852 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7853 		}
7854 		freemsg(mp);
7855 		return (NULL);
7856 	}
7857 	return (mp);
7858 }
7859 
7860 /*
7861  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7862  */
7863 mblk_t *
7864 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7865     uint_t min_size, ip_recv_attr_t *ira)
7866 {
7867 	ill_t	*ill = ira->ira_ill;
7868 
7869 	/*
7870 	 * Make sure we have data length consistent
7871 	 * with the IP header.
7872 	 */
7873 	if (mp->b_cont == NULL) {
7874 		/* pkt_len is based on ipha_len, not the mblk length */
7875 		if (pkt_len < min_size) {
7876 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7877 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7878 			freemsg(mp);
7879 			return (NULL);
7880 		}
7881 		if (len < 0) {
7882 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7883 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7884 			freemsg(mp);
7885 			return (NULL);
7886 		}
7887 		/* Drop any pad */
7888 		mp->b_wptr = rptr + pkt_len;
7889 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7890 		ASSERT(pkt_len >= min_size);
7891 		if (pkt_len < min_size) {
7892 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7893 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7894 			freemsg(mp);
7895 			return (NULL);
7896 		}
7897 		if (len < 0) {
7898 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7899 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7900 			freemsg(mp);
7901 			return (NULL);
7902 		}
7903 		/* Drop any pad */
7904 		(void) adjmsg(mp, -len);
7905 		/*
7906 		 * adjmsg may have freed an mblk from the chain, hence
7907 		 * invalidate any hw checksum here. This will force IP to
7908 		 * calculate the checksum in sw, but only for this packet.
7909 		 */
7910 		DB_CKSUMFLAGS(mp) = 0;
7911 		IP_STAT(ill->ill_ipst, ip_multimblk);
7912 	}
7913 	return (mp);
7914 }
7915 
7916 /*
7917  * Check that the IPv4 opt_len is consistent with the packet and pullup
7918  * the options.
7919  */
7920 mblk_t *
7921 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7922     ip_recv_attr_t *ira)
7923 {
7924 	ill_t	*ill = ira->ira_ill;
7925 	ssize_t len;
7926 
7927 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7928 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7929 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7930 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7931 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7932 		freemsg(mp);
7933 		return (NULL);
7934 	}
7935 
7936 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7937 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7938 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7939 		freemsg(mp);
7940 		return (NULL);
7941 	}
7942 	/*
7943 	 * Recompute complete header length and make sure we
7944 	 * have access to all of it.
7945 	 */
7946 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7947 	if (len > (mp->b_wptr - mp->b_rptr)) {
7948 		if (len > pkt_len) {
7949 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7950 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7951 			freemsg(mp);
7952 			return (NULL);
7953 		}
7954 		if (ip_pullup(mp, len, ira) == NULL) {
7955 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7956 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7957 			freemsg(mp);
7958 			return (NULL);
7959 		}
7960 	}
7961 	return (mp);
7962 }
7963 
7964 /*
7965  * Returns a new ire, or the same ire, or NULL.
7966  * If a different IRE is returned, then it is held; the caller
7967  * needs to release it.
7968  * In no case is there any hold/release on the ire argument.
7969  */
7970 ire_t *
7971 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7972 {
7973 	ire_t		*new_ire;
7974 	ill_t		*ire_ill;
7975 	uint_t		ifindex;
7976 	ip_stack_t	*ipst = ill->ill_ipst;
7977 	boolean_t	strict_check = B_FALSE;
7978 
7979 	/*
7980 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7981 	 * issue (e.g. packet received on an underlying interface matched an
7982 	 * IRE_LOCAL on its associated group interface).
7983 	 */
7984 	ASSERT(ire->ire_ill != NULL);
7985 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7986 		return (ire);
7987 
7988 	/*
7989 	 * Do another ire lookup here, using the ingress ill, to see if the
7990 	 * interface is in a usesrc group.
7991 	 * As long as the ills belong to the same group, we don't consider
7992 	 * them to be arriving on the wrong interface. Thus, if the switch
7993 	 * is doing inbound load spreading, we won't drop packets when the
7994 	 * ip*_strict_dst_multihoming switch is on.
7995 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7996 	 * where the local address may not be unique. In this case we were
7997 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7998 	 * actually returned. The new lookup, which is more specific, should
7999 	 * only find the IRE_LOCAL associated with the ingress ill if one
8000 	 * exists.
8001 	 */
8002 	if (ire->ire_ipversion == IPV4_VERSION) {
8003 		if (ipst->ips_ip_strict_dst_multihoming)
8004 			strict_check = B_TRUE;
8005 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
8006 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
8007 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
8008 	} else {
8009 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
8010 		if (ipst->ips_ipv6_strict_dst_multihoming)
8011 			strict_check = B_TRUE;
8012 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
8013 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
8014 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
8015 	}
8016 	/*
8017 	 * If the same ire that was returned in ip_input() is found then this
8018 	 * is an indication that usesrc groups are in use. The packet
8019 	 * arrived on a different ill in the group than the one associated with
8020 	 * the destination address.  If a different ire was found then the same
8021 	 * IP address must be hosted on multiple ills. This is possible with
8022 	 * unnumbered point2point interfaces. We switch to use this new ire in
8023 	 * order to have accurate interface statistics.
8024 	 */
8025 	if (new_ire != NULL) {
8026 		/* Note: held in one case but not the other? Caller handles */
8027 		if (new_ire != ire)
8028 			return (new_ire);
8029 		/* Unchanged */
8030 		ire_refrele(new_ire);
8031 		return (ire);
8032 	}
8033 
8034 	/*
8035 	 * Chase pointers once and store locally.
8036 	 */
8037 	ASSERT(ire->ire_ill != NULL);
8038 	ire_ill = ire->ire_ill;
8039 	ifindex = ill->ill_usesrc_ifindex;
8040 
8041 	/*
8042 	 * Check if it's a legal address on the 'usesrc' interface.
8043 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
8044 	 * can just check phyint_ifindex.
8045 	 */
8046 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
8047 		return (ire);
8048 	}
8049 
8050 	/*
8051 	 * If the ip*_strict_dst_multihoming switch is on then we can
8052 	 * only accept this packet if the interface is marked as routing.
8053 	 */
8054 	if (!(strict_check))
8055 		return (ire);
8056 
8057 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
8058 		return (ire);
8059 	}
8060 	return (NULL);
8061 }
8062 
8063 /*
8064  * This function is used to construct a mac_header_info_s from a
8065  * DL_UNITDATA_IND message.
8066  * The address fields in the mhi structure points into the message,
8067  * thus the caller can't use those fields after freeing the message.
8068  *
8069  * We determine whether the packet received is a non-unicast packet
8070  * and in doing so, determine whether or not it is broadcast vs multicast.
8071  * For it to be a broadcast packet, we must have the appropriate mblk_t
8072  * hanging off the ill_t.  If this is either not present or doesn't match
8073  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
8074  * to be multicast.  Thus NICs that have no broadcast address (or no
8075  * capability for one, such as point to point links) cannot return as
8076  * the packet being broadcast.
8077  */
8078 void
8079 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
8080 {
8081 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
8082 	mblk_t *bmp;
8083 	uint_t extra_offset;
8084 
8085 	bzero(mhip, sizeof (struct mac_header_info_s));
8086 
8087 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
8088 
8089 	if (ill->ill_sap_length < 0)
8090 		extra_offset = 0;
8091 	else
8092 		extra_offset = ill->ill_sap_length;
8093 
8094 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
8095 	    extra_offset;
8096 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
8097 	    extra_offset;
8098 
8099 	if (!ind->dl_group_address)
8100 		return;
8101 
8102 	/* Multicast or broadcast */
8103 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
8104 
8105 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
8106 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
8107 	    (bmp = ill->ill_bcast_mp) != NULL) {
8108 		dl_unitdata_req_t *dlur;
8109 		uint8_t *bphys_addr;
8110 
8111 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
8112 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
8113 		    extra_offset;
8114 
8115 		if (bcmp(mhip->mhi_daddr, bphys_addr,
8116 		    ind->dl_dest_addr_length) == 0)
8117 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
8118 	}
8119 }
8120 
8121 /*
8122  * This function is used to construct a mac_header_info_s from a
8123  * M_DATA fastpath message from a DLPI driver.
8124  * The address fields in the mhi structure points into the message,
8125  * thus the caller can't use those fields after freeing the message.
8126  *
8127  * We determine whether the packet received is a non-unicast packet
8128  * and in doing so, determine whether or not it is broadcast vs multicast.
8129  * For it to be a broadcast packet, we must have the appropriate mblk_t
8130  * hanging off the ill_t.  If this is either not present or doesn't match
8131  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
8132  * to be multicast.  Thus NICs that have no broadcast address (or no
8133  * capability for one, such as point to point links) cannot return as
8134  * the packet being broadcast.
8135  */
8136 void
8137 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
8138 {
8139 	mblk_t *bmp;
8140 	struct ether_header *pether;
8141 
8142 	bzero(mhip, sizeof (struct mac_header_info_s));
8143 
8144 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
8145 
8146 	pether = (struct ether_header *)((char *)mp->b_rptr
8147 	    - sizeof (struct ether_header));
8148 
8149 	/*
8150 	 * Make sure the interface is an ethernet type, since we don't
8151 	 * know the header format for anything but Ethernet. Also make
8152 	 * sure we are pointing correctly above db_base.
8153 	 */
8154 	if (ill->ill_type != IFT_ETHER)
8155 		return;
8156 
8157 retry:
8158 	if ((uchar_t *)pether < mp->b_datap->db_base)
8159 		return;
8160 
8161 	/* Is there a VLAN tag? */
8162 	if (ill->ill_isv6) {
8163 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
8164 			pether = (struct ether_header *)((char *)pether - 4);
8165 			goto retry;
8166 		}
8167 	} else {
8168 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
8169 			pether = (struct ether_header *)((char *)pether - 4);
8170 			goto retry;
8171 		}
8172 	}
8173 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
8174 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
8175 
8176 	if (!(mhip->mhi_daddr[0] & 0x01))
8177 		return;
8178 
8179 	/* Multicast or broadcast */
8180 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
8181 
8182 	if ((bmp = ill->ill_bcast_mp) != NULL) {
8183 		dl_unitdata_req_t *dlur;
8184 		uint8_t *bphys_addr;
8185 		uint_t	addrlen;
8186 
8187 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
8188 		addrlen = dlur->dl_dest_addr_length;
8189 		if (ill->ill_sap_length < 0) {
8190 			bphys_addr = (uchar_t *)dlur +
8191 			    dlur->dl_dest_addr_offset;
8192 			addrlen += ill->ill_sap_length;
8193 		} else {
8194 			bphys_addr = (uchar_t *)dlur +
8195 			    dlur->dl_dest_addr_offset +
8196 			    ill->ill_sap_length;
8197 			addrlen -= ill->ill_sap_length;
8198 		}
8199 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
8200 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
8201 	}
8202 }
8203 
8204 /*
8205  * Handle anything but M_DATA messages
8206  * We see the DL_UNITDATA_IND which are part
8207  * of the data path, and also the other messages from the driver.
8208  */
8209 void
8210 ip_rput_notdata(ill_t *ill, mblk_t *mp)
8211 {
8212 	mblk_t		*first_mp;
8213 	struct iocblk   *iocp;
8214 	struct mac_header_info_s mhi;
8215 
8216 	switch (DB_TYPE(mp)) {
8217 	case M_PROTO:
8218 	case M_PCPROTO: {
8219 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
8220 		    DL_UNITDATA_IND) {
8221 			/* Go handle anything other than data elsewhere. */
8222 			ip_rput_dlpi(ill, mp);
8223 			return;
8224 		}
8225 
8226 		first_mp = mp;
8227 		mp = first_mp->b_cont;
8228 		first_mp->b_cont = NULL;
8229 
8230 		if (mp == NULL) {
8231 			freeb(first_mp);
8232 			return;
8233 		}
8234 		ip_dlur_to_mhi(ill, first_mp, &mhi);
8235 		if (ill->ill_isv6)
8236 			ip_input_v6(ill, NULL, mp, &mhi);
8237 		else
8238 			ip_input(ill, NULL, mp, &mhi);
8239 
8240 		/* Ditch the DLPI header. */
8241 		freeb(first_mp);
8242 		return;
8243 	}
8244 	case M_IOCACK:
8245 		iocp = (struct iocblk *)mp->b_rptr;
8246 		switch (iocp->ioc_cmd) {
8247 		case DL_IOC_HDR_INFO:
8248 			ill_fastpath_ack(ill, mp);
8249 			return;
8250 		default:
8251 			putnext(ill->ill_rq, mp);
8252 			return;
8253 		}
8254 		/* FALLTHRU */
8255 	case M_ERROR:
8256 	case M_HANGUP:
8257 		mutex_enter(&ill->ill_lock);
8258 		if (ill->ill_state_flags & ILL_CONDEMNED) {
8259 			mutex_exit(&ill->ill_lock);
8260 			freemsg(mp);
8261 			return;
8262 		}
8263 		ill_refhold_locked(ill);
8264 		mutex_exit(&ill->ill_lock);
8265 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
8266 		    B_FALSE);
8267 		return;
8268 	case M_CTL:
8269 		putnext(ill->ill_rq, mp);
8270 		return;
8271 	case M_IOCNAK:
8272 		ip1dbg(("got iocnak "));
8273 		iocp = (struct iocblk *)mp->b_rptr;
8274 		switch (iocp->ioc_cmd) {
8275 		case DL_IOC_HDR_INFO:
8276 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
8277 			return;
8278 		default:
8279 			break;
8280 		}
8281 		/* FALLTHRU */
8282 	default:
8283 		putnext(ill->ill_rq, mp);
8284 		return;
8285 	}
8286 }
8287 
8288 /* Read side put procedure.  Packets coming from the wire arrive here. */
8289 void
8290 ip_rput(queue_t *q, mblk_t *mp)
8291 {
8292 	ill_t	*ill;
8293 	union DL_primitives *dl;
8294 
8295 	ill = (ill_t *)q->q_ptr;
8296 
8297 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
8298 		/*
8299 		 * If things are opening or closing, only accept high-priority
8300 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
8301 		 * created; on close, things hanging off the ill may have been
8302 		 * freed already.)
8303 		 */
8304 		dl = (union DL_primitives *)mp->b_rptr;
8305 		if (DB_TYPE(mp) != M_PCPROTO ||
8306 		    dl->dl_primitive == DL_UNITDATA_IND) {
8307 			inet_freemsg(mp);
8308 			return;
8309 		}
8310 	}
8311 	if (DB_TYPE(mp) == M_DATA) {
8312 		struct mac_header_info_s mhi;
8313 
8314 		ip_mdata_to_mhi(ill, mp, &mhi);
8315 		ip_input(ill, NULL, mp, &mhi);
8316 	} else {
8317 		ip_rput_notdata(ill, mp);
8318 	}
8319 }
8320 
8321 /*
8322  * Move the information to a copy.
8323  */
8324 mblk_t *
8325 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8326 {
8327 	mblk_t		*mp1;
8328 	ill_t		*ill = ira->ira_ill;
8329 	ip_stack_t	*ipst = ill->ill_ipst;
8330 
8331 	IP_STAT(ipst, ip_db_ref);
8332 
8333 	/* Make sure we have ira_l2src before we loose the original mblk */
8334 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
8335 		ip_setl2src(mp, ira, ira->ira_rill);
8336 
8337 	mp1 = copymsg(mp);
8338 	if (mp1 == NULL) {
8339 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8340 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
8341 		freemsg(mp);
8342 		return (NULL);
8343 	}
8344 	/* preserve the hardware checksum flags and data, if present */
8345 	if (DB_CKSUMFLAGS(mp) != 0) {
8346 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8347 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8348 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8349 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8350 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8351 	}
8352 	freemsg(mp);
8353 	return (mp1);
8354 }
8355 
8356 static void
8357 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8358     t_uscalar_t err)
8359 {
8360 	if (dl_err == DL_SYSERR) {
8361 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8362 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8363 		    ill->ill_name, dl_primstr(prim), err);
8364 		return;
8365 	}
8366 
8367 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8368 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8369 	    dl_errstr(dl_err));
8370 }
8371 
8372 /*
8373  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8374  * than DL_UNITDATA_IND messages. If we need to process this message
8375  * exclusively, we call qwriter_ip, in which case we also need to call
8376  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8377  */
8378 void
8379 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8380 {
8381 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8382 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8383 	queue_t		*q = ill->ill_rq;
8384 	t_uscalar_t	prim = dloa->dl_primitive;
8385 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8386 
8387 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8388 	    char *, dl_primstr(prim), ill_t *, ill);
8389 	ip1dbg(("ip_rput_dlpi"));
8390 
8391 	/*
8392 	 * If we received an ACK but didn't send a request for it, then it
8393 	 * can't be part of any pending operation; discard up-front.
8394 	 */
8395 	switch (prim) {
8396 	case DL_ERROR_ACK:
8397 		reqprim = dlea->dl_error_primitive;
8398 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8399 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8400 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8401 		    dlea->dl_unix_errno));
8402 		break;
8403 	case DL_OK_ACK:
8404 		reqprim = dloa->dl_correct_primitive;
8405 		break;
8406 	case DL_INFO_ACK:
8407 		reqprim = DL_INFO_REQ;
8408 		break;
8409 	case DL_BIND_ACK:
8410 		reqprim = DL_BIND_REQ;
8411 		break;
8412 	case DL_PHYS_ADDR_ACK:
8413 		reqprim = DL_PHYS_ADDR_REQ;
8414 		break;
8415 	case DL_NOTIFY_ACK:
8416 		reqprim = DL_NOTIFY_REQ;
8417 		break;
8418 	case DL_CAPABILITY_ACK:
8419 		reqprim = DL_CAPABILITY_REQ;
8420 		break;
8421 	}
8422 
8423 	if (prim != DL_NOTIFY_IND) {
8424 		if (reqprim == DL_PRIM_INVAL ||
8425 		    !ill_dlpi_pending(ill, reqprim)) {
8426 			/* Not a DLPI message we support or expected */
8427 			freemsg(mp);
8428 			return;
8429 		}
8430 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8431 		    dl_primstr(reqprim)));
8432 	}
8433 
8434 	switch (reqprim) {
8435 	case DL_UNBIND_REQ:
8436 		/*
8437 		 * NOTE: we mark the unbind as complete even if we got a
8438 		 * DL_ERROR_ACK, since there's not much else we can do.
8439 		 */
8440 		mutex_enter(&ill->ill_lock);
8441 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8442 		cv_signal(&ill->ill_cv);
8443 		mutex_exit(&ill->ill_lock);
8444 		break;
8445 
8446 	case DL_ENABMULTI_REQ:
8447 		if (prim == DL_OK_ACK) {
8448 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8449 				ill->ill_dlpi_multicast_state = IDS_OK;
8450 		}
8451 		break;
8452 	}
8453 
8454 	/*
8455 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8456 	 * need to become writer to continue to process it.  Because an
8457 	 * exclusive operation doesn't complete until replies to all queued
8458 	 * DLPI messages have been received, we know we're in the middle of an
8459 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8460 	 *
8461 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8462 	 * Since this is on the ill stream we unconditionally bump up the
8463 	 * refcount without doing ILL_CAN_LOOKUP().
8464 	 */
8465 	ill_refhold(ill);
8466 	if (prim == DL_NOTIFY_IND)
8467 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8468 	else
8469 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8470 }
8471 
8472 /*
8473  * Handling of DLPI messages that require exclusive access to the ipsq.
8474  *
8475  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8476  * happen here. (along with mi_copy_done)
8477  */
8478 /* ARGSUSED */
8479 static void
8480 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8481 {
8482 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8483 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8484 	int		err = 0;
8485 	ill_t		*ill = (ill_t *)q->q_ptr;
8486 	ipif_t		*ipif = NULL;
8487 	mblk_t		*mp1 = NULL;
8488 	conn_t		*connp = NULL;
8489 	t_uscalar_t	paddrreq;
8490 	mblk_t		*mp_hw;
8491 	boolean_t	success;
8492 	boolean_t	ioctl_aborted = B_FALSE;
8493 	boolean_t	log = B_TRUE;
8494 
8495 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8496 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8497 
8498 	ip1dbg(("ip_rput_dlpi_writer .."));
8499 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8500 	ASSERT(IAM_WRITER_ILL(ill));
8501 
8502 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8503 	/*
8504 	 * The current ioctl could have been aborted by the user and a new
8505 	 * ioctl to bring up another ill could have started. We could still
8506 	 * get a response from the driver later.
8507 	 */
8508 	if (ipif != NULL && ipif->ipif_ill != ill)
8509 		ioctl_aborted = B_TRUE;
8510 
8511 	switch (dloa->dl_primitive) {
8512 	case DL_ERROR_ACK:
8513 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8514 		    dl_primstr(dlea->dl_error_primitive)));
8515 
8516 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8517 		    char *, dl_primstr(dlea->dl_error_primitive),
8518 		    ill_t *, ill);
8519 
8520 		switch (dlea->dl_error_primitive) {
8521 		case DL_DISABMULTI_REQ:
8522 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8523 			break;
8524 		case DL_PROMISCON_REQ:
8525 		case DL_PROMISCOFF_REQ:
8526 		case DL_UNBIND_REQ:
8527 		case DL_ATTACH_REQ:
8528 		case DL_INFO_REQ:
8529 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8530 			break;
8531 		case DL_NOTIFY_REQ:
8532 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8533 			log = B_FALSE;
8534 			break;
8535 		case DL_PHYS_ADDR_REQ:
8536 			/*
8537 			 * For IPv6 only, there are two additional
8538 			 * phys_addr_req's sent to the driver to get the
8539 			 * IPv6 token and lla. This allows IP to acquire
8540 			 * the hardware address format for a given interface
8541 			 * without having built in knowledge of the hardware
8542 			 * address. ill_phys_addr_pend keeps track of the last
8543 			 * DL_PAR sent so we know which response we are
8544 			 * dealing with. ill_dlpi_done will update
8545 			 * ill_phys_addr_pend when it sends the next req.
8546 			 * We don't complete the IOCTL until all three DL_PARs
8547 			 * have been attempted, so set *_len to 0 and break.
8548 			 */
8549 			paddrreq = ill->ill_phys_addr_pend;
8550 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8551 			if (paddrreq == DL_IPV6_TOKEN) {
8552 				ill->ill_token_length = 0;
8553 				log = B_FALSE;
8554 				break;
8555 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8556 				ill->ill_nd_lla_len = 0;
8557 				log = B_FALSE;
8558 				break;
8559 			}
8560 			/*
8561 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8562 			 * We presumably have an IOCTL hanging out waiting
8563 			 * for completion. Find it and complete the IOCTL
8564 			 * with the error noted.
8565 			 * However, ill_dl_phys was called on an ill queue
8566 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8567 			 * set. But the ioctl is known to be pending on ill_wq.
8568 			 */
8569 			if (!ill->ill_ifname_pending)
8570 				break;
8571 			ill->ill_ifname_pending = 0;
8572 			if (!ioctl_aborted)
8573 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8574 			if (mp1 != NULL) {
8575 				/*
8576 				 * This operation (SIOCSLIFNAME) must have
8577 				 * happened on the ill. Assert there is no conn
8578 				 */
8579 				ASSERT(connp == NULL);
8580 				q = ill->ill_wq;
8581 			}
8582 			break;
8583 		case DL_BIND_REQ:
8584 			ill_dlpi_done(ill, DL_BIND_REQ);
8585 			if (ill->ill_ifname_pending)
8586 				break;
8587 			/*
8588 			 * Something went wrong with the bind.  We presumably
8589 			 * have an IOCTL hanging out waiting for completion.
8590 			 * Find it, take down the interface that was coming
8591 			 * up, and complete the IOCTL with the error noted.
8592 			 */
8593 			if (!ioctl_aborted)
8594 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8595 			if (mp1 != NULL) {
8596 				/*
8597 				 * This might be a result of a DL_NOTE_REPLUMB
8598 				 * notification. In that case, connp is NULL.
8599 				 */
8600 				if (connp != NULL)
8601 					q = CONNP_TO_WQ(connp);
8602 
8603 				(void) ipif_down(ipif, NULL, NULL);
8604 				/* error is set below the switch */
8605 			}
8606 			break;
8607 		case DL_ENABMULTI_REQ:
8608 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8609 
8610 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8611 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8612 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8613 
8614 				printf("ip: joining multicasts failed (%d)"
8615 				    " on %s - will use link layer "
8616 				    "broadcasts for multicast\n",
8617 				    dlea->dl_errno, ill->ill_name);
8618 
8619 				/*
8620 				 * Set up for multi_bcast; We are the
8621 				 * writer, so ok to access ill->ill_ipif
8622 				 * without any lock.
8623 				 */
8624 				mutex_enter(&ill->ill_phyint->phyint_lock);
8625 				ill->ill_phyint->phyint_flags |=
8626 				    PHYI_MULTI_BCAST;
8627 				mutex_exit(&ill->ill_phyint->phyint_lock);
8628 
8629 			}
8630 			freemsg(mp);	/* Don't want to pass this up */
8631 			return;
8632 		case DL_CAPABILITY_REQ:
8633 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8634 			    "DL_CAPABILITY REQ\n"));
8635 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8636 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8637 			ill_capability_done(ill);
8638 			freemsg(mp);
8639 			return;
8640 		}
8641 		/*
8642 		 * Note the error for IOCTL completion (mp1 is set when
8643 		 * ready to complete ioctl). If ill_ifname_pending_err is
8644 		 * set, an error occured during plumbing (ill_ifname_pending),
8645 		 * so we want to report that error.
8646 		 *
8647 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8648 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8649 		 * expected to get errack'd if the driver doesn't support
8650 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8651 		 * if these error conditions are encountered.
8652 		 */
8653 		if (mp1 != NULL) {
8654 			if (ill->ill_ifname_pending_err != 0)  {
8655 				err = ill->ill_ifname_pending_err;
8656 				ill->ill_ifname_pending_err = 0;
8657 			} else {
8658 				err = dlea->dl_unix_errno ?
8659 				    dlea->dl_unix_errno : ENXIO;
8660 			}
8661 		/*
8662 		 * If we're plumbing an interface and an error hasn't already
8663 		 * been saved, set ill_ifname_pending_err to the error passed
8664 		 * up. Ignore the error if log is B_FALSE (see comment above).
8665 		 */
8666 		} else if (log && ill->ill_ifname_pending &&
8667 		    ill->ill_ifname_pending_err == 0) {
8668 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8669 			    dlea->dl_unix_errno : ENXIO;
8670 		}
8671 
8672 		if (log)
8673 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8674 			    dlea->dl_errno, dlea->dl_unix_errno);
8675 		break;
8676 	case DL_CAPABILITY_ACK:
8677 		ill_capability_ack(ill, mp);
8678 		/*
8679 		 * The message has been handed off to ill_capability_ack
8680 		 * and must not be freed below
8681 		 */
8682 		mp = NULL;
8683 		break;
8684 
8685 	case DL_INFO_ACK:
8686 		/* Call a routine to handle this one. */
8687 		ill_dlpi_done(ill, DL_INFO_REQ);
8688 		ip_ll_subnet_defaults(ill, mp);
8689 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8690 		return;
8691 	case DL_BIND_ACK:
8692 		/*
8693 		 * We should have an IOCTL waiting on this unless
8694 		 * sent by ill_dl_phys, in which case just return
8695 		 */
8696 		ill_dlpi_done(ill, DL_BIND_REQ);
8697 		if (ill->ill_ifname_pending) {
8698 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8699 			    ill_t *, ill, mblk_t *, mp);
8700 			break;
8701 		}
8702 		if (!ioctl_aborted)
8703 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8704 		if (mp1 == NULL) {
8705 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8706 			break;
8707 		}
8708 		/*
8709 		 * mp1 was added by ill_dl_up(). if that is a result of
8710 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8711 		 */
8712 		if (connp != NULL)
8713 			q = CONNP_TO_WQ(connp);
8714 		/*
8715 		 * We are exclusive. So nothing can change even after
8716 		 * we get the pending mp.
8717 		 */
8718 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8719 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8720 
8721 		mutex_enter(&ill->ill_lock);
8722 		ill->ill_dl_up = 1;
8723 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8724 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8725 		mutex_exit(&ill->ill_lock);
8726 
8727 		/*
8728 		 * Now bring up the resolver; when that is complete, we'll
8729 		 * create IREs.  Note that we intentionally mirror what
8730 		 * ipif_up() would have done, because we got here by way of
8731 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8732 		 */
8733 		if (ill->ill_isv6) {
8734 			/*
8735 			 * v6 interfaces.
8736 			 * Unlike ARP which has to do another bind
8737 			 * and attach, once we get here we are
8738 			 * done with NDP
8739 			 */
8740 			(void) ipif_resolver_up(ipif, Res_act_initial);
8741 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8742 				err = ipif_up_done_v6(ipif);
8743 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8744 			/*
8745 			 * ARP and other v4 external resolvers.
8746 			 * Leave the pending mblk intact so that
8747 			 * the ioctl completes in ip_rput().
8748 			 */
8749 			if (connp != NULL)
8750 				mutex_enter(&connp->conn_lock);
8751 			mutex_enter(&ill->ill_lock);
8752 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8753 			mutex_exit(&ill->ill_lock);
8754 			if (connp != NULL)
8755 				mutex_exit(&connp->conn_lock);
8756 			if (success) {
8757 				err = ipif_resolver_up(ipif, Res_act_initial);
8758 				if (err == EINPROGRESS) {
8759 					freemsg(mp);
8760 					return;
8761 				}
8762 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8763 			} else {
8764 				/* The conn has started closing */
8765 				err = EINTR;
8766 			}
8767 		} else {
8768 			/*
8769 			 * This one is complete. Reply to pending ioctl.
8770 			 */
8771 			(void) ipif_resolver_up(ipif, Res_act_initial);
8772 			err = ipif_up_done(ipif);
8773 		}
8774 
8775 		if ((err == 0) && (ill->ill_up_ipifs)) {
8776 			err = ill_up_ipifs(ill, q, mp1);
8777 			if (err == EINPROGRESS) {
8778 				freemsg(mp);
8779 				return;
8780 			}
8781 		}
8782 
8783 		/*
8784 		 * If we have a moved ipif to bring up, and everything has
8785 		 * succeeded to this point, bring it up on the IPMP ill.
8786 		 * Otherwise, leave it down -- the admin can try to bring it
8787 		 * up by hand if need be.
8788 		 */
8789 		if (ill->ill_move_ipif != NULL) {
8790 			if (err != 0) {
8791 				ill->ill_move_ipif = NULL;
8792 			} else {
8793 				ipif = ill->ill_move_ipif;
8794 				ill->ill_move_ipif = NULL;
8795 				err = ipif_up(ipif, q, mp1);
8796 				if (err == EINPROGRESS) {
8797 					freemsg(mp);
8798 					return;
8799 				}
8800 			}
8801 		}
8802 		break;
8803 
8804 	case DL_NOTIFY_IND: {
8805 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8806 		uint_t orig_mtu;
8807 
8808 		switch (notify->dl_notification) {
8809 		case DL_NOTE_PHYS_ADDR:
8810 			err = ill_set_phys_addr(ill, mp);
8811 			break;
8812 
8813 		case DL_NOTE_REPLUMB:
8814 			/*
8815 			 * Directly return after calling ill_replumb().
8816 			 * Note that we should not free mp as it is reused
8817 			 * in the ill_replumb() function.
8818 			 */
8819 			err = ill_replumb(ill, mp);
8820 			return;
8821 
8822 		case DL_NOTE_FASTPATH_FLUSH:
8823 			nce_flush(ill, B_FALSE);
8824 			break;
8825 
8826 		case DL_NOTE_SDU_SIZE:
8827 			/*
8828 			 * The dce and fragmentation code can cope with
8829 			 * this changing while packets are being sent.
8830 			 * When packets are sent ip_output will discover
8831 			 * a change.
8832 			 *
8833 			 * Change the MTU size of the interface.
8834 			 */
8835 			mutex_enter(&ill->ill_lock);
8836 			ill->ill_current_frag = (uint_t)notify->dl_data;
8837 			if (ill->ill_current_frag > ill->ill_max_frag)
8838 				ill->ill_max_frag = ill->ill_current_frag;
8839 
8840 			orig_mtu = ill->ill_mtu;
8841 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8842 				ill->ill_mtu = ill->ill_current_frag;
8843 
8844 				/*
8845 				 * If ill_user_mtu was set (via
8846 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8847 				 */
8848 				if (ill->ill_user_mtu != 0 &&
8849 				    ill->ill_user_mtu < ill->ill_mtu)
8850 					ill->ill_mtu = ill->ill_user_mtu;
8851 
8852 				if (ill->ill_isv6) {
8853 					if (ill->ill_mtu < IPV6_MIN_MTU)
8854 						ill->ill_mtu = IPV6_MIN_MTU;
8855 				} else {
8856 					if (ill->ill_mtu < IP_MIN_MTU)
8857 						ill->ill_mtu = IP_MIN_MTU;
8858 				}
8859 			}
8860 			mutex_exit(&ill->ill_lock);
8861 			/*
8862 			 * Make sure all dce_generation checks find out
8863 			 * that ill_mtu has changed.
8864 			 */
8865 			if (orig_mtu != ill->ill_mtu) {
8866 				dce_increment_all_generations(ill->ill_isv6,
8867 				    ill->ill_ipst);
8868 			}
8869 
8870 			/*
8871 			 * Refresh IPMP meta-interface MTU if necessary.
8872 			 */
8873 			if (IS_UNDER_IPMP(ill))
8874 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8875 			break;
8876 
8877 		case DL_NOTE_LINK_UP:
8878 		case DL_NOTE_LINK_DOWN: {
8879 			/*
8880 			 * We are writer. ill / phyint / ipsq assocs stable.
8881 			 * The RUNNING flag reflects the state of the link.
8882 			 */
8883 			phyint_t *phyint = ill->ill_phyint;
8884 			uint64_t new_phyint_flags;
8885 			boolean_t changed = B_FALSE;
8886 			boolean_t went_up;
8887 
8888 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8889 			mutex_enter(&phyint->phyint_lock);
8890 
8891 			new_phyint_flags = went_up ?
8892 			    phyint->phyint_flags | PHYI_RUNNING :
8893 			    phyint->phyint_flags & ~PHYI_RUNNING;
8894 
8895 			if (IS_IPMP(ill)) {
8896 				new_phyint_flags = went_up ?
8897 				    new_phyint_flags & ~PHYI_FAILED :
8898 				    new_phyint_flags | PHYI_FAILED;
8899 			}
8900 
8901 			if (new_phyint_flags != phyint->phyint_flags) {
8902 				phyint->phyint_flags = new_phyint_flags;
8903 				changed = B_TRUE;
8904 			}
8905 			mutex_exit(&phyint->phyint_lock);
8906 			/*
8907 			 * ill_restart_dad handles the DAD restart and routing
8908 			 * socket notification logic.
8909 			 */
8910 			if (changed) {
8911 				ill_restart_dad(phyint->phyint_illv4, went_up);
8912 				ill_restart_dad(phyint->phyint_illv6, went_up);
8913 			}
8914 			break;
8915 		}
8916 		case DL_NOTE_PROMISC_ON_PHYS: {
8917 			phyint_t *phyint = ill->ill_phyint;
8918 
8919 			mutex_enter(&phyint->phyint_lock);
8920 			phyint->phyint_flags |= PHYI_PROMISC;
8921 			mutex_exit(&phyint->phyint_lock);
8922 			break;
8923 		}
8924 		case DL_NOTE_PROMISC_OFF_PHYS: {
8925 			phyint_t *phyint = ill->ill_phyint;
8926 
8927 			mutex_enter(&phyint->phyint_lock);
8928 			phyint->phyint_flags &= ~PHYI_PROMISC;
8929 			mutex_exit(&phyint->phyint_lock);
8930 			break;
8931 		}
8932 		case DL_NOTE_CAPAB_RENEG:
8933 			/*
8934 			 * Something changed on the driver side.
8935 			 * It wants us to renegotiate the capabilities
8936 			 * on this ill. One possible cause is the aggregation
8937 			 * interface under us where a port got added or
8938 			 * went away.
8939 			 *
8940 			 * If the capability negotiation is already done
8941 			 * or is in progress, reset the capabilities and
8942 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8943 			 * so that when the ack comes back, we can start
8944 			 * the renegotiation process.
8945 			 *
8946 			 * Note that if ill_capab_reneg is already B_TRUE
8947 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8948 			 * the capability resetting request has been sent
8949 			 * and the renegotiation has not been started yet;
8950 			 * nothing needs to be done in this case.
8951 			 */
8952 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8953 			ill_capability_reset(ill, B_TRUE);
8954 			ipsq_current_finish(ipsq);
8955 			break;
8956 		default:
8957 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8958 			    "type 0x%x for DL_NOTIFY_IND\n",
8959 			    notify->dl_notification));
8960 			break;
8961 		}
8962 
8963 		/*
8964 		 * As this is an asynchronous operation, we
8965 		 * should not call ill_dlpi_done
8966 		 */
8967 		break;
8968 	}
8969 	case DL_NOTIFY_ACK: {
8970 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8971 
8972 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8973 			ill->ill_note_link = 1;
8974 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8975 		break;
8976 	}
8977 	case DL_PHYS_ADDR_ACK: {
8978 		/*
8979 		 * As part of plumbing the interface via SIOCSLIFNAME,
8980 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8981 		 * whose answers we receive here.  As each answer is received,
8982 		 * we call ill_dlpi_done() to dispatch the next request as
8983 		 * we're processing the current one.  Once all answers have
8984 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8985 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8986 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8987 		 * available, but we know the ioctl is pending on ill_wq.)
8988 		 */
8989 		uint_t	paddrlen, paddroff;
8990 		uint8_t	*addr;
8991 
8992 		paddrreq = ill->ill_phys_addr_pend;
8993 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8994 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8995 		addr = mp->b_rptr + paddroff;
8996 
8997 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8998 		if (paddrreq == DL_IPV6_TOKEN) {
8999 			/*
9000 			 * bcopy to low-order bits of ill_token
9001 			 *
9002 			 * XXX Temporary hack - currently, all known tokens
9003 			 * are 64 bits, so I'll cheat for the moment.
9004 			 */
9005 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
9006 			ill->ill_token_length = paddrlen;
9007 			break;
9008 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
9009 			ASSERT(ill->ill_nd_lla_mp == NULL);
9010 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
9011 			mp = NULL;
9012 			break;
9013 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
9014 			ASSERT(ill->ill_dest_addr_mp == NULL);
9015 			ill->ill_dest_addr_mp = mp;
9016 			ill->ill_dest_addr = addr;
9017 			mp = NULL;
9018 			if (ill->ill_isv6) {
9019 				ill_setdesttoken(ill);
9020 				ipif_setdestlinklocal(ill->ill_ipif);
9021 			}
9022 			break;
9023 		}
9024 
9025 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
9026 		ASSERT(ill->ill_phys_addr_mp == NULL);
9027 		if (!ill->ill_ifname_pending)
9028 			break;
9029 		ill->ill_ifname_pending = 0;
9030 		if (!ioctl_aborted)
9031 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
9032 		if (mp1 != NULL) {
9033 			ASSERT(connp == NULL);
9034 			q = ill->ill_wq;
9035 		}
9036 		/*
9037 		 * If any error acks received during the plumbing sequence,
9038 		 * ill_ifname_pending_err will be set. Break out and send up
9039 		 * the error to the pending ioctl.
9040 		 */
9041 		if (ill->ill_ifname_pending_err != 0) {
9042 			err = ill->ill_ifname_pending_err;
9043 			ill->ill_ifname_pending_err = 0;
9044 			break;
9045 		}
9046 
9047 		ill->ill_phys_addr_mp = mp;
9048 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
9049 		mp = NULL;
9050 
9051 		/*
9052 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
9053 		 * provider doesn't support physical addresses.  We check both
9054 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
9055 		 * not have physical addresses, but historically adversises a
9056 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
9057 		 * its DL_PHYS_ADDR_ACK.
9058 		 */
9059 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
9060 			ill->ill_phys_addr = NULL;
9061 		} else if (paddrlen != ill->ill_phys_addr_length) {
9062 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
9063 			    paddrlen, ill->ill_phys_addr_length));
9064 			err = EINVAL;
9065 			break;
9066 		}
9067 
9068 		if (ill->ill_nd_lla_mp == NULL) {
9069 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
9070 				err = ENOMEM;
9071 				break;
9072 			}
9073 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
9074 		}
9075 
9076 		if (ill->ill_isv6) {
9077 			ill_setdefaulttoken(ill);
9078 			ipif_setlinklocal(ill->ill_ipif);
9079 		}
9080 		break;
9081 	}
9082 	case DL_OK_ACK:
9083 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
9084 		    dl_primstr((int)dloa->dl_correct_primitive),
9085 		    dloa->dl_correct_primitive));
9086 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
9087 		    char *, dl_primstr(dloa->dl_correct_primitive),
9088 		    ill_t *, ill);
9089 
9090 		switch (dloa->dl_correct_primitive) {
9091 		case DL_ENABMULTI_REQ:
9092 		case DL_DISABMULTI_REQ:
9093 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
9094 			break;
9095 		case DL_PROMISCON_REQ:
9096 		case DL_PROMISCOFF_REQ:
9097 		case DL_UNBIND_REQ:
9098 		case DL_ATTACH_REQ:
9099 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
9100 			break;
9101 		}
9102 		break;
9103 	default:
9104 		break;
9105 	}
9106 
9107 	freemsg(mp);
9108 	if (mp1 == NULL)
9109 		return;
9110 
9111 	/*
9112 	 * The operation must complete without EINPROGRESS since
9113 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
9114 	 * the operation will be stuck forever inside the IPSQ.
9115 	 */
9116 	ASSERT(err != EINPROGRESS);
9117 
9118 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
9119 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
9120 	    ipif_t *, NULL);
9121 
9122 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
9123 	case 0:
9124 		ipsq_current_finish(ipsq);
9125 		break;
9126 
9127 	case SIOCSLIFNAME:
9128 	case IF_UNITSEL: {
9129 		ill_t *ill_other = ILL_OTHER(ill);
9130 
9131 		/*
9132 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
9133 		 * ill has a peer which is in an IPMP group, then place ill
9134 		 * into the same group.  One catch: although ifconfig plumbs
9135 		 * the appropriate IPMP meta-interface prior to plumbing this
9136 		 * ill, it is possible for multiple ifconfig applications to
9137 		 * race (or for another application to adjust plumbing), in
9138 		 * which case the IPMP meta-interface we need will be missing.
9139 		 * If so, kick the phyint out of the group.
9140 		 */
9141 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
9142 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
9143 			ipmp_illgrp_t	*illg;
9144 
9145 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
9146 			if (illg == NULL)
9147 				ipmp_phyint_leave_grp(ill->ill_phyint);
9148 			else
9149 				ipmp_ill_join_illgrp(ill, illg);
9150 		}
9151 
9152 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
9153 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
9154 		else
9155 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
9156 		break;
9157 	}
9158 	case SIOCLIFADDIF:
9159 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
9160 		break;
9161 
9162 	default:
9163 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
9164 		break;
9165 	}
9166 }
9167 
9168 /*
9169  * ip_rput_other is called by ip_rput to handle messages modifying the global
9170  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
9171  */
9172 /* ARGSUSED */
9173 void
9174 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
9175 {
9176 	ill_t		*ill = q->q_ptr;
9177 	struct iocblk	*iocp;
9178 
9179 	ip1dbg(("ip_rput_other "));
9180 	if (ipsq != NULL) {
9181 		ASSERT(IAM_WRITER_IPSQ(ipsq));
9182 		ASSERT(ipsq->ipsq_xop ==
9183 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
9184 	}
9185 
9186 	switch (mp->b_datap->db_type) {
9187 	case M_ERROR:
9188 	case M_HANGUP:
9189 		/*
9190 		 * The device has a problem.  We force the ILL down.  It can
9191 		 * be brought up again manually using SIOCSIFFLAGS (via
9192 		 * ifconfig or equivalent).
9193 		 */
9194 		ASSERT(ipsq != NULL);
9195 		if (mp->b_rptr < mp->b_wptr)
9196 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
9197 		if (ill->ill_error == 0)
9198 			ill->ill_error = ENXIO;
9199 		if (!ill_down_start(q, mp))
9200 			return;
9201 		ipif_all_down_tail(ipsq, q, mp, NULL);
9202 		break;
9203 	case M_IOCNAK: {
9204 		iocp = (struct iocblk *)mp->b_rptr;
9205 
9206 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
9207 		/*
9208 		 * If this was the first attempt, turn off the fastpath
9209 		 * probing.
9210 		 */
9211 		mutex_enter(&ill->ill_lock);
9212 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
9213 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
9214 			mutex_exit(&ill->ill_lock);
9215 			/*
9216 			 * don't flush the nce_t entries: we use them
9217 			 * as an index to the ncec itself.
9218 			 */
9219 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
9220 			    ill->ill_name));
9221 		} else {
9222 			mutex_exit(&ill->ill_lock);
9223 		}
9224 		freemsg(mp);
9225 		break;
9226 	}
9227 	default:
9228 		ASSERT(0);
9229 		break;
9230 	}
9231 }
9232 
9233 /*
9234  * Update any source route, record route or timestamp options
9235  * When it fails it has consumed the message and BUMPed the MIB.
9236  */
9237 boolean_t
9238 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
9239     ip_recv_attr_t *ira)
9240 {
9241 	ipoptp_t	opts;
9242 	uchar_t		*opt;
9243 	uint8_t		optval;
9244 	uint8_t		optlen;
9245 	ipaddr_t	dst;
9246 	ipaddr_t	ifaddr;
9247 	uint32_t	ts;
9248 	timestruc_t	now;
9249 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9250 
9251 	ip2dbg(("ip_forward_options\n"));
9252 	dst = ipha->ipha_dst;
9253 	for (optval = ipoptp_first(&opts, ipha);
9254 	    optval != IPOPT_EOL;
9255 	    optval = ipoptp_next(&opts)) {
9256 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9257 		opt = opts.ipoptp_cur;
9258 		optlen = opts.ipoptp_len;
9259 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
9260 		    optval, opts.ipoptp_len));
9261 		switch (optval) {
9262 			uint32_t off;
9263 		case IPOPT_SSRR:
9264 		case IPOPT_LSRR:
9265 			/* Check if adminstratively disabled */
9266 			if (!ipst->ips_ip_forward_src_routed) {
9267 				BUMP_MIB(dst_ill->ill_ip_mib,
9268 				    ipIfStatsForwProhibits);
9269 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
9270 				    mp, dst_ill);
9271 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
9272 				    ira);
9273 				return (B_FALSE);
9274 			}
9275 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9276 				/*
9277 				 * Must be partial since ip_input_options
9278 				 * checked for strict.
9279 				 */
9280 				break;
9281 			}
9282 			off = opt[IPOPT_OFFSET];
9283 			off--;
9284 		redo_srr:
9285 			if (optlen < IP_ADDR_LEN ||
9286 			    off > optlen - IP_ADDR_LEN) {
9287 				/* End of source route */
9288 				ip1dbg((
9289 				    "ip_forward_options: end of SR\n"));
9290 				break;
9291 			}
9292 			/* Pick a reasonable address on the outbound if */
9293 			ASSERT(dst_ill != NULL);
9294 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9295 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9296 			    NULL) != 0) {
9297 				/* No source! Shouldn't happen */
9298 				ifaddr = INADDR_ANY;
9299 			}
9300 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9301 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9302 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
9303 			    ntohl(dst)));
9304 
9305 			/*
9306 			 * Check if our address is present more than
9307 			 * once as consecutive hops in source route.
9308 			 */
9309 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9310 				off += IP_ADDR_LEN;
9311 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9312 				goto redo_srr;
9313 			}
9314 			ipha->ipha_dst = dst;
9315 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9316 			break;
9317 		case IPOPT_RR:
9318 			off = opt[IPOPT_OFFSET];
9319 			off--;
9320 			if (optlen < IP_ADDR_LEN ||
9321 			    off > optlen - IP_ADDR_LEN) {
9322 				/* No more room - ignore */
9323 				ip1dbg((
9324 				    "ip_forward_options: end of RR\n"));
9325 				break;
9326 			}
9327 			/* Pick a reasonable address on the outbound if */
9328 			ASSERT(dst_ill != NULL);
9329 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9330 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9331 			    NULL) != 0) {
9332 				/* No source! Shouldn't happen */
9333 				ifaddr = INADDR_ANY;
9334 			}
9335 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9336 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9337 			break;
9338 		case IPOPT_TS:
9339 			/* Insert timestamp if there is room */
9340 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9341 			case IPOPT_TS_TSONLY:
9342 				off = IPOPT_TS_TIMELEN;
9343 				break;
9344 			case IPOPT_TS_PRESPEC:
9345 			case IPOPT_TS_PRESPEC_RFC791:
9346 				/* Verify that the address matched */
9347 				off = opt[IPOPT_OFFSET] - 1;
9348 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9349 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9350 					/* Not for us */
9351 					break;
9352 				}
9353 				/* FALLTHRU */
9354 			case IPOPT_TS_TSANDADDR:
9355 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9356 				break;
9357 			default:
9358 				/*
9359 				 * ip_*put_options should have already
9360 				 * dropped this packet.
9361 				 */
9362 				cmn_err(CE_PANIC, "ip_forward_options: "
9363 				    "unknown IT - bug in ip_input_options?\n");
9364 				return (B_TRUE);	/* Keep "lint" happy */
9365 			}
9366 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9367 				/* Increase overflow counter */
9368 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9369 				opt[IPOPT_POS_OV_FLG] =
9370 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9371 				    (off << 4));
9372 				break;
9373 			}
9374 			off = opt[IPOPT_OFFSET] - 1;
9375 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9376 			case IPOPT_TS_PRESPEC:
9377 			case IPOPT_TS_PRESPEC_RFC791:
9378 			case IPOPT_TS_TSANDADDR:
9379 				/* Pick a reasonable addr on the outbound if */
9380 				ASSERT(dst_ill != NULL);
9381 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9382 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9383 				    NULL, NULL) != 0) {
9384 					/* No source! Shouldn't happen */
9385 					ifaddr = INADDR_ANY;
9386 				}
9387 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9388 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9389 				/* FALLTHRU */
9390 			case IPOPT_TS_TSONLY:
9391 				off = opt[IPOPT_OFFSET] - 1;
9392 				/* Compute # of milliseconds since midnight */
9393 				gethrestime(&now);
9394 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9395 				    now.tv_nsec / (NANOSEC / MILLISEC);
9396 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9397 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9398 				break;
9399 			}
9400 			break;
9401 		}
9402 	}
9403 	return (B_TRUE);
9404 }
9405 
9406 /*
9407  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9408  * returns 'true' if there are still fragments left on the queue, in
9409  * which case we restart the timer.
9410  */
9411 void
9412 ill_frag_timer(void *arg)
9413 {
9414 	ill_t	*ill = (ill_t *)arg;
9415 	boolean_t frag_pending;
9416 	ip_stack_t	*ipst = ill->ill_ipst;
9417 	time_t	timeout;
9418 
9419 	mutex_enter(&ill->ill_lock);
9420 	ASSERT(!ill->ill_fragtimer_executing);
9421 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9422 		ill->ill_frag_timer_id = 0;
9423 		mutex_exit(&ill->ill_lock);
9424 		return;
9425 	}
9426 	ill->ill_fragtimer_executing = 1;
9427 	mutex_exit(&ill->ill_lock);
9428 
9429 	if (ill->ill_isv6)
9430 		timeout = ipst->ips_ipv6_frag_timeout;
9431 	else
9432 		timeout = ipst->ips_ip_g_frag_timeout;
9433 
9434 	frag_pending = ill_frag_timeout(ill, timeout);
9435 
9436 	/*
9437 	 * Restart the timer, if we have fragments pending or if someone
9438 	 * wanted us to be scheduled again.
9439 	 */
9440 	mutex_enter(&ill->ill_lock);
9441 	ill->ill_fragtimer_executing = 0;
9442 	ill->ill_frag_timer_id = 0;
9443 	if (frag_pending || ill->ill_fragtimer_needrestart)
9444 		ill_frag_timer_start(ill);
9445 	mutex_exit(&ill->ill_lock);
9446 }
9447 
9448 void
9449 ill_frag_timer_start(ill_t *ill)
9450 {
9451 	ip_stack_t	*ipst = ill->ill_ipst;
9452 	clock_t	timeo_ms;
9453 
9454 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9455 
9456 	/* If the ill is closing or opening don't proceed */
9457 	if (ill->ill_state_flags & ILL_CONDEMNED)
9458 		return;
9459 
9460 	if (ill->ill_fragtimer_executing) {
9461 		/*
9462 		 * ill_frag_timer is currently executing. Just record the
9463 		 * the fact that we want the timer to be restarted.
9464 		 * ill_frag_timer will post a timeout before it returns,
9465 		 * ensuring it will be called again.
9466 		 */
9467 		ill->ill_fragtimer_needrestart = 1;
9468 		return;
9469 	}
9470 
9471 	if (ill->ill_frag_timer_id == 0) {
9472 		if (ill->ill_isv6)
9473 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
9474 		else
9475 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
9476 		/*
9477 		 * The timer is neither running nor is the timeout handler
9478 		 * executing. Post a timeout so that ill_frag_timer will be
9479 		 * called
9480 		 */
9481 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9482 		    MSEC_TO_TICK(timeo_ms >> 1));
9483 		ill->ill_fragtimer_needrestart = 0;
9484 	}
9485 }
9486 
9487 /*
9488  * Update any source route, record route or timestamp options.
9489  * Check that we are at end of strict source route.
9490  * The options have already been checked for sanity in ip_input_options().
9491  */
9492 boolean_t
9493 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9494 {
9495 	ipoptp_t	opts;
9496 	uchar_t		*opt;
9497 	uint8_t		optval;
9498 	uint8_t		optlen;
9499 	ipaddr_t	dst;
9500 	ipaddr_t	ifaddr;
9501 	uint32_t	ts;
9502 	timestruc_t	now;
9503 	ill_t		*ill = ira->ira_ill;
9504 	ip_stack_t	*ipst = ill->ill_ipst;
9505 
9506 	ip2dbg(("ip_input_local_options\n"));
9507 
9508 	for (optval = ipoptp_first(&opts, ipha);
9509 	    optval != IPOPT_EOL;
9510 	    optval = ipoptp_next(&opts)) {
9511 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9512 		opt = opts.ipoptp_cur;
9513 		optlen = opts.ipoptp_len;
9514 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9515 		    optval, optlen));
9516 		switch (optval) {
9517 			uint32_t off;
9518 		case IPOPT_SSRR:
9519 		case IPOPT_LSRR:
9520 			off = opt[IPOPT_OFFSET];
9521 			off--;
9522 			if (optlen < IP_ADDR_LEN ||
9523 			    off > optlen - IP_ADDR_LEN) {
9524 				/* End of source route */
9525 				ip1dbg(("ip_input_local_options: end of SR\n"));
9526 				break;
9527 			}
9528 			/*
9529 			 * This will only happen if two consecutive entries
9530 			 * in the source route contains our address or if
9531 			 * it is a packet with a loose source route which
9532 			 * reaches us before consuming the whole source route
9533 			 */
9534 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9535 			if (optval == IPOPT_SSRR) {
9536 				goto bad_src_route;
9537 			}
9538 			/*
9539 			 * Hack: instead of dropping the packet truncate the
9540 			 * source route to what has been used by filling the
9541 			 * rest with IPOPT_NOP.
9542 			 */
9543 			opt[IPOPT_OLEN] = (uint8_t)off;
9544 			while (off < optlen) {
9545 				opt[off++] = IPOPT_NOP;
9546 			}
9547 			break;
9548 		case IPOPT_RR:
9549 			off = opt[IPOPT_OFFSET];
9550 			off--;
9551 			if (optlen < IP_ADDR_LEN ||
9552 			    off > optlen - IP_ADDR_LEN) {
9553 				/* No more room - ignore */
9554 				ip1dbg((
9555 				    "ip_input_local_options: end of RR\n"));
9556 				break;
9557 			}
9558 			/* Pick a reasonable address on the outbound if */
9559 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9560 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9561 			    NULL) != 0) {
9562 				/* No source! Shouldn't happen */
9563 				ifaddr = INADDR_ANY;
9564 			}
9565 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9566 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9567 			break;
9568 		case IPOPT_TS:
9569 			/* Insert timestamp if there is romm */
9570 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9571 			case IPOPT_TS_TSONLY:
9572 				off = IPOPT_TS_TIMELEN;
9573 				break;
9574 			case IPOPT_TS_PRESPEC:
9575 			case IPOPT_TS_PRESPEC_RFC791:
9576 				/* Verify that the address matched */
9577 				off = opt[IPOPT_OFFSET] - 1;
9578 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9579 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9580 					/* Not for us */
9581 					break;
9582 				}
9583 				/* FALLTHRU */
9584 			case IPOPT_TS_TSANDADDR:
9585 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9586 				break;
9587 			default:
9588 				/*
9589 				 * ip_*put_options should have already
9590 				 * dropped this packet.
9591 				 */
9592 				cmn_err(CE_PANIC, "ip_input_local_options: "
9593 				    "unknown IT - bug in ip_input_options?\n");
9594 				return (B_TRUE);	/* Keep "lint" happy */
9595 			}
9596 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9597 				/* Increase overflow counter */
9598 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9599 				opt[IPOPT_POS_OV_FLG] =
9600 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9601 				    (off << 4));
9602 				break;
9603 			}
9604 			off = opt[IPOPT_OFFSET] - 1;
9605 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9606 			case IPOPT_TS_PRESPEC:
9607 			case IPOPT_TS_PRESPEC_RFC791:
9608 			case IPOPT_TS_TSANDADDR:
9609 				/* Pick a reasonable addr on the outbound if */
9610 				if (ip_select_source_v4(ill, INADDR_ANY,
9611 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9612 				    &ifaddr, NULL, NULL) != 0) {
9613 					/* No source! Shouldn't happen */
9614 					ifaddr = INADDR_ANY;
9615 				}
9616 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9617 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9618 				/* FALLTHRU */
9619 			case IPOPT_TS_TSONLY:
9620 				off = opt[IPOPT_OFFSET] - 1;
9621 				/* Compute # of milliseconds since midnight */
9622 				gethrestime(&now);
9623 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9624 				    now.tv_nsec / (NANOSEC / MILLISEC);
9625 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9626 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9627 				break;
9628 			}
9629 			break;
9630 		}
9631 	}
9632 	return (B_TRUE);
9633 
9634 bad_src_route:
9635 	/* make sure we clear any indication of a hardware checksum */
9636 	DB_CKSUMFLAGS(mp) = 0;
9637 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9638 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9639 	return (B_FALSE);
9640 
9641 }
9642 
9643 /*
9644  * Process IP options in an inbound packet.  Always returns the nexthop.
9645  * Normally this is the passed in nexthop, but if there is an option
9646  * that effects the nexthop (such as a source route) that will be returned.
9647  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9648  * and mp freed.
9649  */
9650 ipaddr_t
9651 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9652     ip_recv_attr_t *ira, int *errorp)
9653 {
9654 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9655 	ipoptp_t	opts;
9656 	uchar_t		*opt;
9657 	uint8_t		optval;
9658 	uint8_t		optlen;
9659 	intptr_t	code = 0;
9660 	ire_t		*ire;
9661 
9662 	ip2dbg(("ip_input_options\n"));
9663 	*errorp = 0;
9664 	for (optval = ipoptp_first(&opts, ipha);
9665 	    optval != IPOPT_EOL;
9666 	    optval = ipoptp_next(&opts)) {
9667 		opt = opts.ipoptp_cur;
9668 		optlen = opts.ipoptp_len;
9669 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9670 		    optval, optlen));
9671 		/*
9672 		 * Note: we need to verify the checksum before we
9673 		 * modify anything thus this routine only extracts the next
9674 		 * hop dst from any source route.
9675 		 */
9676 		switch (optval) {
9677 			uint32_t off;
9678 		case IPOPT_SSRR:
9679 		case IPOPT_LSRR:
9680 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9681 				if (optval == IPOPT_SSRR) {
9682 					ip1dbg(("ip_input_options: not next"
9683 					    " strict source route 0x%x\n",
9684 					    ntohl(dst)));
9685 					code = (char *)&ipha->ipha_dst -
9686 					    (char *)ipha;
9687 					goto param_prob; /* RouterReq's */
9688 				}
9689 				ip2dbg(("ip_input_options: "
9690 				    "not next source route 0x%x\n",
9691 				    ntohl(dst)));
9692 				break;
9693 			}
9694 
9695 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9696 				ip1dbg((
9697 				    "ip_input_options: bad option offset\n"));
9698 				code = (char *)&opt[IPOPT_OLEN] -
9699 				    (char *)ipha;
9700 				goto param_prob;
9701 			}
9702 			off = opt[IPOPT_OFFSET];
9703 			off--;
9704 		redo_srr:
9705 			if (optlen < IP_ADDR_LEN ||
9706 			    off > optlen - IP_ADDR_LEN) {
9707 				/* End of source route */
9708 				ip1dbg(("ip_input_options: end of SR\n"));
9709 				break;
9710 			}
9711 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9712 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9713 			    ntohl(dst)));
9714 
9715 			/*
9716 			 * Check if our address is present more than
9717 			 * once as consecutive hops in source route.
9718 			 * XXX verify per-interface ip_forwarding
9719 			 * for source route?
9720 			 */
9721 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9722 				off += IP_ADDR_LEN;
9723 				goto redo_srr;
9724 			}
9725 
9726 			if (dst == htonl(INADDR_LOOPBACK)) {
9727 				ip1dbg(("ip_input_options: loopback addr in "
9728 				    "source route!\n"));
9729 				goto bad_src_route;
9730 			}
9731 			/*
9732 			 * For strict: verify that dst is directly
9733 			 * reachable.
9734 			 */
9735 			if (optval == IPOPT_SSRR) {
9736 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9737 				    IRE_IF_ALL, NULL, ALL_ZONES,
9738 				    ira->ira_tsl,
9739 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9740 				    NULL);
9741 				if (ire == NULL) {
9742 					ip1dbg(("ip_input_options: SSRR not "
9743 					    "directly reachable: 0x%x\n",
9744 					    ntohl(dst)));
9745 					goto bad_src_route;
9746 				}
9747 				ire_refrele(ire);
9748 			}
9749 			/*
9750 			 * Defer update of the offset and the record route
9751 			 * until the packet is forwarded.
9752 			 */
9753 			break;
9754 		case IPOPT_RR:
9755 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9756 				ip1dbg((
9757 				    "ip_input_options: bad option offset\n"));
9758 				code = (char *)&opt[IPOPT_OLEN] -
9759 				    (char *)ipha;
9760 				goto param_prob;
9761 			}
9762 			break;
9763 		case IPOPT_TS:
9764 			/*
9765 			 * Verify that length >= 5 and that there is either
9766 			 * room for another timestamp or that the overflow
9767 			 * counter is not maxed out.
9768 			 */
9769 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9770 			if (optlen < IPOPT_MINLEN_IT) {
9771 				goto param_prob;
9772 			}
9773 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9774 				ip1dbg((
9775 				    "ip_input_options: bad option offset\n"));
9776 				code = (char *)&opt[IPOPT_OFFSET] -
9777 				    (char *)ipha;
9778 				goto param_prob;
9779 			}
9780 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9781 			case IPOPT_TS_TSONLY:
9782 				off = IPOPT_TS_TIMELEN;
9783 				break;
9784 			case IPOPT_TS_TSANDADDR:
9785 			case IPOPT_TS_PRESPEC:
9786 			case IPOPT_TS_PRESPEC_RFC791:
9787 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9788 				break;
9789 			default:
9790 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9791 				    (char *)ipha;
9792 				goto param_prob;
9793 			}
9794 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9795 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9796 				/*
9797 				 * No room and the overflow counter is 15
9798 				 * already.
9799 				 */
9800 				goto param_prob;
9801 			}
9802 			break;
9803 		}
9804 	}
9805 
9806 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9807 		return (dst);
9808 	}
9809 
9810 	ip1dbg(("ip_input_options: error processing IP options."));
9811 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9812 
9813 param_prob:
9814 	/* make sure we clear any indication of a hardware checksum */
9815 	DB_CKSUMFLAGS(mp) = 0;
9816 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9817 	icmp_param_problem(mp, (uint8_t)code, ira);
9818 	*errorp = -1;
9819 	return (dst);
9820 
9821 bad_src_route:
9822 	/* make sure we clear any indication of a hardware checksum */
9823 	DB_CKSUMFLAGS(mp) = 0;
9824 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9825 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9826 	*errorp = -1;
9827 	return (dst);
9828 }
9829 
9830 /*
9831  * IP & ICMP info in >=14 msg's ...
9832  *  - ip fixed part (mib2_ip_t)
9833  *  - icmp fixed part (mib2_icmp_t)
9834  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9835  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9836  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9837  *  - ipRouteAttributeTable (ip 102)	labeled routes
9838  *  - ip multicast membership (ip_member_t)
9839  *  - ip multicast source filtering (ip_grpsrc_t)
9840  *  - igmp fixed part (struct igmpstat)
9841  *  - multicast routing stats (struct mrtstat)
9842  *  - multicast routing vifs (array of struct vifctl)
9843  *  - multicast routing routes (array of struct mfcctl)
9844  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9845  *					One per ill plus one generic
9846  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9847  *					One per ill plus one generic
9848  *  - ipv6RouteEntry			all IPv6 IREs
9849  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9850  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9851  *  - ipv6AddrEntry			all IPv6 ipifs
9852  *  - ipv6 multicast membership (ipv6_member_t)
9853  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9854  *
9855  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9856  * already filled in by the caller.
9857  * Return value of 0 indicates that no messages were sent and caller
9858  * should free mpctl.
9859  */
9860 int
9861 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
9862 {
9863 	ip_stack_t *ipst;
9864 	sctp_stack_t *sctps;
9865 
9866 	if (q->q_next != NULL) {
9867 		ipst = ILLQ_TO_IPST(q);
9868 	} else {
9869 		ipst = CONNQ_TO_IPST(q);
9870 	}
9871 	ASSERT(ipst != NULL);
9872 	sctps = ipst->ips_netstack->netstack_sctp;
9873 
9874 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9875 		return (0);
9876 	}
9877 
9878 	/*
9879 	 * For the purposes of the (broken) packet shell use
9880 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9881 	 * to make TCP and UDP appear first in the list of mib items.
9882 	 * TBD: We could expand this and use it in netstat so that
9883 	 * the kernel doesn't have to produce large tables (connections,
9884 	 * routes, etc) when netstat only wants the statistics or a particular
9885 	 * table.
9886 	 */
9887 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9888 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9889 			return (1);
9890 		}
9891 	}
9892 
9893 	if (level != MIB2_TCP) {
9894 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
9895 			return (1);
9896 		}
9897 	}
9898 
9899 	if (level != MIB2_UDP) {
9900 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
9901 			return (1);
9902 		}
9903 	}
9904 
9905 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9906 	    ipst)) == NULL) {
9907 		return (1);
9908 	}
9909 
9910 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
9911 		return (1);
9912 	}
9913 
9914 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9915 		return (1);
9916 	}
9917 
9918 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9919 		return (1);
9920 	}
9921 
9922 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9923 		return (1);
9924 	}
9925 
9926 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9927 		return (1);
9928 	}
9929 
9930 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
9931 		return (1);
9932 	}
9933 
9934 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
9935 		return (1);
9936 	}
9937 
9938 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9939 		return (1);
9940 	}
9941 
9942 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9943 		return (1);
9944 	}
9945 
9946 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9947 		return (1);
9948 	}
9949 
9950 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9951 		return (1);
9952 	}
9953 
9954 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9955 		return (1);
9956 	}
9957 
9958 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9959 		return (1);
9960 	}
9961 
9962 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9963 	if (mpctl == NULL)
9964 		return (1);
9965 
9966 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9967 	if (mpctl == NULL)
9968 		return (1);
9969 
9970 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9971 		return (1);
9972 	}
9973 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9974 		return (1);
9975 	}
9976 	freemsg(mpctl);
9977 	return (1);
9978 }
9979 
9980 /* Get global (legacy) IPv4 statistics */
9981 static mblk_t *
9982 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9983     ip_stack_t *ipst)
9984 {
9985 	mib2_ip_t		old_ip_mib;
9986 	struct opthdr		*optp;
9987 	mblk_t			*mp2ctl;
9988 
9989 	/*
9990 	 * make a copy of the original message
9991 	 */
9992 	mp2ctl = copymsg(mpctl);
9993 
9994 	/* fixed length IP structure... */
9995 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9996 	optp->level = MIB2_IP;
9997 	optp->name = 0;
9998 	SET_MIB(old_ip_mib.ipForwarding,
9999 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
10000 	SET_MIB(old_ip_mib.ipDefaultTTL,
10001 	    (uint32_t)ipst->ips_ip_def_ttl);
10002 	SET_MIB(old_ip_mib.ipReasmTimeout,
10003 	    ipst->ips_ip_g_frag_timeout);
10004 	SET_MIB(old_ip_mib.ipAddrEntrySize,
10005 	    sizeof (mib2_ipAddrEntry_t));
10006 	SET_MIB(old_ip_mib.ipRouteEntrySize,
10007 	    sizeof (mib2_ipRouteEntry_t));
10008 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
10009 	    sizeof (mib2_ipNetToMediaEntry_t));
10010 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
10011 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
10012 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
10013 	    sizeof (mib2_ipAttributeEntry_t));
10014 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
10015 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
10016 
10017 	/*
10018 	 * Grab the statistics from the new IP MIB
10019 	 */
10020 	SET_MIB(old_ip_mib.ipInReceives,
10021 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
10022 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
10023 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
10024 	SET_MIB(old_ip_mib.ipForwDatagrams,
10025 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
10026 	SET_MIB(old_ip_mib.ipInUnknownProtos,
10027 	    ipmib->ipIfStatsInUnknownProtos);
10028 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
10029 	SET_MIB(old_ip_mib.ipInDelivers,
10030 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
10031 	SET_MIB(old_ip_mib.ipOutRequests,
10032 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
10033 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
10034 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
10035 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
10036 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
10037 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
10038 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
10039 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
10040 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
10041 
10042 	/* ipRoutingDiscards is not being used */
10043 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
10044 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
10045 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
10046 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
10047 	SET_MIB(old_ip_mib.ipReasmDuplicates,
10048 	    ipmib->ipIfStatsReasmDuplicates);
10049 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
10050 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
10051 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
10052 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
10053 	SET_MIB(old_ip_mib.rawipInOverflows,
10054 	    ipmib->rawipIfStatsInOverflows);
10055 
10056 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
10057 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
10058 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
10059 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
10060 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
10061 	    ipmib->ipIfStatsOutSwitchIPVersion);
10062 
10063 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
10064 	    (int)sizeof (old_ip_mib))) {
10065 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
10066 		    (uint_t)sizeof (old_ip_mib)));
10067 	}
10068 
10069 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10070 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
10071 	    (int)optp->level, (int)optp->name, (int)optp->len));
10072 	qreply(q, mpctl);
10073 	return (mp2ctl);
10074 }
10075 
10076 /* Per interface IPv4 statistics */
10077 static mblk_t *
10078 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10079 {
10080 	struct opthdr		*optp;
10081 	mblk_t			*mp2ctl;
10082 	ill_t			*ill;
10083 	ill_walk_context_t	ctx;
10084 	mblk_t			*mp_tail = NULL;
10085 	mib2_ipIfStatsEntry_t	global_ip_mib;
10086 
10087 	/*
10088 	 * Make a copy of the original message
10089 	 */
10090 	mp2ctl = copymsg(mpctl);
10091 
10092 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10093 	optp->level = MIB2_IP;
10094 	optp->name = MIB2_IP_TRAFFIC_STATS;
10095 	/* Include "unknown interface" ip_mib */
10096 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
10097 	ipst->ips_ip_mib.ipIfStatsIfIndex =
10098 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10099 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
10100 	    (ipst->ips_ip_g_forward ? 1 : 2));
10101 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
10102 	    (uint32_t)ipst->ips_ip_def_ttl);
10103 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
10104 	    sizeof (mib2_ipIfStatsEntry_t));
10105 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
10106 	    sizeof (mib2_ipAddrEntry_t));
10107 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
10108 	    sizeof (mib2_ipRouteEntry_t));
10109 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
10110 	    sizeof (mib2_ipNetToMediaEntry_t));
10111 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
10112 	    sizeof (ip_member_t));
10113 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
10114 	    sizeof (ip_grpsrc_t));
10115 
10116 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10117 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
10118 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
10119 		    "failed to allocate %u bytes\n",
10120 		    (uint_t)sizeof (ipst->ips_ip_mib)));
10121 	}
10122 
10123 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
10124 
10125 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10126 	ill = ILL_START_WALK_V4(&ctx, ipst);
10127 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10128 		ill->ill_ip_mib->ipIfStatsIfIndex =
10129 		    ill->ill_phyint->phyint_ifindex;
10130 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10131 		    (ipst->ips_ip_g_forward ? 1 : 2));
10132 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
10133 		    (uint32_t)ipst->ips_ip_def_ttl);
10134 
10135 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
10136 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10137 		    (char *)ill->ill_ip_mib,
10138 		    (int)sizeof (*ill->ill_ip_mib))) {
10139 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
10140 			    "failed to allocate %u bytes\n",
10141 			    (uint_t)sizeof (*ill->ill_ip_mib)));
10142 		}
10143 	}
10144 	rw_exit(&ipst->ips_ill_g_lock);
10145 
10146 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10147 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
10148 	    "level %d, name %d, len %d\n",
10149 	    (int)optp->level, (int)optp->name, (int)optp->len));
10150 	qreply(q, mpctl);
10151 
10152 	if (mp2ctl == NULL)
10153 		return (NULL);
10154 
10155 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
10156 }
10157 
10158 /* Global IPv4 ICMP statistics */
10159 static mblk_t *
10160 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10161 {
10162 	struct opthdr		*optp;
10163 	mblk_t			*mp2ctl;
10164 
10165 	/*
10166 	 * Make a copy of the original message
10167 	 */
10168 	mp2ctl = copymsg(mpctl);
10169 
10170 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10171 	optp->level = MIB2_ICMP;
10172 	optp->name = 0;
10173 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
10174 	    (int)sizeof (ipst->ips_icmp_mib))) {
10175 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
10176 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
10177 	}
10178 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10179 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
10180 	    (int)optp->level, (int)optp->name, (int)optp->len));
10181 	qreply(q, mpctl);
10182 	return (mp2ctl);
10183 }
10184 
10185 /* Global IPv4 IGMP statistics */
10186 static mblk_t *
10187 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10188 {
10189 	struct opthdr		*optp;
10190 	mblk_t			*mp2ctl;
10191 
10192 	/*
10193 	 * make a copy of the original message
10194 	 */
10195 	mp2ctl = copymsg(mpctl);
10196 
10197 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10198 	optp->level = EXPER_IGMP;
10199 	optp->name = 0;
10200 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
10201 	    (int)sizeof (ipst->ips_igmpstat))) {
10202 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
10203 		    (uint_t)sizeof (ipst->ips_igmpstat)));
10204 	}
10205 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10206 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
10207 	    (int)optp->level, (int)optp->name, (int)optp->len));
10208 	qreply(q, mpctl);
10209 	return (mp2ctl);
10210 }
10211 
10212 /* Global IPv4 Multicast Routing statistics */
10213 static mblk_t *
10214 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10215 {
10216 	struct opthdr		*optp;
10217 	mblk_t			*mp2ctl;
10218 
10219 	/*
10220 	 * make a copy of the original message
10221 	 */
10222 	mp2ctl = copymsg(mpctl);
10223 
10224 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10225 	optp->level = EXPER_DVMRP;
10226 	optp->name = 0;
10227 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
10228 		ip0dbg(("ip_mroute_stats: failed\n"));
10229 	}
10230 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10231 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
10232 	    (int)optp->level, (int)optp->name, (int)optp->len));
10233 	qreply(q, mpctl);
10234 	return (mp2ctl);
10235 }
10236 
10237 /* IPv4 address information */
10238 static mblk_t *
10239 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10240 {
10241 	struct opthdr		*optp;
10242 	mblk_t			*mp2ctl;
10243 	mblk_t			*mp_tail = NULL;
10244 	ill_t			*ill;
10245 	ipif_t			*ipif;
10246 	uint_t			bitval;
10247 	mib2_ipAddrEntry_t	mae;
10248 	zoneid_t		zoneid;
10249 	ill_walk_context_t ctx;
10250 
10251 	/*
10252 	 * make a copy of the original message
10253 	 */
10254 	mp2ctl = copymsg(mpctl);
10255 
10256 	/* ipAddrEntryTable */
10257 
10258 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10259 	optp->level = MIB2_IP;
10260 	optp->name = MIB2_IP_ADDR;
10261 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10262 
10263 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10264 	ill = ILL_START_WALK_V4(&ctx, ipst);
10265 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10266 		for (ipif = ill->ill_ipif; ipif != NULL;
10267 		    ipif = ipif->ipif_next) {
10268 			if (ipif->ipif_zoneid != zoneid &&
10269 			    ipif->ipif_zoneid != ALL_ZONES)
10270 				continue;
10271 			/* Sum of count from dead IRE_LO* and our current */
10272 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10273 			if (ipif->ipif_ire_local != NULL) {
10274 				mae.ipAdEntInfo.ae_ibcnt +=
10275 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10276 			}
10277 			mae.ipAdEntInfo.ae_obcnt = 0;
10278 			mae.ipAdEntInfo.ae_focnt = 0;
10279 
10280 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
10281 			    OCTET_LENGTH);
10282 			mae.ipAdEntIfIndex.o_length =
10283 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
10284 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
10285 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
10286 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
10287 			mae.ipAdEntInfo.ae_subnet_len =
10288 			    ip_mask_to_plen(ipif->ipif_net_mask);
10289 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
10290 			for (bitval = 1;
10291 			    bitval &&
10292 			    !(bitval & ipif->ipif_brd_addr);
10293 			    bitval <<= 1)
10294 				noop;
10295 			mae.ipAdEntBcastAddr = bitval;
10296 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10297 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10298 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
10299 			mae.ipAdEntInfo.ae_broadcast_addr =
10300 			    ipif->ipif_brd_addr;
10301 			mae.ipAdEntInfo.ae_pp_dst_addr =
10302 			    ipif->ipif_pp_dst_addr;
10303 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10304 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10305 			mae.ipAdEntRetransmitTime =
10306 			    ill->ill_reachable_retrans_time;
10307 
10308 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10309 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
10310 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10311 				    "allocate %u bytes\n",
10312 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
10313 			}
10314 		}
10315 	}
10316 	rw_exit(&ipst->ips_ill_g_lock);
10317 
10318 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10319 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10320 	    (int)optp->level, (int)optp->name, (int)optp->len));
10321 	qreply(q, mpctl);
10322 	return (mp2ctl);
10323 }
10324 
10325 /* IPv6 address information */
10326 static mblk_t *
10327 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10328 {
10329 	struct opthdr		*optp;
10330 	mblk_t			*mp2ctl;
10331 	mblk_t			*mp_tail = NULL;
10332 	ill_t			*ill;
10333 	ipif_t			*ipif;
10334 	mib2_ipv6AddrEntry_t	mae6;
10335 	zoneid_t		zoneid;
10336 	ill_walk_context_t	ctx;
10337 
10338 	/*
10339 	 * make a copy of the original message
10340 	 */
10341 	mp2ctl = copymsg(mpctl);
10342 
10343 	/* ipv6AddrEntryTable */
10344 
10345 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10346 	optp->level = MIB2_IP6;
10347 	optp->name = MIB2_IP6_ADDR;
10348 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10349 
10350 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10351 	ill = ILL_START_WALK_V6(&ctx, ipst);
10352 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10353 		for (ipif = ill->ill_ipif; ipif != NULL;
10354 		    ipif = ipif->ipif_next) {
10355 			if (ipif->ipif_zoneid != zoneid &&
10356 			    ipif->ipif_zoneid != ALL_ZONES)
10357 				continue;
10358 			/* Sum of count from dead IRE_LO* and our current */
10359 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10360 			if (ipif->ipif_ire_local != NULL) {
10361 				mae6.ipv6AddrInfo.ae_ibcnt +=
10362 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10363 			}
10364 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10365 			mae6.ipv6AddrInfo.ae_focnt = 0;
10366 
10367 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10368 			    OCTET_LENGTH);
10369 			mae6.ipv6AddrIfIndex.o_length =
10370 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10371 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10372 			mae6.ipv6AddrPfxLength =
10373 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10374 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10375 			mae6.ipv6AddrInfo.ae_subnet_len =
10376 			    mae6.ipv6AddrPfxLength;
10377 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10378 
10379 			/* Type: stateless(1), stateful(2), unknown(3) */
10380 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10381 				mae6.ipv6AddrType = 1;
10382 			else
10383 				mae6.ipv6AddrType = 2;
10384 			/* Anycast: true(1), false(2) */
10385 			if (ipif->ipif_flags & IPIF_ANYCAST)
10386 				mae6.ipv6AddrAnycastFlag = 1;
10387 			else
10388 				mae6.ipv6AddrAnycastFlag = 2;
10389 
10390 			/*
10391 			 * Address status: preferred(1), deprecated(2),
10392 			 * invalid(3), inaccessible(4), unknown(5)
10393 			 */
10394 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10395 				mae6.ipv6AddrStatus = 3;
10396 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10397 				mae6.ipv6AddrStatus = 2;
10398 			else
10399 				mae6.ipv6AddrStatus = 1;
10400 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10401 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
10402 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10403 			    ipif->ipif_v6pp_dst_addr;
10404 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10405 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10406 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10407 			mae6.ipv6AddrIdentifier = ill->ill_token;
10408 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10409 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10410 			mae6.ipv6AddrRetransmitTime =
10411 			    ill->ill_reachable_retrans_time;
10412 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10413 			    (char *)&mae6,
10414 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
10415 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10416 				    "allocate %u bytes\n",
10417 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
10418 			}
10419 		}
10420 	}
10421 	rw_exit(&ipst->ips_ill_g_lock);
10422 
10423 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10424 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10425 	    (int)optp->level, (int)optp->name, (int)optp->len));
10426 	qreply(q, mpctl);
10427 	return (mp2ctl);
10428 }
10429 
10430 /* IPv4 multicast group membership. */
10431 static mblk_t *
10432 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10433 {
10434 	struct opthdr		*optp;
10435 	mblk_t			*mp2ctl;
10436 	ill_t			*ill;
10437 	ipif_t			*ipif;
10438 	ilm_t			*ilm;
10439 	ip_member_t		ipm;
10440 	mblk_t			*mp_tail = NULL;
10441 	ill_walk_context_t	ctx;
10442 	zoneid_t		zoneid;
10443 
10444 	/*
10445 	 * make a copy of the original message
10446 	 */
10447 	mp2ctl = copymsg(mpctl);
10448 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10449 
10450 	/* ipGroupMember table */
10451 	optp = (struct opthdr *)&mpctl->b_rptr[
10452 	    sizeof (struct T_optmgmt_ack)];
10453 	optp->level = MIB2_IP;
10454 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10455 
10456 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10457 	ill = ILL_START_WALK_V4(&ctx, ipst);
10458 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10459 		/* Make sure the ill isn't going away. */
10460 		if (!ill_check_and_refhold(ill))
10461 			continue;
10462 		rw_exit(&ipst->ips_ill_g_lock);
10463 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10464 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10465 			if (ilm->ilm_zoneid != zoneid &&
10466 			    ilm->ilm_zoneid != ALL_ZONES)
10467 				continue;
10468 
10469 			/* Is there an ipif for ilm_ifaddr? */
10470 			for (ipif = ill->ill_ipif; ipif != NULL;
10471 			    ipif = ipif->ipif_next) {
10472 				if (!IPIF_IS_CONDEMNED(ipif) &&
10473 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10474 				    ilm->ilm_ifaddr != INADDR_ANY)
10475 					break;
10476 			}
10477 			if (ipif != NULL) {
10478 				ipif_get_name(ipif,
10479 				    ipm.ipGroupMemberIfIndex.o_bytes,
10480 				    OCTET_LENGTH);
10481 			} else {
10482 				ill_get_name(ill,
10483 				    ipm.ipGroupMemberIfIndex.o_bytes,
10484 				    OCTET_LENGTH);
10485 			}
10486 			ipm.ipGroupMemberIfIndex.o_length =
10487 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10488 
10489 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10490 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10491 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10492 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10493 			    (char *)&ipm, (int)sizeof (ipm))) {
10494 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10495 				    "failed to allocate %u bytes\n",
10496 				    (uint_t)sizeof (ipm)));
10497 			}
10498 		}
10499 		rw_exit(&ill->ill_mcast_lock);
10500 		ill_refrele(ill);
10501 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10502 	}
10503 	rw_exit(&ipst->ips_ill_g_lock);
10504 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10505 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10506 	    (int)optp->level, (int)optp->name, (int)optp->len));
10507 	qreply(q, mpctl);
10508 	return (mp2ctl);
10509 }
10510 
10511 /* IPv6 multicast group membership. */
10512 static mblk_t *
10513 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10514 {
10515 	struct opthdr		*optp;
10516 	mblk_t			*mp2ctl;
10517 	ill_t			*ill;
10518 	ilm_t			*ilm;
10519 	ipv6_member_t		ipm6;
10520 	mblk_t			*mp_tail = NULL;
10521 	ill_walk_context_t	ctx;
10522 	zoneid_t		zoneid;
10523 
10524 	/*
10525 	 * make a copy of the original message
10526 	 */
10527 	mp2ctl = copymsg(mpctl);
10528 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10529 
10530 	/* ip6GroupMember table */
10531 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10532 	optp->level = MIB2_IP6;
10533 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10534 
10535 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10536 	ill = ILL_START_WALK_V6(&ctx, ipst);
10537 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10538 		/* Make sure the ill isn't going away. */
10539 		if (!ill_check_and_refhold(ill))
10540 			continue;
10541 		rw_exit(&ipst->ips_ill_g_lock);
10542 		/*
10543 		 * Normally we don't have any members on under IPMP interfaces.
10544 		 * We report them as a debugging aid.
10545 		 */
10546 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10547 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10548 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10549 			if (ilm->ilm_zoneid != zoneid &&
10550 			    ilm->ilm_zoneid != ALL_ZONES)
10551 				continue;	/* not this zone */
10552 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10553 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10554 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10555 			if (!snmp_append_data2(mpctl->b_cont,
10556 			    &mp_tail,
10557 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10558 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10559 				    "failed to allocate %u bytes\n",
10560 				    (uint_t)sizeof (ipm6)));
10561 			}
10562 		}
10563 		rw_exit(&ill->ill_mcast_lock);
10564 		ill_refrele(ill);
10565 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10566 	}
10567 	rw_exit(&ipst->ips_ill_g_lock);
10568 
10569 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10570 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10571 	    (int)optp->level, (int)optp->name, (int)optp->len));
10572 	qreply(q, mpctl);
10573 	return (mp2ctl);
10574 }
10575 
10576 /* IP multicast filtered sources */
10577 static mblk_t *
10578 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10579 {
10580 	struct opthdr		*optp;
10581 	mblk_t			*mp2ctl;
10582 	ill_t			*ill;
10583 	ipif_t			*ipif;
10584 	ilm_t			*ilm;
10585 	ip_grpsrc_t		ips;
10586 	mblk_t			*mp_tail = NULL;
10587 	ill_walk_context_t	ctx;
10588 	zoneid_t		zoneid;
10589 	int			i;
10590 	slist_t			*sl;
10591 
10592 	/*
10593 	 * make a copy of the original message
10594 	 */
10595 	mp2ctl = copymsg(mpctl);
10596 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10597 
10598 	/* ipGroupSource table */
10599 	optp = (struct opthdr *)&mpctl->b_rptr[
10600 	    sizeof (struct T_optmgmt_ack)];
10601 	optp->level = MIB2_IP;
10602 	optp->name = EXPER_IP_GROUP_SOURCES;
10603 
10604 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10605 	ill = ILL_START_WALK_V4(&ctx, ipst);
10606 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10607 		/* Make sure the ill isn't going away. */
10608 		if (!ill_check_and_refhold(ill))
10609 			continue;
10610 		rw_exit(&ipst->ips_ill_g_lock);
10611 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10612 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10613 			sl = ilm->ilm_filter;
10614 			if (ilm->ilm_zoneid != zoneid &&
10615 			    ilm->ilm_zoneid != ALL_ZONES)
10616 				continue;
10617 			if (SLIST_IS_EMPTY(sl))
10618 				continue;
10619 
10620 			/* Is there an ipif for ilm_ifaddr? */
10621 			for (ipif = ill->ill_ipif; ipif != NULL;
10622 			    ipif = ipif->ipif_next) {
10623 				if (!IPIF_IS_CONDEMNED(ipif) &&
10624 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10625 				    ilm->ilm_ifaddr != INADDR_ANY)
10626 					break;
10627 			}
10628 			if (ipif != NULL) {
10629 				ipif_get_name(ipif,
10630 				    ips.ipGroupSourceIfIndex.o_bytes,
10631 				    OCTET_LENGTH);
10632 			} else {
10633 				ill_get_name(ill,
10634 				    ips.ipGroupSourceIfIndex.o_bytes,
10635 				    OCTET_LENGTH);
10636 			}
10637 			ips.ipGroupSourceIfIndex.o_length =
10638 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10639 
10640 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10641 			for (i = 0; i < sl->sl_numsrc; i++) {
10642 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10643 					continue;
10644 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10645 				    ips.ipGroupSourceAddress);
10646 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10647 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10648 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10649 					    " failed to allocate %u bytes\n",
10650 					    (uint_t)sizeof (ips)));
10651 				}
10652 			}
10653 		}
10654 		rw_exit(&ill->ill_mcast_lock);
10655 		ill_refrele(ill);
10656 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10657 	}
10658 	rw_exit(&ipst->ips_ill_g_lock);
10659 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10660 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10661 	    (int)optp->level, (int)optp->name, (int)optp->len));
10662 	qreply(q, mpctl);
10663 	return (mp2ctl);
10664 }
10665 
10666 /* IPv6 multicast filtered sources. */
10667 static mblk_t *
10668 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10669 {
10670 	struct opthdr		*optp;
10671 	mblk_t			*mp2ctl;
10672 	ill_t			*ill;
10673 	ilm_t			*ilm;
10674 	ipv6_grpsrc_t		ips6;
10675 	mblk_t			*mp_tail = NULL;
10676 	ill_walk_context_t	ctx;
10677 	zoneid_t		zoneid;
10678 	int			i;
10679 	slist_t			*sl;
10680 
10681 	/*
10682 	 * make a copy of the original message
10683 	 */
10684 	mp2ctl = copymsg(mpctl);
10685 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10686 
10687 	/* ip6GroupMember table */
10688 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10689 	optp->level = MIB2_IP6;
10690 	optp->name = EXPER_IP6_GROUP_SOURCES;
10691 
10692 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10693 	ill = ILL_START_WALK_V6(&ctx, ipst);
10694 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10695 		/* Make sure the ill isn't going away. */
10696 		if (!ill_check_and_refhold(ill))
10697 			continue;
10698 		rw_exit(&ipst->ips_ill_g_lock);
10699 		/*
10700 		 * Normally we don't have any members on under IPMP interfaces.
10701 		 * We report them as a debugging aid.
10702 		 */
10703 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10704 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10705 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10706 			sl = ilm->ilm_filter;
10707 			if (ilm->ilm_zoneid != zoneid &&
10708 			    ilm->ilm_zoneid != ALL_ZONES)
10709 				continue;
10710 			if (SLIST_IS_EMPTY(sl))
10711 				continue;
10712 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10713 			for (i = 0; i < sl->sl_numsrc; i++) {
10714 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10715 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10716 				    (char *)&ips6, (int)sizeof (ips6))) {
10717 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10718 					    "group_src: failed to allocate "
10719 					    "%u bytes\n",
10720 					    (uint_t)sizeof (ips6)));
10721 				}
10722 			}
10723 		}
10724 		rw_exit(&ill->ill_mcast_lock);
10725 		ill_refrele(ill);
10726 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10727 	}
10728 	rw_exit(&ipst->ips_ill_g_lock);
10729 
10730 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10731 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10732 	    (int)optp->level, (int)optp->name, (int)optp->len));
10733 	qreply(q, mpctl);
10734 	return (mp2ctl);
10735 }
10736 
10737 /* Multicast routing virtual interface table. */
10738 static mblk_t *
10739 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10740 {
10741 	struct opthdr		*optp;
10742 	mblk_t			*mp2ctl;
10743 
10744 	/*
10745 	 * make a copy of the original message
10746 	 */
10747 	mp2ctl = copymsg(mpctl);
10748 
10749 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10750 	optp->level = EXPER_DVMRP;
10751 	optp->name = EXPER_DVMRP_VIF;
10752 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10753 		ip0dbg(("ip_mroute_vif: failed\n"));
10754 	}
10755 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10756 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10757 	    (int)optp->level, (int)optp->name, (int)optp->len));
10758 	qreply(q, mpctl);
10759 	return (mp2ctl);
10760 }
10761 
10762 /* Multicast routing table. */
10763 static mblk_t *
10764 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10765 {
10766 	struct opthdr		*optp;
10767 	mblk_t			*mp2ctl;
10768 
10769 	/*
10770 	 * make a copy of the original message
10771 	 */
10772 	mp2ctl = copymsg(mpctl);
10773 
10774 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10775 	optp->level = EXPER_DVMRP;
10776 	optp->name = EXPER_DVMRP_MRT;
10777 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10778 		ip0dbg(("ip_mroute_mrt: failed\n"));
10779 	}
10780 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10781 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10782 	    (int)optp->level, (int)optp->name, (int)optp->len));
10783 	qreply(q, mpctl);
10784 	return (mp2ctl);
10785 }
10786 
10787 /*
10788  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10789  * in one IRE walk.
10790  */
10791 static mblk_t *
10792 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10793     ip_stack_t *ipst)
10794 {
10795 	struct opthdr	*optp;
10796 	mblk_t		*mp2ctl;	/* Returned */
10797 	mblk_t		*mp3ctl;	/* nettomedia */
10798 	mblk_t		*mp4ctl;	/* routeattrs */
10799 	iproutedata_t	ird;
10800 	zoneid_t	zoneid;
10801 
10802 	/*
10803 	 * make copies of the original message
10804 	 *	- mp2ctl is returned unchanged to the caller for his use
10805 	 *	- mpctl is sent upstream as ipRouteEntryTable
10806 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10807 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10808 	 */
10809 	mp2ctl = copymsg(mpctl);
10810 	mp3ctl = copymsg(mpctl);
10811 	mp4ctl = copymsg(mpctl);
10812 	if (mp3ctl == NULL || mp4ctl == NULL) {
10813 		freemsg(mp4ctl);
10814 		freemsg(mp3ctl);
10815 		freemsg(mp2ctl);
10816 		freemsg(mpctl);
10817 		return (NULL);
10818 	}
10819 
10820 	bzero(&ird, sizeof (ird));
10821 
10822 	ird.ird_route.lp_head = mpctl->b_cont;
10823 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10824 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10825 	/*
10826 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10827 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10828 	 * intended a temporary solution until a proper MIB API is provided
10829 	 * that provides complete filtering/caller-opt-in.
10830 	 */
10831 	if (level == EXPER_IP_AND_ALL_IRES)
10832 		ird.ird_flags |= IRD_REPORT_ALL;
10833 
10834 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10835 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10836 
10837 	/* ipRouteEntryTable in mpctl */
10838 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10839 	optp->level = MIB2_IP;
10840 	optp->name = MIB2_IP_ROUTE;
10841 	optp->len = msgdsize(ird.ird_route.lp_head);
10842 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10843 	    (int)optp->level, (int)optp->name, (int)optp->len));
10844 	qreply(q, mpctl);
10845 
10846 	/* ipNetToMediaEntryTable in mp3ctl */
10847 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10848 
10849 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10850 	optp->level = MIB2_IP;
10851 	optp->name = MIB2_IP_MEDIA;
10852 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10853 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10854 	    (int)optp->level, (int)optp->name, (int)optp->len));
10855 	qreply(q, mp3ctl);
10856 
10857 	/* ipRouteAttributeTable in mp4ctl */
10858 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10859 	optp->level = MIB2_IP;
10860 	optp->name = EXPER_IP_RTATTR;
10861 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10862 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10863 	    (int)optp->level, (int)optp->name, (int)optp->len));
10864 	if (optp->len == 0)
10865 		freemsg(mp4ctl);
10866 	else
10867 		qreply(q, mp4ctl);
10868 
10869 	return (mp2ctl);
10870 }
10871 
10872 /*
10873  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10874  * ipv6NetToMediaEntryTable in an NDP walk.
10875  */
10876 static mblk_t *
10877 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10878     ip_stack_t *ipst)
10879 {
10880 	struct opthdr	*optp;
10881 	mblk_t		*mp2ctl;	/* Returned */
10882 	mblk_t		*mp3ctl;	/* nettomedia */
10883 	mblk_t		*mp4ctl;	/* routeattrs */
10884 	iproutedata_t	ird;
10885 	zoneid_t	zoneid;
10886 
10887 	/*
10888 	 * make copies of the original message
10889 	 *	- mp2ctl is returned unchanged to the caller for his use
10890 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10891 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10892 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10893 	 */
10894 	mp2ctl = copymsg(mpctl);
10895 	mp3ctl = copymsg(mpctl);
10896 	mp4ctl = copymsg(mpctl);
10897 	if (mp3ctl == NULL || mp4ctl == NULL) {
10898 		freemsg(mp4ctl);
10899 		freemsg(mp3ctl);
10900 		freemsg(mp2ctl);
10901 		freemsg(mpctl);
10902 		return (NULL);
10903 	}
10904 
10905 	bzero(&ird, sizeof (ird));
10906 
10907 	ird.ird_route.lp_head = mpctl->b_cont;
10908 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10909 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10910 	/*
10911 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10912 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10913 	 * intended a temporary solution until a proper MIB API is provided
10914 	 * that provides complete filtering/caller-opt-in.
10915 	 */
10916 	if (level == EXPER_IP_AND_ALL_IRES)
10917 		ird.ird_flags |= IRD_REPORT_ALL;
10918 
10919 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10920 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10921 
10922 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10923 	optp->level = MIB2_IP6;
10924 	optp->name = MIB2_IP6_ROUTE;
10925 	optp->len = msgdsize(ird.ird_route.lp_head);
10926 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10927 	    (int)optp->level, (int)optp->name, (int)optp->len));
10928 	qreply(q, mpctl);
10929 
10930 	/* ipv6NetToMediaEntryTable in mp3ctl */
10931 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10932 
10933 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10934 	optp->level = MIB2_IP6;
10935 	optp->name = MIB2_IP6_MEDIA;
10936 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10937 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10938 	    (int)optp->level, (int)optp->name, (int)optp->len));
10939 	qreply(q, mp3ctl);
10940 
10941 	/* ipv6RouteAttributeTable in mp4ctl */
10942 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10943 	optp->level = MIB2_IP6;
10944 	optp->name = EXPER_IP_RTATTR;
10945 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10946 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10947 	    (int)optp->level, (int)optp->name, (int)optp->len));
10948 	if (optp->len == 0)
10949 		freemsg(mp4ctl);
10950 	else
10951 		qreply(q, mp4ctl);
10952 
10953 	return (mp2ctl);
10954 }
10955 
10956 /*
10957  * IPv6 mib: One per ill
10958  */
10959 static mblk_t *
10960 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10961 {
10962 	struct opthdr		*optp;
10963 	mblk_t			*mp2ctl;
10964 	ill_t			*ill;
10965 	ill_walk_context_t	ctx;
10966 	mblk_t			*mp_tail = NULL;
10967 
10968 	/*
10969 	 * Make a copy of the original message
10970 	 */
10971 	mp2ctl = copymsg(mpctl);
10972 
10973 	/* fixed length IPv6 structure ... */
10974 
10975 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10976 	optp->level = MIB2_IP6;
10977 	optp->name = 0;
10978 	/* Include "unknown interface" ip6_mib */
10979 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10980 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10981 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10982 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10983 	    ipst->ips_ipv6_forward ? 1 : 2);
10984 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10985 	    ipst->ips_ipv6_def_hops);
10986 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10987 	    sizeof (mib2_ipIfStatsEntry_t));
10988 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10989 	    sizeof (mib2_ipv6AddrEntry_t));
10990 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10991 	    sizeof (mib2_ipv6RouteEntry_t));
10992 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10993 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10994 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10995 	    sizeof (ipv6_member_t));
10996 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10997 	    sizeof (ipv6_grpsrc_t));
10998 
10999 	/*
11000 	 * Synchronize 64- and 32-bit counters
11001 	 */
11002 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
11003 	    ipIfStatsHCInReceives);
11004 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
11005 	    ipIfStatsHCInDelivers);
11006 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
11007 	    ipIfStatsHCOutRequests);
11008 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
11009 	    ipIfStatsHCOutForwDatagrams);
11010 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
11011 	    ipIfStatsHCOutMcastPkts);
11012 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
11013 	    ipIfStatsHCInMcastPkts);
11014 
11015 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
11016 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
11017 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
11018 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
11019 	}
11020 
11021 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11022 	ill = ILL_START_WALK_V6(&ctx, ipst);
11023 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
11024 		ill->ill_ip_mib->ipIfStatsIfIndex =
11025 		    ill->ill_phyint->phyint_ifindex;
11026 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
11027 		    ipst->ips_ipv6_forward ? 1 : 2);
11028 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
11029 		    ill->ill_max_hops);
11030 
11031 		/*
11032 		 * Synchronize 64- and 32-bit counters
11033 		 */
11034 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
11035 		    ipIfStatsHCInReceives);
11036 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
11037 		    ipIfStatsHCInDelivers);
11038 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
11039 		    ipIfStatsHCOutRequests);
11040 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
11041 		    ipIfStatsHCOutForwDatagrams);
11042 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
11043 		    ipIfStatsHCOutMcastPkts);
11044 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
11045 		    ipIfStatsHCInMcastPkts);
11046 
11047 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
11048 		    (char *)ill->ill_ip_mib,
11049 		    (int)sizeof (*ill->ill_ip_mib))) {
11050 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
11051 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
11052 		}
11053 	}
11054 	rw_exit(&ipst->ips_ill_g_lock);
11055 
11056 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
11057 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
11058 	    (int)optp->level, (int)optp->name, (int)optp->len));
11059 	qreply(q, mpctl);
11060 	return (mp2ctl);
11061 }
11062 
11063 /*
11064  * ICMPv6 mib: One per ill
11065  */
11066 static mblk_t *
11067 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
11068 {
11069 	struct opthdr		*optp;
11070 	mblk_t			*mp2ctl;
11071 	ill_t			*ill;
11072 	ill_walk_context_t	ctx;
11073 	mblk_t			*mp_tail = NULL;
11074 	/*
11075 	 * Make a copy of the original message
11076 	 */
11077 	mp2ctl = copymsg(mpctl);
11078 
11079 	/* fixed length ICMPv6 structure ... */
11080 
11081 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
11082 	optp->level = MIB2_ICMP6;
11083 	optp->name = 0;
11084 	/* Include "unknown interface" icmp6_mib */
11085 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
11086 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
11087 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
11088 	    sizeof (mib2_ipv6IfIcmpEntry_t);
11089 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
11090 	    (char *)&ipst->ips_icmp6_mib,
11091 	    (int)sizeof (ipst->ips_icmp6_mib))) {
11092 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
11093 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
11094 	}
11095 
11096 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11097 	ill = ILL_START_WALK_V6(&ctx, ipst);
11098 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
11099 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
11100 		    ill->ill_phyint->phyint_ifindex;
11101 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
11102 		    (char *)ill->ill_icmp6_mib,
11103 		    (int)sizeof (*ill->ill_icmp6_mib))) {
11104 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
11105 			    "%u bytes\n",
11106 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
11107 		}
11108 	}
11109 	rw_exit(&ipst->ips_ill_g_lock);
11110 
11111 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
11112 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
11113 	    (int)optp->level, (int)optp->name, (int)optp->len));
11114 	qreply(q, mpctl);
11115 	return (mp2ctl);
11116 }
11117 
11118 /*
11119  * ire_walk routine to create both ipRouteEntryTable and
11120  * ipRouteAttributeTable in one IRE walk
11121  */
11122 static void
11123 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
11124 {
11125 	ill_t				*ill;
11126 	mib2_ipRouteEntry_t		*re;
11127 	mib2_ipAttributeEntry_t		iaes;
11128 	tsol_ire_gw_secattr_t		*attrp;
11129 	tsol_gc_t			*gc = NULL;
11130 	tsol_gcgrp_t			*gcgrp = NULL;
11131 	ip_stack_t			*ipst = ire->ire_ipst;
11132 
11133 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
11134 
11135 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11136 		if (ire->ire_testhidden)
11137 			return;
11138 		if (ire->ire_type & IRE_IF_CLONE)
11139 			return;
11140 	}
11141 
11142 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11143 		return;
11144 
11145 	if ((attrp = ire->ire_gw_secattr) != NULL) {
11146 		mutex_enter(&attrp->igsa_lock);
11147 		if ((gc = attrp->igsa_gc) != NULL) {
11148 			gcgrp = gc->gc_grp;
11149 			ASSERT(gcgrp != NULL);
11150 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11151 		}
11152 		mutex_exit(&attrp->igsa_lock);
11153 	}
11154 	/*
11155 	 * Return all IRE types for route table... let caller pick and choose
11156 	 */
11157 	re->ipRouteDest = ire->ire_addr;
11158 	ill = ire->ire_ill;
11159 	re->ipRouteIfIndex.o_length = 0;
11160 	if (ill != NULL) {
11161 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
11162 		re->ipRouteIfIndex.o_length =
11163 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
11164 	}
11165 	re->ipRouteMetric1 = -1;
11166 	re->ipRouteMetric2 = -1;
11167 	re->ipRouteMetric3 = -1;
11168 	re->ipRouteMetric4 = -1;
11169 
11170 	re->ipRouteNextHop = ire->ire_gateway_addr;
11171 	/* indirect(4), direct(3), or invalid(2) */
11172 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11173 		re->ipRouteType = 2;
11174 	else if (ire->ire_type & IRE_ONLINK)
11175 		re->ipRouteType = 3;
11176 	else
11177 		re->ipRouteType = 4;
11178 
11179 	re->ipRouteProto = -1;
11180 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
11181 	re->ipRouteMask = ire->ire_mask;
11182 	re->ipRouteMetric5 = -1;
11183 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11184 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
11185 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11186 
11187 	re->ipRouteInfo.re_frag_flag	= 0;
11188 	re->ipRouteInfo.re_rtt		= 0;
11189 	re->ipRouteInfo.re_src_addr	= 0;
11190 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
11191 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11192 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11193 	re->ipRouteInfo.re_flags	= ire->ire_flags;
11194 
11195 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11196 	if (ire->ire_type & IRE_INTERFACE) {
11197 		ire_t *child;
11198 
11199 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11200 		child = ire->ire_dep_children;
11201 		while (child != NULL) {
11202 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
11203 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11204 			child = child->ire_dep_sib_next;
11205 		}
11206 		rw_exit(&ipst->ips_ire_dep_lock);
11207 	}
11208 
11209 	if (ire->ire_flags & RTF_DYNAMIC) {
11210 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11211 	} else {
11212 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
11213 	}
11214 
11215 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11216 	    (char *)re, (int)sizeof (*re))) {
11217 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
11218 		    (uint_t)sizeof (*re)));
11219 	}
11220 
11221 	if (gc != NULL) {
11222 		iaes.iae_routeidx = ird->ird_idx;
11223 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11224 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11225 
11226 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11227 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11228 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
11229 			    "bytes\n", (uint_t)sizeof (iaes)));
11230 		}
11231 	}
11232 
11233 	/* bump route index for next pass */
11234 	ird->ird_idx++;
11235 
11236 	kmem_free(re, sizeof (*re));
11237 	if (gcgrp != NULL)
11238 		rw_exit(&gcgrp->gcgrp_rwlock);
11239 }
11240 
11241 /*
11242  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
11243  */
11244 static void
11245 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
11246 {
11247 	ill_t				*ill;
11248 	mib2_ipv6RouteEntry_t		*re;
11249 	mib2_ipAttributeEntry_t		iaes;
11250 	tsol_ire_gw_secattr_t		*attrp;
11251 	tsol_gc_t			*gc = NULL;
11252 	tsol_gcgrp_t			*gcgrp = NULL;
11253 	ip_stack_t			*ipst = ire->ire_ipst;
11254 
11255 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
11256 
11257 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11258 		if (ire->ire_testhidden)
11259 			return;
11260 		if (ire->ire_type & IRE_IF_CLONE)
11261 			return;
11262 	}
11263 
11264 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11265 		return;
11266 
11267 	if ((attrp = ire->ire_gw_secattr) != NULL) {
11268 		mutex_enter(&attrp->igsa_lock);
11269 		if ((gc = attrp->igsa_gc) != NULL) {
11270 			gcgrp = gc->gc_grp;
11271 			ASSERT(gcgrp != NULL);
11272 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11273 		}
11274 		mutex_exit(&attrp->igsa_lock);
11275 	}
11276 	/*
11277 	 * Return all IRE types for route table... let caller pick and choose
11278 	 */
11279 	re->ipv6RouteDest = ire->ire_addr_v6;
11280 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11281 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
11282 	re->ipv6RouteIfIndex.o_length = 0;
11283 	ill = ire->ire_ill;
11284 	if (ill != NULL) {
11285 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11286 		re->ipv6RouteIfIndex.o_length =
11287 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11288 	}
11289 
11290 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
11291 
11292 	mutex_enter(&ire->ire_lock);
11293 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11294 	mutex_exit(&ire->ire_lock);
11295 
11296 	/* remote(4), local(3), or discard(2) */
11297 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11298 		re->ipv6RouteType = 2;
11299 	else if (ire->ire_type & IRE_ONLINK)
11300 		re->ipv6RouteType = 3;
11301 	else
11302 		re->ipv6RouteType = 4;
11303 
11304 	re->ipv6RouteProtocol	= -1;
11305 	re->ipv6RoutePolicy	= 0;
11306 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
11307 	re->ipv6RouteNextHopRDI	= 0;
11308 	re->ipv6RouteWeight	= 0;
11309 	re->ipv6RouteMetric	= 0;
11310 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11311 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11312 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11313 
11314 	re->ipv6RouteInfo.re_frag_flag	= 0;
11315 	re->ipv6RouteInfo.re_rtt	= 0;
11316 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
11317 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11318 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11319 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
11320 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
11321 
11322 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11323 	if (ire->ire_type & IRE_INTERFACE) {
11324 		ire_t *child;
11325 
11326 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11327 		child = ire->ire_dep_children;
11328 		while (child != NULL) {
11329 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11330 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11331 			child = child->ire_dep_sib_next;
11332 		}
11333 		rw_exit(&ipst->ips_ire_dep_lock);
11334 	}
11335 	if (ire->ire_flags & RTF_DYNAMIC) {
11336 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11337 	} else {
11338 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
11339 	}
11340 
11341 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11342 	    (char *)re, (int)sizeof (*re))) {
11343 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11344 		    (uint_t)sizeof (*re)));
11345 	}
11346 
11347 	if (gc != NULL) {
11348 		iaes.iae_routeidx = ird->ird_idx;
11349 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11350 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11351 
11352 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11353 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11354 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11355 			    "bytes\n", (uint_t)sizeof (iaes)));
11356 		}
11357 	}
11358 
11359 	/* bump route index for next pass */
11360 	ird->ird_idx++;
11361 
11362 	kmem_free(re, sizeof (*re));
11363 	if (gcgrp != NULL)
11364 		rw_exit(&gcgrp->gcgrp_rwlock);
11365 }
11366 
11367 /*
11368  * ncec_walk routine to create ipv6NetToMediaEntryTable
11369  */
11370 static int
11371 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11372 {
11373 	ill_t				*ill;
11374 	mib2_ipv6NetToMediaEntry_t	ntme;
11375 
11376 	ill = ncec->ncec_ill;
11377 	/* skip arpce entries, and loopback ncec entries */
11378 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11379 		return (0);
11380 	/*
11381 	 * Neighbor cache entry attached to IRE with on-link
11382 	 * destination.
11383 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11384 	 */
11385 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11386 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11387 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11388 	if (ncec->ncec_lladdr != NULL) {
11389 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11390 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11391 	}
11392 	/*
11393 	 * Note: Returns ND_* states. Should be:
11394 	 * reachable(1), stale(2), delay(3), probe(4),
11395 	 * invalid(5), unknown(6)
11396 	 */
11397 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11398 	ntme.ipv6NetToMediaLastUpdated = 0;
11399 
11400 	/* other(1), dynamic(2), static(3), local(4) */
11401 	if (NCE_MYADDR(ncec)) {
11402 		ntme.ipv6NetToMediaType = 4;
11403 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11404 		ntme.ipv6NetToMediaType = 1; /* proxy */
11405 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11406 		ntme.ipv6NetToMediaType = 3;
11407 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11408 		ntme.ipv6NetToMediaType = 1;
11409 	} else {
11410 		ntme.ipv6NetToMediaType = 2;
11411 	}
11412 
11413 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11414 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11415 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11416 		    (uint_t)sizeof (ntme)));
11417 	}
11418 	return (0);
11419 }
11420 
11421 int
11422 nce2ace(ncec_t *ncec)
11423 {
11424 	int flags = 0;
11425 
11426 	if (NCE_ISREACHABLE(ncec))
11427 		flags |= ACE_F_RESOLVED;
11428 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11429 		flags |= ACE_F_AUTHORITY;
11430 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11431 		flags |= ACE_F_PUBLISH;
11432 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11433 		flags |= ACE_F_PERMANENT;
11434 	if (NCE_MYADDR(ncec))
11435 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11436 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11437 		flags |= ACE_F_UNVERIFIED;
11438 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11439 		flags |= ACE_F_AUTHORITY;
11440 	if (ncec->ncec_flags & NCE_F_DELAYED)
11441 		flags |= ACE_F_DELAYED;
11442 	return (flags);
11443 }
11444 
11445 /*
11446  * ncec_walk routine to create ipNetToMediaEntryTable
11447  */
11448 static int
11449 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11450 {
11451 	ill_t				*ill;
11452 	mib2_ipNetToMediaEntry_t	ntme;
11453 	const char			*name = "unknown";
11454 	ipaddr_t			ncec_addr;
11455 
11456 	ill = ncec->ncec_ill;
11457 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11458 	    ill->ill_net_type == IRE_LOOPBACK)
11459 		return (0);
11460 
11461 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11462 	name = ill->ill_name;
11463 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11464 	if (NCE_MYADDR(ncec)) {
11465 		ntme.ipNetToMediaType = 4;
11466 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11467 		ntme.ipNetToMediaType = 1;
11468 	} else {
11469 		ntme.ipNetToMediaType = 3;
11470 	}
11471 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11472 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11473 	    ntme.ipNetToMediaIfIndex.o_length);
11474 
11475 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11476 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11477 
11478 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11479 	ncec_addr = INADDR_BROADCAST;
11480 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11481 	    sizeof (ncec_addr));
11482 	/*
11483 	 * map all the flags to the ACE counterpart.
11484 	 */
11485 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11486 
11487 	ntme.ipNetToMediaPhysAddress.o_length =
11488 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11489 
11490 	if (!NCE_ISREACHABLE(ncec))
11491 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11492 	else {
11493 		if (ncec->ncec_lladdr != NULL) {
11494 			bcopy(ncec->ncec_lladdr,
11495 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11496 			    ntme.ipNetToMediaPhysAddress.o_length);
11497 		}
11498 	}
11499 
11500 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11501 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11502 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11503 		    (uint_t)sizeof (ntme)));
11504 	}
11505 	return (0);
11506 }
11507 
11508 /*
11509  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11510  */
11511 /* ARGSUSED */
11512 int
11513 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11514 {
11515 	switch (level) {
11516 	case MIB2_IP:
11517 	case MIB2_ICMP:
11518 		switch (name) {
11519 		default:
11520 			break;
11521 		}
11522 		return (1);
11523 	default:
11524 		return (1);
11525 	}
11526 }
11527 
11528 /*
11529  * When there exists both a 64- and 32-bit counter of a particular type
11530  * (i.e., InReceives), only the 64-bit counters are added.
11531  */
11532 void
11533 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11534 {
11535 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11536 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11537 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11538 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11539 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11540 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11541 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11542 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11543 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11544 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11545 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11546 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11547 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11548 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11549 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11550 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11551 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11552 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11553 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11554 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11555 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11556 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11557 	    o2->ipIfStatsInWrongIPVersion);
11558 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11559 	    o2->ipIfStatsInWrongIPVersion);
11560 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11561 	    o2->ipIfStatsOutSwitchIPVersion);
11562 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11563 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11564 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11565 	    o2->ipIfStatsHCInForwDatagrams);
11566 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11567 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11568 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11569 	    o2->ipIfStatsHCOutForwDatagrams);
11570 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11571 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11572 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11573 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11574 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11575 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11576 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11577 	    o2->ipIfStatsHCOutMcastOctets);
11578 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11579 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11580 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11581 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11582 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11583 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11584 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11585 }
11586 
11587 void
11588 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11589 {
11590 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11591 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11592 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11593 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11594 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11595 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11596 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11597 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11598 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11599 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11600 	    o2->ipv6IfIcmpInRouterSolicits);
11601 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11602 	    o2->ipv6IfIcmpInRouterAdvertisements);
11603 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11604 	    o2->ipv6IfIcmpInNeighborSolicits);
11605 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11606 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11607 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11608 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11609 	    o2->ipv6IfIcmpInGroupMembQueries);
11610 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11611 	    o2->ipv6IfIcmpInGroupMembResponses);
11612 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11613 	    o2->ipv6IfIcmpInGroupMembReductions);
11614 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11615 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11616 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11617 	    o2->ipv6IfIcmpOutDestUnreachs);
11618 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11619 	    o2->ipv6IfIcmpOutAdminProhibs);
11620 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11621 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11622 	    o2->ipv6IfIcmpOutParmProblems);
11623 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11624 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11625 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11626 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11627 	    o2->ipv6IfIcmpOutRouterSolicits);
11628 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11629 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11630 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11631 	    o2->ipv6IfIcmpOutNeighborSolicits);
11632 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11633 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11634 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11635 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11636 	    o2->ipv6IfIcmpOutGroupMembQueries);
11637 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11638 	    o2->ipv6IfIcmpOutGroupMembResponses);
11639 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11640 	    o2->ipv6IfIcmpOutGroupMembReductions);
11641 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11642 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11643 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11644 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11645 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11646 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11647 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11648 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11649 	    o2->ipv6IfIcmpInGroupMembTotal);
11650 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11651 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11652 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11653 	    o2->ipv6IfIcmpInGroupMembBadReports);
11654 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11655 	    o2->ipv6IfIcmpInGroupMembOurReports);
11656 }
11657 
11658 /*
11659  * Called before the options are updated to check if this packet will
11660  * be source routed from here.
11661  * This routine assumes that the options are well formed i.e. that they
11662  * have already been checked.
11663  */
11664 boolean_t
11665 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11666 {
11667 	ipoptp_t	opts;
11668 	uchar_t		*opt;
11669 	uint8_t		optval;
11670 	uint8_t		optlen;
11671 	ipaddr_t	dst;
11672 
11673 	if (IS_SIMPLE_IPH(ipha)) {
11674 		ip2dbg(("not source routed\n"));
11675 		return (B_FALSE);
11676 	}
11677 	dst = ipha->ipha_dst;
11678 	for (optval = ipoptp_first(&opts, ipha);
11679 	    optval != IPOPT_EOL;
11680 	    optval = ipoptp_next(&opts)) {
11681 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11682 		opt = opts.ipoptp_cur;
11683 		optlen = opts.ipoptp_len;
11684 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11685 		    optval, optlen));
11686 		switch (optval) {
11687 			uint32_t off;
11688 		case IPOPT_SSRR:
11689 		case IPOPT_LSRR:
11690 			/*
11691 			 * If dst is one of our addresses and there are some
11692 			 * entries left in the source route return (true).
11693 			 */
11694 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11695 				ip2dbg(("ip_source_routed: not next"
11696 				    " source route 0x%x\n",
11697 				    ntohl(dst)));
11698 				return (B_FALSE);
11699 			}
11700 			off = opt[IPOPT_OFFSET];
11701 			off--;
11702 			if (optlen < IP_ADDR_LEN ||
11703 			    off > optlen - IP_ADDR_LEN) {
11704 				/* End of source route */
11705 				ip1dbg(("ip_source_routed: end of SR\n"));
11706 				return (B_FALSE);
11707 			}
11708 			return (B_TRUE);
11709 		}
11710 	}
11711 	ip2dbg(("not source routed\n"));
11712 	return (B_FALSE);
11713 }
11714 
11715 /*
11716  * ip_unbind is called by the transports to remove a conn from
11717  * the fanout table.
11718  */
11719 void
11720 ip_unbind(conn_t *connp)
11721 {
11722 
11723 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11724 
11725 	if (is_system_labeled() && connp->conn_anon_port) {
11726 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11727 		    connp->conn_mlp_type, connp->conn_proto,
11728 		    ntohs(connp->conn_lport), B_FALSE);
11729 		connp->conn_anon_port = 0;
11730 	}
11731 	connp->conn_mlp_type = mlptSingle;
11732 
11733 	ipcl_hash_remove(connp);
11734 }
11735 
11736 /*
11737  * Used for deciding the MSS size for the upper layer. Thus
11738  * we need to check the outbound policy values in the conn.
11739  */
11740 int
11741 conn_ipsec_length(conn_t *connp)
11742 {
11743 	ipsec_latch_t *ipl;
11744 
11745 	ipl = connp->conn_latch;
11746 	if (ipl == NULL)
11747 		return (0);
11748 
11749 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11750 		return (0);
11751 
11752 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11753 }
11754 
11755 /*
11756  * Returns an estimate of the IPsec headers size. This is used if
11757  * we don't want to call into IPsec to get the exact size.
11758  */
11759 int
11760 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11761 {
11762 	ipsec_action_t *a;
11763 
11764 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11765 		return (0);
11766 
11767 	a = ixa->ixa_ipsec_action;
11768 	if (a == NULL) {
11769 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11770 		a = ixa->ixa_ipsec_policy->ipsp_act;
11771 	}
11772 	ASSERT(a != NULL);
11773 
11774 	return (a->ipa_ovhd);
11775 }
11776 
11777 /*
11778  * If there are any source route options, return the true final
11779  * destination. Otherwise, return the destination.
11780  */
11781 ipaddr_t
11782 ip_get_dst(ipha_t *ipha)
11783 {
11784 	ipoptp_t	opts;
11785 	uchar_t		*opt;
11786 	uint8_t		optval;
11787 	uint8_t		optlen;
11788 	ipaddr_t	dst;
11789 	uint32_t off;
11790 
11791 	dst = ipha->ipha_dst;
11792 
11793 	if (IS_SIMPLE_IPH(ipha))
11794 		return (dst);
11795 
11796 	for (optval = ipoptp_first(&opts, ipha);
11797 	    optval != IPOPT_EOL;
11798 	    optval = ipoptp_next(&opts)) {
11799 		opt = opts.ipoptp_cur;
11800 		optlen = opts.ipoptp_len;
11801 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11802 		switch (optval) {
11803 		case IPOPT_SSRR:
11804 		case IPOPT_LSRR:
11805 			off = opt[IPOPT_OFFSET];
11806 			/*
11807 			 * If one of the conditions is true, it means
11808 			 * end of options and dst already has the right
11809 			 * value.
11810 			 */
11811 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11812 				off = optlen - IP_ADDR_LEN;
11813 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11814 			}
11815 			return (dst);
11816 		default:
11817 			break;
11818 		}
11819 	}
11820 
11821 	return (dst);
11822 }
11823 
11824 /*
11825  * Outbound IP fragmentation routine.
11826  * Assumes the caller has checked whether or not fragmentation should
11827  * be allowed. Here we copy the DF bit from the header to all the generated
11828  * fragments.
11829  */
11830 int
11831 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11832     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11833     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11834 {
11835 	int		i1;
11836 	int		hdr_len;
11837 	mblk_t		*hdr_mp;
11838 	ipha_t		*ipha;
11839 	int		ip_data_end;
11840 	int		len;
11841 	mblk_t		*mp = mp_orig;
11842 	int		offset;
11843 	ill_t		*ill = nce->nce_ill;
11844 	ip_stack_t	*ipst = ill->ill_ipst;
11845 	mblk_t		*carve_mp;
11846 	uint32_t	frag_flag;
11847 	uint_t		priority = mp->b_band;
11848 	int		error = 0;
11849 
11850 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11851 
11852 	if (pkt_len != msgdsize(mp)) {
11853 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11854 		    pkt_len, msgdsize(mp)));
11855 		freemsg(mp);
11856 		return (EINVAL);
11857 	}
11858 
11859 	if (max_frag == 0) {
11860 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11861 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11862 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11863 		freemsg(mp);
11864 		return (EINVAL);
11865 	}
11866 
11867 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11868 	ipha = (ipha_t *)mp->b_rptr;
11869 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11870 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11871 
11872 	/*
11873 	 * Establish the starting offset.  May not be zero if we are fragging
11874 	 * a fragment that is being forwarded.
11875 	 */
11876 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11877 
11878 	/* TODO why is this test needed? */
11879 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11880 		/* TODO: notify ulp somehow */
11881 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11882 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11883 		freemsg(mp);
11884 		return (EINVAL);
11885 	}
11886 
11887 	hdr_len = IPH_HDR_LENGTH(ipha);
11888 	ipha->ipha_hdr_checksum = 0;
11889 
11890 	/*
11891 	 * Establish the number of bytes maximum per frag, after putting
11892 	 * in the header.
11893 	 */
11894 	len = (max_frag - hdr_len) & ~7;
11895 
11896 	/* Get a copy of the header for the trailing frags */
11897 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11898 	    mp);
11899 	if (hdr_mp == NULL) {
11900 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11901 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11902 		freemsg(mp);
11903 		return (ENOBUFS);
11904 	}
11905 
11906 	/* Store the starting offset, with the MoreFrags flag. */
11907 	i1 = offset | IPH_MF | frag_flag;
11908 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11909 
11910 	/* Establish the ending byte offset, based on the starting offset. */
11911 	offset <<= 3;
11912 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11913 
11914 	/* Store the length of the first fragment in the IP header. */
11915 	i1 = len + hdr_len;
11916 	ASSERT(i1 <= IP_MAXPACKET);
11917 	ipha->ipha_length = htons((uint16_t)i1);
11918 
11919 	/*
11920 	 * Compute the IP header checksum for the first frag.  We have to
11921 	 * watch out that we stop at the end of the header.
11922 	 */
11923 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11924 
11925 	/*
11926 	 * Now carve off the first frag.  Note that this will include the
11927 	 * original IP header.
11928 	 */
11929 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11930 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11931 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11932 		freeb(hdr_mp);
11933 		freemsg(mp_orig);
11934 		return (ENOBUFS);
11935 	}
11936 
11937 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11938 
11939 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11940 	    ixa_cookie);
11941 	if (error != 0 && error != EWOULDBLOCK) {
11942 		/* No point in sending the other fragments */
11943 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11944 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11945 		freeb(hdr_mp);
11946 		freemsg(mp_orig);
11947 		return (error);
11948 	}
11949 
11950 	/* No need to redo state machine in loop */
11951 	ixaflags &= ~IXAF_REACH_CONF;
11952 
11953 	/* Advance the offset to the second frag starting point. */
11954 	offset += len;
11955 	/*
11956 	 * Update hdr_len from the copied header - there might be less options
11957 	 * in the later fragments.
11958 	 */
11959 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11960 	/* Loop until done. */
11961 	for (;;) {
11962 		uint16_t	offset_and_flags;
11963 		uint16_t	ip_len;
11964 
11965 		if (ip_data_end - offset > len) {
11966 			/*
11967 			 * Carve off the appropriate amount from the original
11968 			 * datagram.
11969 			 */
11970 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11971 				mp = NULL;
11972 				break;
11973 			}
11974 			/*
11975 			 * More frags after this one.  Get another copy
11976 			 * of the header.
11977 			 */
11978 			if (carve_mp->b_datap->db_ref == 1 &&
11979 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11980 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11981 				/* Inline IP header */
11982 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11983 				    hdr_mp->b_rptr;
11984 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11985 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11986 				mp = carve_mp;
11987 			} else {
11988 				if (!(mp = copyb(hdr_mp))) {
11989 					freemsg(carve_mp);
11990 					break;
11991 				}
11992 				/* Get priority marking, if any. */
11993 				mp->b_band = priority;
11994 				mp->b_cont = carve_mp;
11995 			}
11996 			ipha = (ipha_t *)mp->b_rptr;
11997 			offset_and_flags = IPH_MF;
11998 		} else {
11999 			/*
12000 			 * Last frag.  Consume the header. Set len to
12001 			 * the length of this last piece.
12002 			 */
12003 			len = ip_data_end - offset;
12004 
12005 			/*
12006 			 * Carve off the appropriate amount from the original
12007 			 * datagram.
12008 			 */
12009 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
12010 				mp = NULL;
12011 				break;
12012 			}
12013 			if (carve_mp->b_datap->db_ref == 1 &&
12014 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
12015 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
12016 				/* Inline IP header */
12017 				carve_mp->b_rptr -= hdr_mp->b_wptr -
12018 				    hdr_mp->b_rptr;
12019 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
12020 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
12021 				mp = carve_mp;
12022 				freeb(hdr_mp);
12023 				hdr_mp = mp;
12024 			} else {
12025 				mp = hdr_mp;
12026 				/* Get priority marking, if any. */
12027 				mp->b_band = priority;
12028 				mp->b_cont = carve_mp;
12029 			}
12030 			ipha = (ipha_t *)mp->b_rptr;
12031 			/* A frag of a frag might have IPH_MF non-zero */
12032 			offset_and_flags =
12033 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
12034 			    IPH_MF;
12035 		}
12036 		offset_and_flags |= (uint16_t)(offset >> 3);
12037 		offset_and_flags |= (uint16_t)frag_flag;
12038 		/* Store the offset and flags in the IP header. */
12039 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
12040 
12041 		/* Store the length in the IP header. */
12042 		ip_len = (uint16_t)(len + hdr_len);
12043 		ipha->ipha_length = htons(ip_len);
12044 
12045 		/*
12046 		 * Set the IP header checksum.	Note that mp is just
12047 		 * the header, so this is easy to pass to ip_csum.
12048 		 */
12049 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
12050 
12051 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
12052 
12053 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
12054 		    nolzid, ixa_cookie);
12055 		/* All done if we just consumed the hdr_mp. */
12056 		if (mp == hdr_mp) {
12057 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
12058 			return (error);
12059 		}
12060 		if (error != 0 && error != EWOULDBLOCK) {
12061 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
12062 			    mblk_t *, hdr_mp);
12063 			/* No point in sending the other fragments */
12064 			break;
12065 		}
12066 
12067 		/* Otherwise, advance and loop. */
12068 		offset += len;
12069 	}
12070 	/* Clean up following allocation failure. */
12071 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
12072 	ip_drop_output("FragFails: loop ended", NULL, ill);
12073 	if (mp != hdr_mp)
12074 		freeb(hdr_mp);
12075 	if (mp != mp_orig)
12076 		freemsg(mp_orig);
12077 	return (error);
12078 }
12079 
12080 /*
12081  * Copy the header plus those options which have the copy bit set
12082  */
12083 static mblk_t *
12084 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
12085     mblk_t *src)
12086 {
12087 	mblk_t	*mp;
12088 	uchar_t	*up;
12089 
12090 	/*
12091 	 * Quick check if we need to look for options without the copy bit
12092 	 * set
12093 	 */
12094 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
12095 	if (!mp)
12096 		return (mp);
12097 	mp->b_rptr += ipst->ips_ip_wroff_extra;
12098 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
12099 		bcopy(rptr, mp->b_rptr, hdr_len);
12100 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
12101 		return (mp);
12102 	}
12103 	up  = mp->b_rptr;
12104 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
12105 	up += IP_SIMPLE_HDR_LENGTH;
12106 	rptr += IP_SIMPLE_HDR_LENGTH;
12107 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
12108 	while (hdr_len > 0) {
12109 		uint32_t optval;
12110 		uint32_t optlen;
12111 
12112 		optval = *rptr;
12113 		if (optval == IPOPT_EOL)
12114 			break;
12115 		if (optval == IPOPT_NOP)
12116 			optlen = 1;
12117 		else
12118 			optlen = rptr[1];
12119 		if (optval & IPOPT_COPY) {
12120 			bcopy(rptr, up, optlen);
12121 			up += optlen;
12122 		}
12123 		rptr += optlen;
12124 		hdr_len -= optlen;
12125 	}
12126 	/*
12127 	 * Make sure that we drop an even number of words by filling
12128 	 * with EOL to the next word boundary.
12129 	 */
12130 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
12131 	    hdr_len & 0x3; hdr_len++)
12132 		*up++ = IPOPT_EOL;
12133 	mp->b_wptr = up;
12134 	/* Update header length */
12135 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
12136 	return (mp);
12137 }
12138 
12139 /*
12140  * Update any source route, record route, or timestamp options when
12141  * sending a packet back to ourselves.
12142  * Check that we are at end of strict source route.
12143  * The options have been sanity checked by ip_output_options().
12144  */
12145 void
12146 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
12147 {
12148 	ipoptp_t	opts;
12149 	uchar_t		*opt;
12150 	uint8_t		optval;
12151 	uint8_t		optlen;
12152 	ipaddr_t	dst;
12153 	uint32_t	ts;
12154 	timestruc_t	now;
12155 
12156 	for (optval = ipoptp_first(&opts, ipha);
12157 	    optval != IPOPT_EOL;
12158 	    optval = ipoptp_next(&opts)) {
12159 		opt = opts.ipoptp_cur;
12160 		optlen = opts.ipoptp_len;
12161 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
12162 		switch (optval) {
12163 			uint32_t off;
12164 		case IPOPT_SSRR:
12165 		case IPOPT_LSRR:
12166 			off = opt[IPOPT_OFFSET];
12167 			off--;
12168 			if (optlen < IP_ADDR_LEN ||
12169 			    off > optlen - IP_ADDR_LEN) {
12170 				/* End of source route */
12171 				break;
12172 			}
12173 			/*
12174 			 * This will only happen if two consecutive entries
12175 			 * in the source route contains our address or if
12176 			 * it is a packet with a loose source route which
12177 			 * reaches us before consuming the whole source route
12178 			 */
12179 
12180 			if (optval == IPOPT_SSRR) {
12181 				return;
12182 			}
12183 			/*
12184 			 * Hack: instead of dropping the packet truncate the
12185 			 * source route to what has been used by filling the
12186 			 * rest with IPOPT_NOP.
12187 			 */
12188 			opt[IPOPT_OLEN] = (uint8_t)off;
12189 			while (off < optlen) {
12190 				opt[off++] = IPOPT_NOP;
12191 			}
12192 			break;
12193 		case IPOPT_RR:
12194 			off = opt[IPOPT_OFFSET];
12195 			off--;
12196 			if (optlen < IP_ADDR_LEN ||
12197 			    off > optlen - IP_ADDR_LEN) {
12198 				/* No more room - ignore */
12199 				ip1dbg((
12200 				    "ip_output_local_options: end of RR\n"));
12201 				break;
12202 			}
12203 			dst = htonl(INADDR_LOOPBACK);
12204 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12205 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12206 			break;
12207 		case IPOPT_TS:
12208 			/* Insert timestamp if there is romm */
12209 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12210 			case IPOPT_TS_TSONLY:
12211 				off = IPOPT_TS_TIMELEN;
12212 				break;
12213 			case IPOPT_TS_PRESPEC:
12214 			case IPOPT_TS_PRESPEC_RFC791:
12215 				/* Verify that the address matched */
12216 				off = opt[IPOPT_OFFSET] - 1;
12217 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
12218 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
12219 					/* Not for us */
12220 					break;
12221 				}
12222 				/* FALLTHRU */
12223 			case IPOPT_TS_TSANDADDR:
12224 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12225 				break;
12226 			default:
12227 				/*
12228 				 * ip_*put_options should have already
12229 				 * dropped this packet.
12230 				 */
12231 				cmn_err(CE_PANIC, "ip_output_local_options: "
12232 				    "unknown IT - bug in ip_output_options?\n");
12233 				return;	/* Keep "lint" happy */
12234 			}
12235 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
12236 				/* Increase overflow counter */
12237 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
12238 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
12239 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
12240 				    (off << 4);
12241 				break;
12242 			}
12243 			off = opt[IPOPT_OFFSET] - 1;
12244 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12245 			case IPOPT_TS_PRESPEC:
12246 			case IPOPT_TS_PRESPEC_RFC791:
12247 			case IPOPT_TS_TSANDADDR:
12248 				dst = htonl(INADDR_LOOPBACK);
12249 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12250 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12251 				/* FALLTHRU */
12252 			case IPOPT_TS_TSONLY:
12253 				off = opt[IPOPT_OFFSET] - 1;
12254 				/* Compute # of milliseconds since midnight */
12255 				gethrestime(&now);
12256 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
12257 				    now.tv_nsec / (NANOSEC / MILLISEC);
12258 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
12259 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
12260 				break;
12261 			}
12262 			break;
12263 		}
12264 	}
12265 }
12266 
12267 /*
12268  * Prepend an M_DATA fastpath header, and if none present prepend a
12269  * DL_UNITDATA_REQ. Frees the mblk on failure.
12270  *
12271  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12272  * If there is a change to them, the nce will be deleted (condemned) and
12273  * a new nce_t will be created when packets are sent. Thus we need no locks
12274  * to access those fields.
12275  *
12276  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12277  * we place b_band in dl_priority.dl_max.
12278  */
12279 static mblk_t *
12280 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12281 {
12282 	uint_t	hlen;
12283 	mblk_t *mp1;
12284 	uint_t	priority;
12285 	uchar_t *rptr;
12286 
12287 	rptr = mp->b_rptr;
12288 
12289 	ASSERT(DB_TYPE(mp) == M_DATA);
12290 	priority = mp->b_band;
12291 
12292 	ASSERT(nce != NULL);
12293 	if ((mp1 = nce->nce_fp_mp) != NULL) {
12294 		hlen = MBLKL(mp1);
12295 		/*
12296 		 * Check if we have enough room to prepend fastpath
12297 		 * header
12298 		 */
12299 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12300 			rptr -= hlen;
12301 			bcopy(mp1->b_rptr, rptr, hlen);
12302 			/*
12303 			 * Set the b_rptr to the start of the link layer
12304 			 * header
12305 			 */
12306 			mp->b_rptr = rptr;
12307 			return (mp);
12308 		}
12309 		mp1 = copyb(mp1);
12310 		if (mp1 == NULL) {
12311 			ill_t *ill = nce->nce_ill;
12312 
12313 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12314 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12315 			freemsg(mp);
12316 			return (NULL);
12317 		}
12318 		mp1->b_band = priority;
12319 		mp1->b_cont = mp;
12320 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12321 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12322 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12323 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12324 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12325 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12326 		/*
12327 		 * XXX disable ICK_VALID and compute checksum
12328 		 * here; can happen if nce_fp_mp changes and
12329 		 * it can't be copied now due to insufficient
12330 		 * space. (unlikely, fp mp can change, but it
12331 		 * does not increase in length)
12332 		 */
12333 		return (mp1);
12334 	}
12335 	mp1 = copyb(nce->nce_dlur_mp);
12336 
12337 	if (mp1 == NULL) {
12338 		ill_t *ill = nce->nce_ill;
12339 
12340 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12341 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12342 		freemsg(mp);
12343 		return (NULL);
12344 	}
12345 	mp1->b_cont = mp;
12346 	if (priority != 0) {
12347 		mp1->b_band = priority;
12348 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12349 		    priority;
12350 	}
12351 	return (mp1);
12352 #undef rptr
12353 }
12354 
12355 /*
12356  * Finish the outbound IPsec processing. This function is called from
12357  * ipsec_out_process() if the IPsec packet was processed
12358  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12359  * asynchronously.
12360  *
12361  * This is common to IPv4 and IPv6.
12362  */
12363 int
12364 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12365 {
12366 	iaflags_t	ixaflags = ixa->ixa_flags;
12367 	uint_t		pktlen;
12368 
12369 
12370 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12371 	if (ixaflags & IXAF_IS_IPV4) {
12372 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12373 
12374 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12375 		pktlen = ntohs(ipha->ipha_length);
12376 	} else {
12377 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12378 
12379 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12380 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12381 	}
12382 
12383 	/*
12384 	 * We release any hard reference on the SAs here to make
12385 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12386 	 * on the SAs.
12387 	 * If in the future we want the hard latching of the SAs in the
12388 	 * ip_xmit_attr_t then we should remove this.
12389 	 */
12390 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12391 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12392 		ixa->ixa_ipsec_esp_sa = NULL;
12393 	}
12394 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12395 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12396 		ixa->ixa_ipsec_ah_sa = NULL;
12397 	}
12398 
12399 	/* Do we need to fragment? */
12400 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12401 	    pktlen > ixa->ixa_fragsize) {
12402 		if (ixaflags & IXAF_IS_IPV4) {
12403 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12404 			/*
12405 			 * We check for the DF case in ipsec_out_process
12406 			 * hence this only handles the non-DF case.
12407 			 */
12408 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12409 			    pktlen, ixa->ixa_fragsize,
12410 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12411 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12412 			    &ixa->ixa_cookie));
12413 		} else {
12414 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12415 			if (mp == NULL) {
12416 				/* MIB and ip_drop_output already done */
12417 				return (ENOMEM);
12418 			}
12419 			pktlen += sizeof (ip6_frag_t);
12420 			if (pktlen > ixa->ixa_fragsize) {
12421 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12422 				    ixa->ixa_flags, pktlen,
12423 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12424 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12425 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12426 			}
12427 		}
12428 	}
12429 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12430 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12431 	    ixa->ixa_no_loop_zoneid, NULL));
12432 }
12433 
12434 /*
12435  * Finish the inbound IPsec processing. This function is called from
12436  * ipsec_out_process() if the IPsec packet was processed
12437  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12438  * asynchronously.
12439  *
12440  * This is common to IPv4 and IPv6.
12441  */
12442 void
12443 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12444 {
12445 	iaflags_t	iraflags = ira->ira_flags;
12446 
12447 	/* Length might have changed */
12448 	if (iraflags & IRAF_IS_IPV4) {
12449 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12450 
12451 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12452 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12453 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12454 		ira->ira_protocol = ipha->ipha_protocol;
12455 
12456 		ip_fanout_v4(mp, ipha, ira);
12457 	} else {
12458 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12459 		uint8_t		*nexthdrp;
12460 
12461 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12462 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12463 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12464 		    &nexthdrp)) {
12465 			/* Malformed packet */
12466 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12467 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12468 			freemsg(mp);
12469 			return;
12470 		}
12471 		ira->ira_protocol = *nexthdrp;
12472 		ip_fanout_v6(mp, ip6h, ira);
12473 	}
12474 }
12475 
12476 /*
12477  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12478  *
12479  * If this function returns B_TRUE, the requested SA's have been filled
12480  * into the ixa_ipsec_*_sa pointers.
12481  *
12482  * If the function returns B_FALSE, the packet has been "consumed", most
12483  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12484  *
12485  * The SA references created by the protocol-specific "select"
12486  * function will be released in ip_output_post_ipsec.
12487  */
12488 static boolean_t
12489 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12490 {
12491 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12492 	ipsec_policy_t *pp;
12493 	ipsec_action_t *ap;
12494 
12495 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12496 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12497 	    (ixa->ixa_ipsec_action != NULL));
12498 
12499 	ap = ixa->ixa_ipsec_action;
12500 	if (ap == NULL) {
12501 		pp = ixa->ixa_ipsec_policy;
12502 		ASSERT(pp != NULL);
12503 		ap = pp->ipsp_act;
12504 		ASSERT(ap != NULL);
12505 	}
12506 
12507 	/*
12508 	 * We have an action.  now, let's select SA's.
12509 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12510 	 * be cached in the conn_t.
12511 	 */
12512 	if (ap->ipa_want_esp) {
12513 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12514 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12515 			    IPPROTO_ESP);
12516 		}
12517 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12518 	}
12519 
12520 	if (ap->ipa_want_ah) {
12521 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12522 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12523 			    IPPROTO_AH);
12524 		}
12525 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12526 		/*
12527 		 * The ESP and AH processing order needs to be preserved
12528 		 * when both protocols are required (ESP should be applied
12529 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12530 		 * when both ESP and AH are required, and an AH ACQUIRE
12531 		 * is needed.
12532 		 */
12533 		if (ap->ipa_want_esp && need_ah_acquire)
12534 			need_esp_acquire = B_TRUE;
12535 	}
12536 
12537 	/*
12538 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12539 	 * Release SAs that got referenced, but will not be used until we
12540 	 * acquire _all_ of the SAs we need.
12541 	 */
12542 	if (need_ah_acquire || need_esp_acquire) {
12543 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12544 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12545 			ixa->ixa_ipsec_ah_sa = NULL;
12546 		}
12547 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12548 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12549 			ixa->ixa_ipsec_esp_sa = NULL;
12550 		}
12551 
12552 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12553 		return (B_FALSE);
12554 	}
12555 
12556 	return (B_TRUE);
12557 }
12558 
12559 /*
12560  * Handle IPsec output processing.
12561  * This function is only entered once for a given packet.
12562  * We try to do things synchronously, but if we need to have user-level
12563  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12564  * will be completed
12565  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12566  *  - when asynchronous ESP is done it will do AH
12567  *
12568  * In all cases we come back in ip_output_post_ipsec() to fragment and
12569  * send out the packet.
12570  */
12571 int
12572 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12573 {
12574 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12575 	ip_stack_t	*ipst = ixa->ixa_ipst;
12576 	ipsec_stack_t	*ipss;
12577 	ipsec_policy_t	*pp;
12578 	ipsec_action_t	*ap;
12579 
12580 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12581 
12582 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12583 	    (ixa->ixa_ipsec_action != NULL));
12584 
12585 	ipss = ipst->ips_netstack->netstack_ipsec;
12586 	if (!ipsec_loaded(ipss)) {
12587 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12588 		ip_drop_packet(mp, B_TRUE, ill,
12589 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12590 		    &ipss->ipsec_dropper);
12591 		return (ENOTSUP);
12592 	}
12593 
12594 	ap = ixa->ixa_ipsec_action;
12595 	if (ap == NULL) {
12596 		pp = ixa->ixa_ipsec_policy;
12597 		ASSERT(pp != NULL);
12598 		ap = pp->ipsp_act;
12599 		ASSERT(ap != NULL);
12600 	}
12601 
12602 	/* Handle explicit drop action and bypass. */
12603 	switch (ap->ipa_act.ipa_type) {
12604 	case IPSEC_ACT_DISCARD:
12605 	case IPSEC_ACT_REJECT:
12606 		ip_drop_packet(mp, B_FALSE, ill,
12607 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12608 		return (EHOSTUNREACH);	/* IPsec policy failure */
12609 	case IPSEC_ACT_BYPASS:
12610 		return (ip_output_post_ipsec(mp, ixa));
12611 	}
12612 
12613 	/*
12614 	 * The order of processing is first insert a IP header if needed.
12615 	 * Then insert the ESP header and then the AH header.
12616 	 */
12617 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12618 		/*
12619 		 * First get the outer IP header before sending
12620 		 * it to ESP.
12621 		 */
12622 		ipha_t *oipha, *iipha;
12623 		mblk_t *outer_mp, *inner_mp;
12624 
12625 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12626 			(void) mi_strlog(ill->ill_rq, 0,
12627 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12628 			    "ipsec_out_process: "
12629 			    "Self-Encapsulation failed: Out of memory\n");
12630 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12631 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12632 			freemsg(mp);
12633 			return (ENOBUFS);
12634 		}
12635 		inner_mp = mp;
12636 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12637 		oipha = (ipha_t *)outer_mp->b_rptr;
12638 		iipha = (ipha_t *)inner_mp->b_rptr;
12639 		*oipha = *iipha;
12640 		outer_mp->b_wptr += sizeof (ipha_t);
12641 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12642 		    sizeof (ipha_t));
12643 		oipha->ipha_protocol = IPPROTO_ENCAP;
12644 		oipha->ipha_version_and_hdr_length =
12645 		    IP_SIMPLE_HDR_VERSION;
12646 		oipha->ipha_hdr_checksum = 0;
12647 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12648 		outer_mp->b_cont = inner_mp;
12649 		mp = outer_mp;
12650 
12651 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12652 	}
12653 
12654 	/* If we need to wait for a SA then we can't return any errno */
12655 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12656 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12657 	    !ipsec_out_select_sa(mp, ixa))
12658 		return (0);
12659 
12660 	/*
12661 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12662 	 * to do the heavy lifting.
12663 	 */
12664 	if (ap->ipa_want_esp) {
12665 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12666 
12667 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12668 		if (mp == NULL) {
12669 			/*
12670 			 * Either it failed or is pending. In the former case
12671 			 * ipIfStatsInDiscards was increased.
12672 			 */
12673 			return (0);
12674 		}
12675 	}
12676 
12677 	if (ap->ipa_want_ah) {
12678 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12679 
12680 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12681 		if (mp == NULL) {
12682 			/*
12683 			 * Either it failed or is pending. In the former case
12684 			 * ipIfStatsInDiscards was increased.
12685 			 */
12686 			return (0);
12687 		}
12688 	}
12689 	/*
12690 	 * We are done with IPsec processing. Send it over
12691 	 * the wire.
12692 	 */
12693 	return (ip_output_post_ipsec(mp, ixa));
12694 }
12695 
12696 /*
12697  * ioctls that go through a down/up sequence may need to wait for the down
12698  * to complete. This involves waiting for the ire and ipif refcnts to go down
12699  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12700  */
12701 /* ARGSUSED */
12702 void
12703 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12704 {
12705 	struct iocblk *iocp;
12706 	mblk_t *mp1;
12707 	ip_ioctl_cmd_t *ipip;
12708 	int err;
12709 	sin_t	*sin;
12710 	struct lifreq *lifr;
12711 	struct ifreq *ifr;
12712 
12713 	iocp = (struct iocblk *)mp->b_rptr;
12714 	ASSERT(ipsq != NULL);
12715 	/* Existence of mp1 verified in ip_wput_nondata */
12716 	mp1 = mp->b_cont->b_cont;
12717 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12718 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12719 		/*
12720 		 * Special case where ipx_current_ipif is not set:
12721 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12722 		 * We are here as were not able to complete the operation in
12723 		 * ipif_set_values because we could not become exclusive on
12724 		 * the new ipsq.
12725 		 */
12726 		ill_t *ill = q->q_ptr;
12727 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12728 	}
12729 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12730 
12731 	if (ipip->ipi_cmd_type == IF_CMD) {
12732 		/* This a old style SIOC[GS]IF* command */
12733 		ifr = (struct ifreq *)mp1->b_rptr;
12734 		sin = (sin_t *)&ifr->ifr_addr;
12735 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12736 		/* This a new style SIOC[GS]LIF* command */
12737 		lifr = (struct lifreq *)mp1->b_rptr;
12738 		sin = (sin_t *)&lifr->lifr_addr;
12739 	} else {
12740 		sin = NULL;
12741 	}
12742 
12743 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12744 	    q, mp, ipip, mp1->b_rptr);
12745 
12746 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12747 	    int, ipip->ipi_cmd,
12748 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12749 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12750 
12751 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12752 }
12753 
12754 /*
12755  * ioctl processing
12756  *
12757  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12758  * the ioctl command in the ioctl tables, determines the copyin data size
12759  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12760  *
12761  * ioctl processing then continues when the M_IOCDATA makes its way down to
12762  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12763  * associated 'conn' is refheld till the end of the ioctl and the general
12764  * ioctl processing function ip_process_ioctl() is called to extract the
12765  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12766  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12767  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12768  * is used to extract the ioctl's arguments.
12769  *
12770  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12771  * so goes thru the serialization primitive ipsq_try_enter. Then the
12772  * appropriate function to handle the ioctl is called based on the entry in
12773  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12774  * which also refreleases the 'conn' that was refheld at the start of the
12775  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12776  *
12777  * Many exclusive ioctls go thru an internal down up sequence as part of
12778  * the operation. For example an attempt to change the IP address of an
12779  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12780  * does all the cleanup such as deleting all ires that use this address.
12781  * Then we need to wait till all references to the interface go away.
12782  */
12783 void
12784 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12785 {
12786 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12787 	ip_ioctl_cmd_t *ipip = arg;
12788 	ip_extract_func_t *extract_funcp;
12789 	cmd_info_t ci;
12790 	int err;
12791 	boolean_t entered_ipsq = B_FALSE;
12792 
12793 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12794 
12795 	if (ipip == NULL)
12796 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12797 
12798 	/*
12799 	 * SIOCLIFADDIF needs to go thru a special path since the
12800 	 * ill may not exist yet. This happens in the case of lo0
12801 	 * which is created using this ioctl.
12802 	 */
12803 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12804 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12805 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12806 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12807 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12808 		return;
12809 	}
12810 
12811 	ci.ci_ipif = NULL;
12812 	switch (ipip->ipi_cmd_type) {
12813 	case MISC_CMD:
12814 	case MSFILT_CMD:
12815 		/*
12816 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12817 		 */
12818 		if (ipip->ipi_cmd == IF_UNITSEL) {
12819 			/* ioctl comes down the ill */
12820 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12821 			ipif_refhold(ci.ci_ipif);
12822 		}
12823 		err = 0;
12824 		ci.ci_sin = NULL;
12825 		ci.ci_sin6 = NULL;
12826 		ci.ci_lifr = NULL;
12827 		extract_funcp = NULL;
12828 		break;
12829 
12830 	case IF_CMD:
12831 	case LIF_CMD:
12832 		extract_funcp = ip_extract_lifreq;
12833 		break;
12834 
12835 	case ARP_CMD:
12836 	case XARP_CMD:
12837 		extract_funcp = ip_extract_arpreq;
12838 		break;
12839 
12840 	default:
12841 		ASSERT(0);
12842 	}
12843 
12844 	if (extract_funcp != NULL) {
12845 		err = (*extract_funcp)(q, mp, ipip, &ci);
12846 		if (err != 0) {
12847 			DTRACE_PROBE4(ipif__ioctl,
12848 			    char *, "ip_process_ioctl finish err",
12849 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12850 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12851 			return;
12852 		}
12853 
12854 		/*
12855 		 * All of the extraction functions return a refheld ipif.
12856 		 */
12857 		ASSERT(ci.ci_ipif != NULL);
12858 	}
12859 
12860 	if (!(ipip->ipi_flags & IPI_WR)) {
12861 		/*
12862 		 * A return value of EINPROGRESS means the ioctl is
12863 		 * either queued and waiting for some reason or has
12864 		 * already completed.
12865 		 */
12866 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12867 		    ci.ci_lifr);
12868 		if (ci.ci_ipif != NULL) {
12869 			DTRACE_PROBE4(ipif__ioctl,
12870 			    char *, "ip_process_ioctl finish RD",
12871 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12872 			    ipif_t *, ci.ci_ipif);
12873 			ipif_refrele(ci.ci_ipif);
12874 		} else {
12875 			DTRACE_PROBE4(ipif__ioctl,
12876 			    char *, "ip_process_ioctl finish RD",
12877 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12878 		}
12879 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12880 		return;
12881 	}
12882 
12883 	ASSERT(ci.ci_ipif != NULL);
12884 
12885 	/*
12886 	 * If ipsq is non-NULL, we are already being called exclusively
12887 	 */
12888 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12889 	if (ipsq == NULL) {
12890 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12891 		    NEW_OP, B_TRUE);
12892 		if (ipsq == NULL) {
12893 			ipif_refrele(ci.ci_ipif);
12894 			return;
12895 		}
12896 		entered_ipsq = B_TRUE;
12897 	}
12898 	/*
12899 	 * Release the ipif so that ipif_down and friends that wait for
12900 	 * references to go away are not misled about the current ipif_refcnt
12901 	 * values. We are writer so we can access the ipif even after releasing
12902 	 * the ipif.
12903 	 */
12904 	ipif_refrele(ci.ci_ipif);
12905 
12906 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12907 
12908 	/*
12909 	 * A return value of EINPROGRESS means the ioctl is
12910 	 * either queued and waiting for some reason or has
12911 	 * already completed.
12912 	 */
12913 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12914 
12915 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12916 	    int, ipip->ipi_cmd,
12917 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12918 	    ipif_t *, ci.ci_ipif);
12919 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12920 
12921 	if (entered_ipsq)
12922 		ipsq_exit(ipsq);
12923 }
12924 
12925 /*
12926  * Complete the ioctl. Typically ioctls use the mi package and need to
12927  * do mi_copyout/mi_copy_done.
12928  */
12929 void
12930 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12931 {
12932 	conn_t	*connp = NULL;
12933 
12934 	if (err == EINPROGRESS)
12935 		return;
12936 
12937 	if (CONN_Q(q)) {
12938 		connp = Q_TO_CONN(q);
12939 		ASSERT(connp->conn_ref >= 2);
12940 	}
12941 
12942 	switch (mode) {
12943 	case COPYOUT:
12944 		if (err == 0)
12945 			mi_copyout(q, mp);
12946 		else
12947 			mi_copy_done(q, mp, err);
12948 		break;
12949 
12950 	case NO_COPYOUT:
12951 		mi_copy_done(q, mp, err);
12952 		break;
12953 
12954 	default:
12955 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12956 		break;
12957 	}
12958 
12959 	/*
12960 	 * The conn refhold and ioctlref placed on the conn at the start of the
12961 	 * ioctl are released here.
12962 	 */
12963 	if (connp != NULL) {
12964 		CONN_DEC_IOCTLREF(connp);
12965 		CONN_OPER_PENDING_DONE(connp);
12966 	}
12967 
12968 	if (ipsq != NULL)
12969 		ipsq_current_finish(ipsq);
12970 }
12971 
12972 /* Handles all non data messages */
12973 void
12974 ip_wput_nondata(queue_t *q, mblk_t *mp)
12975 {
12976 	mblk_t		*mp1;
12977 	struct iocblk	*iocp;
12978 	ip_ioctl_cmd_t	*ipip;
12979 	conn_t		*connp;
12980 	cred_t		*cr;
12981 	char		*proto_str;
12982 
12983 	if (CONN_Q(q))
12984 		connp = Q_TO_CONN(q);
12985 	else
12986 		connp = NULL;
12987 
12988 	switch (DB_TYPE(mp)) {
12989 	case M_IOCTL:
12990 		/*
12991 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12992 		 * will arrange to copy in associated control structures.
12993 		 */
12994 		ip_sioctl_copyin_setup(q, mp);
12995 		return;
12996 	case M_IOCDATA:
12997 		/*
12998 		 * Ensure that this is associated with one of our trans-
12999 		 * parent ioctls.  If it's not ours, discard it if we're
13000 		 * running as a driver, or pass it on if we're a module.
13001 		 */
13002 		iocp = (struct iocblk *)mp->b_rptr;
13003 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
13004 		if (ipip == NULL) {
13005 			if (q->q_next == NULL) {
13006 				goto nak;
13007 			} else {
13008 				putnext(q, mp);
13009 			}
13010 			return;
13011 		}
13012 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
13013 			/*
13014 			 * The ioctl is one we recognise, but is not consumed
13015 			 * by IP as a module and we are a module, so we drop
13016 			 */
13017 			goto nak;
13018 		}
13019 
13020 		/* IOCTL continuation following copyin or copyout. */
13021 		if (mi_copy_state(q, mp, NULL) == -1) {
13022 			/*
13023 			 * The copy operation failed.  mi_copy_state already
13024 			 * cleaned up, so we're out of here.
13025 			 */
13026 			return;
13027 		}
13028 		/*
13029 		 * If we just completed a copy in, we become writer and
13030 		 * continue processing in ip_sioctl_copyin_done.  If it
13031 		 * was a copy out, we call mi_copyout again.  If there is
13032 		 * nothing more to copy out, it will complete the IOCTL.
13033 		 */
13034 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
13035 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
13036 				mi_copy_done(q, mp, EPROTO);
13037 				return;
13038 			}
13039 			/*
13040 			 * Check for cases that need more copying.  A return
13041 			 * value of 0 means a second copyin has been started,
13042 			 * so we return; a return value of 1 means no more
13043 			 * copying is needed, so we continue.
13044 			 */
13045 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
13046 			    MI_COPY_COUNT(mp) == 1) {
13047 				if (ip_copyin_msfilter(q, mp) == 0)
13048 					return;
13049 			}
13050 			/*
13051 			 * Refhold the conn, till the ioctl completes. This is
13052 			 * needed in case the ioctl ends up in the pending mp
13053 			 * list. Every mp in the ipx_pending_mp list must have
13054 			 * a refhold on the conn to resume processing. The
13055 			 * refhold is released when the ioctl completes
13056 			 * (whether normally or abnormally). An ioctlref is also
13057 			 * placed on the conn to prevent TCP from removing the
13058 			 * queue needed to send the ioctl reply back.
13059 			 * In all cases ip_ioctl_finish is called to finish
13060 			 * the ioctl and release the refholds.
13061 			 */
13062 			if (connp != NULL) {
13063 				/* This is not a reentry */
13064 				CONN_INC_REF(connp);
13065 				CONN_INC_IOCTLREF(connp);
13066 			} else {
13067 				if (!(ipip->ipi_flags & IPI_MODOK)) {
13068 					mi_copy_done(q, mp, EINVAL);
13069 					return;
13070 				}
13071 			}
13072 
13073 			ip_process_ioctl(NULL, q, mp, ipip);
13074 
13075 		} else {
13076 			mi_copyout(q, mp);
13077 		}
13078 		return;
13079 
13080 	case M_IOCNAK:
13081 		/*
13082 		 * The only way we could get here is if a resolver didn't like
13083 		 * an IOCTL we sent it.	 This shouldn't happen.
13084 		 */
13085 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13086 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
13087 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
13088 		freemsg(mp);
13089 		return;
13090 	case M_IOCACK:
13091 		/* /dev/ip shouldn't see this */
13092 		goto nak;
13093 	case M_FLUSH:
13094 		if (*mp->b_rptr & FLUSHW)
13095 			flushq(q, FLUSHALL);
13096 		if (q->q_next) {
13097 			putnext(q, mp);
13098 			return;
13099 		}
13100 		if (*mp->b_rptr & FLUSHR) {
13101 			*mp->b_rptr &= ~FLUSHW;
13102 			qreply(q, mp);
13103 			return;
13104 		}
13105 		freemsg(mp);
13106 		return;
13107 	case M_CTL:
13108 		break;
13109 	case M_PROTO:
13110 	case M_PCPROTO:
13111 		/*
13112 		 * The only PROTO messages we expect are SNMP-related.
13113 		 */
13114 		switch (((union T_primitives *)mp->b_rptr)->type) {
13115 		case T_SVR4_OPTMGMT_REQ:
13116 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
13117 			    "flags %x\n",
13118 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
13119 
13120 			if (connp == NULL) {
13121 				proto_str = "T_SVR4_OPTMGMT_REQ";
13122 				goto protonak;
13123 			}
13124 
13125 			/*
13126 			 * All Solaris components should pass a db_credp
13127 			 * for this TPI message, hence we ASSERT.
13128 			 * But in case there is some other M_PROTO that looks
13129 			 * like a TPI message sent by some other kernel
13130 			 * component, we check and return an error.
13131 			 */
13132 			cr = msg_getcred(mp, NULL);
13133 			ASSERT(cr != NULL);
13134 			if (cr == NULL) {
13135 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
13136 				if (mp != NULL)
13137 					qreply(q, mp);
13138 				return;
13139 			}
13140 
13141 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
13142 				proto_str = "Bad SNMPCOM request?";
13143 				goto protonak;
13144 			}
13145 			return;
13146 		default:
13147 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
13148 			    (int)*(uint_t *)mp->b_rptr));
13149 			freemsg(mp);
13150 			return;
13151 		}
13152 	default:
13153 		break;
13154 	}
13155 	if (q->q_next) {
13156 		putnext(q, mp);
13157 	} else
13158 		freemsg(mp);
13159 	return;
13160 
13161 nak:
13162 	iocp->ioc_error = EINVAL;
13163 	mp->b_datap->db_type = M_IOCNAK;
13164 	iocp->ioc_count = 0;
13165 	qreply(q, mp);
13166 	return;
13167 
13168 protonak:
13169 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
13170 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
13171 		qreply(q, mp);
13172 }
13173 
13174 /*
13175  * Process IP options in an outbound packet.  Verify that the nexthop in a
13176  * strict source route is onlink.
13177  * Returns non-zero if something fails in which case an ICMP error has been
13178  * sent and mp freed.
13179  *
13180  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
13181  */
13182 int
13183 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
13184 {
13185 	ipoptp_t	opts;
13186 	uchar_t		*opt;
13187 	uint8_t		optval;
13188 	uint8_t		optlen;
13189 	ipaddr_t	dst;
13190 	intptr_t	code = 0;
13191 	ire_t		*ire;
13192 	ip_stack_t	*ipst = ixa->ixa_ipst;
13193 	ip_recv_attr_t	iras;
13194 
13195 	ip2dbg(("ip_output_options\n"));
13196 
13197 	dst = ipha->ipha_dst;
13198 	for (optval = ipoptp_first(&opts, ipha);
13199 	    optval != IPOPT_EOL;
13200 	    optval = ipoptp_next(&opts)) {
13201 		opt = opts.ipoptp_cur;
13202 		optlen = opts.ipoptp_len;
13203 		ip2dbg(("ip_output_options: opt %d, len %d\n",
13204 		    optval, optlen));
13205 		switch (optval) {
13206 			uint32_t off;
13207 		case IPOPT_SSRR:
13208 		case IPOPT_LSRR:
13209 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13210 				ip1dbg((
13211 				    "ip_output_options: bad option offset\n"));
13212 				code = (char *)&opt[IPOPT_OLEN] -
13213 				    (char *)ipha;
13214 				goto param_prob;
13215 			}
13216 			off = opt[IPOPT_OFFSET];
13217 			ip1dbg(("ip_output_options: next hop 0x%x\n",
13218 			    ntohl(dst)));
13219 			/*
13220 			 * For strict: verify that dst is directly
13221 			 * reachable.
13222 			 */
13223 			if (optval == IPOPT_SSRR) {
13224 				ire = ire_ftable_lookup_v4(dst, 0, 0,
13225 				    IRE_IF_ALL, NULL, ALL_ZONES, ixa->ixa_tsl,
13226 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
13227 				    NULL);
13228 				if (ire == NULL) {
13229 					ip1dbg(("ip_output_options: SSRR not"
13230 					    " directly reachable: 0x%x\n",
13231 					    ntohl(dst)));
13232 					goto bad_src_route;
13233 				}
13234 				ire_refrele(ire);
13235 			}
13236 			break;
13237 		case IPOPT_RR:
13238 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13239 				ip1dbg((
13240 				    "ip_output_options: bad option offset\n"));
13241 				code = (char *)&opt[IPOPT_OLEN] -
13242 				    (char *)ipha;
13243 				goto param_prob;
13244 			}
13245 			break;
13246 		case IPOPT_TS:
13247 			/*
13248 			 * Verify that length >=5 and that there is either
13249 			 * room for another timestamp or that the overflow
13250 			 * counter is not maxed out.
13251 			 */
13252 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
13253 			if (optlen < IPOPT_MINLEN_IT) {
13254 				goto param_prob;
13255 			}
13256 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13257 				ip1dbg((
13258 				    "ip_output_options: bad option offset\n"));
13259 				code = (char *)&opt[IPOPT_OFFSET] -
13260 				    (char *)ipha;
13261 				goto param_prob;
13262 			}
13263 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13264 			case IPOPT_TS_TSONLY:
13265 				off = IPOPT_TS_TIMELEN;
13266 				break;
13267 			case IPOPT_TS_TSANDADDR:
13268 			case IPOPT_TS_PRESPEC:
13269 			case IPOPT_TS_PRESPEC_RFC791:
13270 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13271 				break;
13272 			default:
13273 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
13274 				    (char *)ipha;
13275 				goto param_prob;
13276 			}
13277 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13278 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13279 				/*
13280 				 * No room and the overflow counter is 15
13281 				 * already.
13282 				 */
13283 				goto param_prob;
13284 			}
13285 			break;
13286 		}
13287 	}
13288 
13289 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13290 		return (0);
13291 
13292 	ip1dbg(("ip_output_options: error processing IP options."));
13293 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13294 
13295 param_prob:
13296 	bzero(&iras, sizeof (iras));
13297 	iras.ira_ill = iras.ira_rill = ill;
13298 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13299 	iras.ira_rifindex = iras.ira_ruifindex;
13300 	iras.ira_flags = IRAF_IS_IPV4;
13301 
13302 	ip_drop_output("ip_output_options", mp, ill);
13303 	icmp_param_problem(mp, (uint8_t)code, &iras);
13304 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13305 	return (-1);
13306 
13307 bad_src_route:
13308 	bzero(&iras, sizeof (iras));
13309 	iras.ira_ill = iras.ira_rill = ill;
13310 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13311 	iras.ira_rifindex = iras.ira_ruifindex;
13312 	iras.ira_flags = IRAF_IS_IPV4;
13313 
13314 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13315 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13316 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13317 	return (-1);
13318 }
13319 
13320 /*
13321  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13322  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13323  * thru /etc/system.
13324  */
13325 #define	CONN_MAXDRAINCNT	64
13326 
13327 static void
13328 conn_drain_init(ip_stack_t *ipst)
13329 {
13330 	int i, j;
13331 	idl_tx_list_t *itl_tx;
13332 
13333 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13334 
13335 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
13336 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13337 		/*
13338 		 * Default value of the number of drainers is the
13339 		 * number of cpus, subject to maximum of 8 drainers.
13340 		 */
13341 		if (boot_max_ncpus != -1)
13342 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13343 		else
13344 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13345 	}
13346 
13347 	ipst->ips_idl_tx_list =
13348 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13349 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13350 		itl_tx =  &ipst->ips_idl_tx_list[i];
13351 		itl_tx->txl_drain_list =
13352 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13353 		    sizeof (idl_t), KM_SLEEP);
13354 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13355 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13356 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13357 			    MUTEX_DEFAULT, NULL);
13358 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13359 		}
13360 	}
13361 }
13362 
13363 static void
13364 conn_drain_fini(ip_stack_t *ipst)
13365 {
13366 	int i;
13367 	idl_tx_list_t *itl_tx;
13368 
13369 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13370 		itl_tx =  &ipst->ips_idl_tx_list[i];
13371 		kmem_free(itl_tx->txl_drain_list,
13372 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13373 	}
13374 	kmem_free(ipst->ips_idl_tx_list,
13375 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13376 	ipst->ips_idl_tx_list = NULL;
13377 }
13378 
13379 /*
13380  * Note: For an overview of how flowcontrol is handled in IP please see the
13381  * IP Flowcontrol notes at the top of this file.
13382  *
13383  * Flow control has blocked us from proceeding. Insert the given conn in one
13384  * of the conn drain lists. These conn wq's will be qenabled later on when
13385  * STREAMS flow control does a backenable. conn_walk_drain will enable
13386  * the first conn in each of these drain lists. Each of these qenabled conns
13387  * in turn enables the next in the list, after it runs, or when it closes,
13388  * thus sustaining the drain process.
13389  */
13390 void
13391 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13392 {
13393 	idl_t	*idl = tx_list->txl_drain_list;
13394 	uint_t	index;
13395 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13396 
13397 	mutex_enter(&connp->conn_lock);
13398 	if (connp->conn_state_flags & CONN_CLOSING) {
13399 		/*
13400 		 * The conn is closing as a result of which CONN_CLOSING
13401 		 * is set. Return.
13402 		 */
13403 		mutex_exit(&connp->conn_lock);
13404 		return;
13405 	} else if (connp->conn_idl == NULL) {
13406 		/*
13407 		 * Assign the next drain list round robin. We dont' use
13408 		 * a lock, and thus it may not be strictly round robin.
13409 		 * Atomicity of load/stores is enough to make sure that
13410 		 * conn_drain_list_index is always within bounds.
13411 		 */
13412 		index = tx_list->txl_drain_index;
13413 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13414 		connp->conn_idl = &tx_list->txl_drain_list[index];
13415 		index++;
13416 		if (index == ipst->ips_conn_drain_list_cnt)
13417 			index = 0;
13418 		tx_list->txl_drain_index = index;
13419 	}
13420 	mutex_exit(&connp->conn_lock);
13421 
13422 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
13423 	if ((connp->conn_drain_prev != NULL) ||
13424 	    (connp->conn_state_flags & CONN_CLOSING)) {
13425 		/*
13426 		 * The conn is already in the drain list, OR
13427 		 * the conn is closing. We need to check again for
13428 		 * the closing case again since close can happen
13429 		 * after we drop the conn_lock, and before we
13430 		 * acquire the CONN_DRAIN_LIST_LOCK.
13431 		 */
13432 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
13433 		return;
13434 	} else {
13435 		idl = connp->conn_idl;
13436 	}
13437 
13438 	/*
13439 	 * The conn is not in the drain list. Insert it at the
13440 	 * tail of the drain list. The drain list is circular
13441 	 * and doubly linked. idl_conn points to the 1st element
13442 	 * in the list.
13443 	 */
13444 	if (idl->idl_conn == NULL) {
13445 		idl->idl_conn = connp;
13446 		connp->conn_drain_next = connp;
13447 		connp->conn_drain_prev = connp;
13448 	} else {
13449 		conn_t *head = idl->idl_conn;
13450 
13451 		connp->conn_drain_next = head;
13452 		connp->conn_drain_prev = head->conn_drain_prev;
13453 		head->conn_drain_prev->conn_drain_next = connp;
13454 		head->conn_drain_prev = connp;
13455 	}
13456 	/*
13457 	 * For non streams based sockets assert flow control.
13458 	 */
13459 	conn_setqfull(connp, NULL);
13460 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
13461 }
13462 
13463 static void
13464 conn_idl_remove(conn_t *connp)
13465 {
13466 	idl_t *idl = connp->conn_idl;
13467 
13468 	if (idl != NULL) {
13469 		/*
13470 		 * Remove ourself from the drain list, if we did not do
13471 		 * a putq, or if the conn is closing.
13472 		 * Note: It is possible that q->q_first is non-null. It means
13473 		 * that these messages landed after we did a enableok() in
13474 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
13475 		 * service them.
13476 		 */
13477 		if (connp->conn_drain_next == connp) {
13478 			/* Singleton in the list */
13479 			ASSERT(connp->conn_drain_prev == connp);
13480 			idl->idl_conn = NULL;
13481 		} else {
13482 			connp->conn_drain_prev->conn_drain_next =
13483 			    connp->conn_drain_next;
13484 			connp->conn_drain_next->conn_drain_prev =
13485 			    connp->conn_drain_prev;
13486 			if (idl->idl_conn == connp)
13487 				idl->idl_conn = connp->conn_drain_next;
13488 		}
13489 	}
13490 	connp->conn_drain_next = NULL;
13491 	connp->conn_drain_prev = NULL;
13492 
13493 	conn_clrqfull(connp, NULL);
13494 	/*
13495 	 * For streams based sockets open up flow control.
13496 	 */
13497 	if (!IPCL_IS_NONSTR(connp))
13498 		enableok(connp->conn_wq);
13499 }
13500 
13501 /*
13502  * This conn is closing, and we are called from ip_close. OR
13503  * this conn is draining because flow-control on the ill has been relieved.
13504  *
13505  * We must also need to remove conn's on this idl from the list, and also
13506  * inform the sockfs upcalls about the change in flow-control.
13507  */
13508 static void
13509 conn_drain_tail(conn_t *connp, boolean_t closing)
13510 {
13511 	idl_t *idl;
13512 	conn_t *next_connp;
13513 
13514 	/*
13515 	 * connp->conn_idl is stable at this point, and no lock is needed
13516 	 * to check it. If we are called from ip_close, close has already
13517 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13518 	 * called us only because conn_idl is non-null. If we are called thru
13519 	 * service, conn_idl could be null, but it cannot change because
13520 	 * service is single-threaded per queue, and there cannot be another
13521 	 * instance of service trying to call conn_drain_insert on this conn
13522 	 * now.
13523 	 */
13524 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13525 
13526 	/*
13527 	 * If connp->conn_idl is null, the conn has not been inserted into any
13528 	 * drain list even once since creation of the conn. Just return.
13529 	 */
13530 	if (connp == NULL || connp->conn_idl == NULL)
13531 		return;
13532 
13533 	if (connp->conn_drain_prev == NULL) {
13534 		/* This conn is currently not in the drain list.  */
13535 		return;
13536 	}
13537 	idl = connp->conn_idl;
13538 	if (!closing) {
13539 		/*
13540 		 * This conn is the current drainer. If this is the last conn
13541 		 * in the drain list, we need to do more checks, in the 'if'
13542 		 * below. Otherwwise we need to just qenable the next conn,
13543 		 * to sustain the draining, and is handled in the 'else'
13544 		 * below.
13545 		 */
13546 		next_connp = connp->conn_drain_next;
13547 		while (next_connp != connp) {
13548 			conn_t *delconnp = next_connp;
13549 
13550 			next_connp = next_connp->conn_drain_next;
13551 			conn_idl_remove(delconnp);
13552 		}
13553 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13554 	}
13555 	conn_idl_remove(connp);
13556 
13557 }
13558 
13559 /*
13560  * Write service routine. Shared perimeter entry point.
13561  * The device queue's messages has fallen below the low water mark and STREAMS
13562  * has backenabled the ill_wq. Send sockfs notification about flow-control onx
13563  * each waiting conn.
13564  */
13565 void
13566 ip_wsrv(queue_t *q)
13567 {
13568 	ill_t	*ill;
13569 
13570 	ill = (ill_t *)q->q_ptr;
13571 	if (ill->ill_state_flags == 0) {
13572 		ip_stack_t *ipst = ill->ill_ipst;
13573 
13574 		/*
13575 		 * The device flow control has opened up.
13576 		 * Walk through conn drain lists and qenable the
13577 		 * first conn in each list. This makes sense only
13578 		 * if the stream is fully plumbed and setup.
13579 		 * Hence the ill_state_flags check above.
13580 		 */
13581 		ip1dbg(("ip_wsrv: walking\n"));
13582 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13583 		enableok(ill->ill_wq);
13584 	}
13585 }
13586 
13587 /*
13588  * Callback to disable flow control in IP.
13589  *
13590  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13591  * is enabled.
13592  *
13593  * When MAC_TX() is not able to send any more packets, dld sets its queue
13594  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13595  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13596  * function and wakes up corresponding mac worker threads, which in turn
13597  * calls this callback function, and disables flow control.
13598  */
13599 void
13600 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13601 {
13602 	ill_t *ill = (ill_t *)arg;
13603 	ip_stack_t *ipst = ill->ill_ipst;
13604 	idl_tx_list_t *idl_txl;
13605 
13606 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13607 	mutex_enter(&idl_txl->txl_lock);
13608 	/* add code to to set a flag to indicate idl_txl is enabled */
13609 	conn_walk_drain(ipst, idl_txl);
13610 	mutex_exit(&idl_txl->txl_lock);
13611 }
13612 
13613 /*
13614  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
13615  * of conns that need to be drained, check if drain is already in progress.
13616  * If so set the idl_repeat bit, indicating that the last conn in the list
13617  * needs to reinitiate the drain once again, for the list. If drain is not
13618  * in progress for the list, initiate the draining, by qenabling the 1st
13619  * conn in the list. The drain is self-sustaining, each qenabled conn will
13620  * in turn qenable the next conn, when it is done/blocked/closing.
13621  */
13622 static void
13623 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13624 {
13625 	int i;
13626 	idl_t *idl;
13627 
13628 	IP_STAT(ipst, ip_conn_walk_drain);
13629 
13630 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13631 		idl = &tx_list->txl_drain_list[i];
13632 		mutex_enter(&idl->idl_lock);
13633 		conn_drain_tail(idl->idl_conn, B_FALSE);
13634 		mutex_exit(&idl->idl_lock);
13635 	}
13636 }
13637 
13638 /*
13639  * Determine if the ill and multicast aspects of that packets
13640  * "matches" the conn.
13641  */
13642 boolean_t
13643 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13644 {
13645 	ill_t		*ill = ira->ira_rill;
13646 	zoneid_t	zoneid = ira->ira_zoneid;
13647 	uint_t		in_ifindex;
13648 	ipaddr_t	dst, src;
13649 
13650 	dst = ipha->ipha_dst;
13651 	src = ipha->ipha_src;
13652 
13653 	/*
13654 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13655 	 * unicast, broadcast and multicast reception to
13656 	 * conn_incoming_ifindex.
13657 	 * conn_wantpacket is called for unicast, broadcast and
13658 	 * multicast packets.
13659 	 */
13660 	in_ifindex = connp->conn_incoming_ifindex;
13661 
13662 	/* mpathd can bind to the under IPMP interface, which we allow */
13663 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13664 		if (!IS_UNDER_IPMP(ill))
13665 			return (B_FALSE);
13666 
13667 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13668 			return (B_FALSE);
13669 	}
13670 
13671 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13672 		return (B_FALSE);
13673 
13674 	if (!(ira->ira_flags & IRAF_MULTICAST))
13675 		return (B_TRUE);
13676 
13677 	if (connp->conn_multi_router) {
13678 		/* multicast packet and multicast router socket: send up */
13679 		return (B_TRUE);
13680 	}
13681 
13682 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13683 	    ipha->ipha_protocol == IPPROTO_RSVP)
13684 		return (B_TRUE);
13685 
13686 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13687 }
13688 
13689 void
13690 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13691 {
13692 	if (IPCL_IS_NONSTR(connp)) {
13693 		(*connp->conn_upcalls->su_txq_full)
13694 		    (connp->conn_upper_handle, B_TRUE);
13695 		if (flow_stopped != NULL)
13696 			*flow_stopped = B_TRUE;
13697 	} else {
13698 		queue_t *q = connp->conn_wq;
13699 
13700 		ASSERT(q != NULL);
13701 		if (!(q->q_flag & QFULL)) {
13702 			mutex_enter(QLOCK(q));
13703 			if (!(q->q_flag & QFULL)) {
13704 				/* still need to set QFULL */
13705 				q->q_flag |= QFULL;
13706 				/* set flow_stopped to true under QLOCK */
13707 				if (flow_stopped != NULL)
13708 					*flow_stopped = B_TRUE;
13709 				mutex_exit(QLOCK(q));
13710 			} else {
13711 				/* flow_stopped is left unchanged */
13712 				mutex_exit(QLOCK(q));
13713 			}
13714 		}
13715 	}
13716 }
13717 
13718 void
13719 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13720 {
13721 	if (IPCL_IS_NONSTR(connp)) {
13722 		(*connp->conn_upcalls->su_txq_full)
13723 		    (connp->conn_upper_handle, B_FALSE);
13724 		if (flow_stopped != NULL)
13725 			*flow_stopped = B_FALSE;
13726 	} else {
13727 		queue_t *q = connp->conn_wq;
13728 
13729 		ASSERT(q != NULL);
13730 		if (q->q_flag & QFULL) {
13731 			mutex_enter(QLOCK(q));
13732 			if (q->q_flag & QFULL) {
13733 				q->q_flag &= ~QFULL;
13734 				/* set flow_stopped to false under QLOCK */
13735 				if (flow_stopped != NULL)
13736 					*flow_stopped = B_FALSE;
13737 				mutex_exit(QLOCK(q));
13738 				if (q->q_flag & QWANTW)
13739 					qbackenable(q, 0);
13740 			} else {
13741 				/* flow_stopped is left unchanged */
13742 				mutex_exit(QLOCK(q));
13743 			}
13744 		}
13745 	}
13746 	connp->conn_direct_blocked = B_FALSE;
13747 }
13748 
13749 /*
13750  * Return the length in bytes of the IPv4 headers (base header, label, and
13751  * other IP options) that will be needed based on the
13752  * ip_pkt_t structure passed by the caller.
13753  *
13754  * The returned length does not include the length of the upper level
13755  * protocol (ULP) header.
13756  * The caller needs to check that the length doesn't exceed the max for IPv4.
13757  */
13758 int
13759 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13760 {
13761 	int len;
13762 
13763 	len = IP_SIMPLE_HDR_LENGTH;
13764 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13765 		ASSERT(ipp->ipp_label_len_v4 != 0);
13766 		/* We need to round up here */
13767 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13768 	}
13769 
13770 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13771 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13772 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13773 		len += ipp->ipp_ipv4_options_len;
13774 	}
13775 	return (len);
13776 }
13777 
13778 /*
13779  * All-purpose routine to build an IPv4 header with options based
13780  * on the abstract ip_pkt_t.
13781  *
13782  * The caller has to set the source and destination address as well as
13783  * ipha_length. The caller has to massage any source route and compensate
13784  * for the ULP pseudo-header checksum due to the source route.
13785  */
13786 void
13787 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13788     uint8_t protocol)
13789 {
13790 	ipha_t	*ipha = (ipha_t *)buf;
13791 	uint8_t *cp;
13792 
13793 	/* Initialize IPv4 header */
13794 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13795 	ipha->ipha_length = 0;	/* Caller will set later */
13796 	ipha->ipha_ident = 0;
13797 	ipha->ipha_fragment_offset_and_flags = 0;
13798 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13799 	ipha->ipha_protocol = protocol;
13800 	ipha->ipha_hdr_checksum = 0;
13801 
13802 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13803 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13804 		ipha->ipha_src = ipp->ipp_addr_v4;
13805 
13806 	cp = (uint8_t *)&ipha[1];
13807 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13808 		ASSERT(ipp->ipp_label_len_v4 != 0);
13809 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13810 		cp += ipp->ipp_label_len_v4;
13811 		/* We need to round up here */
13812 		while ((uintptr_t)cp & 0x3) {
13813 			*cp++ = IPOPT_NOP;
13814 		}
13815 	}
13816 
13817 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13818 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13819 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13820 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13821 		cp += ipp->ipp_ipv4_options_len;
13822 	}
13823 	ipha->ipha_version_and_hdr_length =
13824 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13825 
13826 	ASSERT((int)(cp - buf) == buf_len);
13827 }
13828 
13829 /* Allocate the private structure */
13830 static int
13831 ip_priv_alloc(void **bufp)
13832 {
13833 	void	*buf;
13834 
13835 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13836 		return (ENOMEM);
13837 
13838 	*bufp = buf;
13839 	return (0);
13840 }
13841 
13842 /* Function to delete the private structure */
13843 void
13844 ip_priv_free(void *buf)
13845 {
13846 	ASSERT(buf != NULL);
13847 	kmem_free(buf, sizeof (ip_priv_t));
13848 }
13849 
13850 /*
13851  * The entry point for IPPF processing.
13852  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13853  * routine just returns.
13854  *
13855  * When called, ip_process generates an ipp_packet_t structure
13856  * which holds the state information for this packet and invokes the
13857  * the classifier (via ipp_packet_process). The classification, depending on
13858  * configured filters, results in a list of actions for this packet. Invoking
13859  * an action may cause the packet to be dropped, in which case we return NULL.
13860  * proc indicates the callout position for
13861  * this packet and ill is the interface this packet arrived on or will leave
13862  * on (inbound and outbound resp.).
13863  *
13864  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13865  * on the ill corrsponding to the destination IP address.
13866  */
13867 mblk_t *
13868 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13869 {
13870 	ip_priv_t	*priv;
13871 	ipp_action_id_t	aid;
13872 	int		rc = 0;
13873 	ipp_packet_t	*pp;
13874 
13875 	/* If the classifier is not loaded, return  */
13876 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13877 		return (mp);
13878 	}
13879 
13880 	ASSERT(mp != NULL);
13881 
13882 	/* Allocate the packet structure */
13883 	rc = ipp_packet_alloc(&pp, "ip", aid);
13884 	if (rc != 0)
13885 		goto drop;
13886 
13887 	/* Allocate the private structure */
13888 	rc = ip_priv_alloc((void **)&priv);
13889 	if (rc != 0) {
13890 		ipp_packet_free(pp);
13891 		goto drop;
13892 	}
13893 	priv->proc = proc;
13894 	priv->ill_index = ill_get_upper_ifindex(rill);
13895 
13896 	ipp_packet_set_private(pp, priv, ip_priv_free);
13897 	ipp_packet_set_data(pp, mp);
13898 
13899 	/* Invoke the classifier */
13900 	rc = ipp_packet_process(&pp);
13901 	if (pp != NULL) {
13902 		mp = ipp_packet_get_data(pp);
13903 		ipp_packet_free(pp);
13904 		if (rc != 0)
13905 			goto drop;
13906 		return (mp);
13907 	} else {
13908 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13909 		mp = NULL;
13910 	}
13911 drop:
13912 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13913 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13914 		ip_drop_input("ip_process", mp, ill);
13915 	} else {
13916 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13917 		ip_drop_output("ip_process", mp, ill);
13918 	}
13919 	freemsg(mp);
13920 	return (NULL);
13921 }
13922 
13923 /*
13924  * Propagate a multicast group membership operation (add/drop) on
13925  * all the interfaces crossed by the related multirt routes.
13926  * The call is considered successful if the operation succeeds
13927  * on at least one interface.
13928  *
13929  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13930  * multicast addresses with the ire argument being the first one.
13931  * We walk the bucket to find all the of those.
13932  *
13933  * Common to IPv4 and IPv6.
13934  */
13935 static int
13936 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13937     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13938     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13939     mcast_record_t fmode, const in6_addr_t *v6src)
13940 {
13941 	ire_t		*ire_gw;
13942 	irb_t		*irb;
13943 	int		ifindex;
13944 	int		error = 0;
13945 	int		result;
13946 	ip_stack_t	*ipst = ire->ire_ipst;
13947 	ipaddr_t	group;
13948 	boolean_t	isv6;
13949 	int		match_flags;
13950 
13951 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13952 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13953 		isv6 = B_FALSE;
13954 	} else {
13955 		isv6 = B_TRUE;
13956 	}
13957 
13958 	irb = ire->ire_bucket;
13959 	ASSERT(irb != NULL);
13960 
13961 	result = 0;
13962 	irb_refhold(irb);
13963 	for (; ire != NULL; ire = ire->ire_next) {
13964 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13965 			continue;
13966 
13967 		/* We handle -ifp routes by matching on the ill if set */
13968 		match_flags = MATCH_IRE_TYPE;
13969 		if (ire->ire_ill != NULL)
13970 			match_flags |= MATCH_IRE_ILL;
13971 
13972 		if (isv6) {
13973 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13974 				continue;
13975 
13976 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13977 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13978 			    match_flags, 0, ipst, NULL);
13979 		} else {
13980 			if (ire->ire_addr != group)
13981 				continue;
13982 
13983 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13984 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13985 			    match_flags, 0, ipst, NULL);
13986 		}
13987 		/* No interface route exists for the gateway; skip this ire. */
13988 		if (ire_gw == NULL)
13989 			continue;
13990 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13991 			ire_refrele(ire_gw);
13992 			continue;
13993 		}
13994 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13995 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13996 
13997 		/*
13998 		 * The operation is considered a success if
13999 		 * it succeeds at least once on any one interface.
14000 		 */
14001 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
14002 		    fmode, v6src);
14003 		if (error == 0)
14004 			result = CGTP_MCAST_SUCCESS;
14005 
14006 		ire_refrele(ire_gw);
14007 	}
14008 	irb_refrele(irb);
14009 	/*
14010 	 * Consider the call as successful if we succeeded on at least
14011 	 * one interface. Otherwise, return the last encountered error.
14012 	 */
14013 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
14014 }
14015 
14016 /*
14017  * Get the CGTP (multirouting) filtering status.
14018  * If 0, the CGTP hooks are transparent.
14019  */
14020 /* ARGSUSED */
14021 static int
14022 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
14023 {
14024 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
14025 
14026 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
14027 	return (0);
14028 }
14029 
14030 /*
14031  * Set the CGTP (multirouting) filtering status.
14032  * If the status is changed from active to transparent
14033  * or from transparent to active, forward the new status
14034  * to the filtering module (if loaded).
14035  */
14036 /* ARGSUSED */
14037 static int
14038 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
14039     cred_t *ioc_cr)
14040 {
14041 	long		new_value;
14042 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
14043 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
14044 
14045 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
14046 		return (EPERM);
14047 
14048 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
14049 	    new_value < 0 || new_value > 1) {
14050 		return (EINVAL);
14051 	}
14052 
14053 	if ((!*ip_cgtp_filter_value) && new_value) {
14054 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
14055 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
14056 		    " (module not loaded)" : "");
14057 	}
14058 	if (*ip_cgtp_filter_value && (!new_value)) {
14059 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
14060 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
14061 		    " (module not loaded)" : "");
14062 	}
14063 
14064 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
14065 		int	res;
14066 		netstackid_t stackid;
14067 
14068 		stackid = ipst->ips_netstack->netstack_stackid;
14069 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
14070 		    new_value);
14071 		if (res)
14072 			return (res);
14073 	}
14074 
14075 	*ip_cgtp_filter_value = (boolean_t)new_value;
14076 
14077 	ill_set_inputfn_all(ipst);
14078 	return (0);
14079 }
14080 
14081 /*
14082  * Return the expected CGTP hooks version number.
14083  */
14084 int
14085 ip_cgtp_filter_supported(void)
14086 {
14087 	return (ip_cgtp_filter_rev);
14088 }
14089 
14090 /*
14091  * CGTP hooks can be registered by invoking this function.
14092  * Checks that the version number matches.
14093  */
14094 int
14095 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
14096 {
14097 	netstack_t *ns;
14098 	ip_stack_t *ipst;
14099 
14100 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
14101 		return (ENOTSUP);
14102 
14103 	ns = netstack_find_by_stackid(stackid);
14104 	if (ns == NULL)
14105 		return (EINVAL);
14106 	ipst = ns->netstack_ip;
14107 	ASSERT(ipst != NULL);
14108 
14109 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
14110 		netstack_rele(ns);
14111 		return (EALREADY);
14112 	}
14113 
14114 	ipst->ips_ip_cgtp_filter_ops = ops;
14115 
14116 	ill_set_inputfn_all(ipst);
14117 
14118 	netstack_rele(ns);
14119 	return (0);
14120 }
14121 
14122 /*
14123  * CGTP hooks can be unregistered by invoking this function.
14124  * Returns ENXIO if there was no registration.
14125  * Returns EBUSY if the ndd variable has not been turned off.
14126  */
14127 int
14128 ip_cgtp_filter_unregister(netstackid_t stackid)
14129 {
14130 	netstack_t *ns;
14131 	ip_stack_t *ipst;
14132 
14133 	ns = netstack_find_by_stackid(stackid);
14134 	if (ns == NULL)
14135 		return (EINVAL);
14136 	ipst = ns->netstack_ip;
14137 	ASSERT(ipst != NULL);
14138 
14139 	if (ipst->ips_ip_cgtp_filter) {
14140 		netstack_rele(ns);
14141 		return (EBUSY);
14142 	}
14143 
14144 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
14145 		netstack_rele(ns);
14146 		return (ENXIO);
14147 	}
14148 	ipst->ips_ip_cgtp_filter_ops = NULL;
14149 
14150 	ill_set_inputfn_all(ipst);
14151 
14152 	netstack_rele(ns);
14153 	return (0);
14154 }
14155 
14156 /*
14157  * Check whether there is a CGTP filter registration.
14158  * Returns non-zero if there is a registration, otherwise returns zero.
14159  * Note: returns zero if bad stackid.
14160  */
14161 int
14162 ip_cgtp_filter_is_registered(netstackid_t stackid)
14163 {
14164 	netstack_t *ns;
14165 	ip_stack_t *ipst;
14166 	int ret;
14167 
14168 	ns = netstack_find_by_stackid(stackid);
14169 	if (ns == NULL)
14170 		return (0);
14171 	ipst = ns->netstack_ip;
14172 	ASSERT(ipst != NULL);
14173 
14174 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
14175 		ret = 1;
14176 	else
14177 		ret = 0;
14178 
14179 	netstack_rele(ns);
14180 	return (ret);
14181 }
14182 
14183 static int
14184 ip_squeue_switch(int val)
14185 {
14186 	int rval;
14187 
14188 	switch (val) {
14189 	case IP_SQUEUE_ENTER_NODRAIN:
14190 		rval = SQ_NODRAIN;
14191 		break;
14192 	case IP_SQUEUE_ENTER:
14193 		rval = SQ_PROCESS;
14194 		break;
14195 	case IP_SQUEUE_FILL:
14196 	default:
14197 		rval = SQ_FILL;
14198 		break;
14199 	}
14200 	return (rval);
14201 }
14202 
14203 /* ARGSUSED */
14204 static int
14205 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
14206     caddr_t addr, cred_t *cr)
14207 {
14208 	int *v = (int *)addr;
14209 	long new_value;
14210 
14211 	if (secpolicy_net_config(cr, B_FALSE) != 0)
14212 		return (EPERM);
14213 
14214 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
14215 		return (EINVAL);
14216 
14217 	ip_squeue_flag = ip_squeue_switch(new_value);
14218 	*v = new_value;
14219 	return (0);
14220 }
14221 
14222 /*
14223  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
14224  * ip_debug.
14225  */
14226 /* ARGSUSED */
14227 static int
14228 ip_int_set(queue_t *q, mblk_t *mp, char *value,
14229     caddr_t addr, cred_t *cr)
14230 {
14231 	int *v = (int *)addr;
14232 	long new_value;
14233 
14234 	if (secpolicy_net_config(cr, B_FALSE) != 0)
14235 		return (EPERM);
14236 
14237 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
14238 		return (EINVAL);
14239 
14240 	*v = new_value;
14241 	return (0);
14242 }
14243 
14244 static void *
14245 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
14246 {
14247 	kstat_t *ksp;
14248 
14249 	ip_stat_t template = {
14250 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
14251 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
14252 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
14253 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
14254 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
14255 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
14256 		{ "ip_opt",			KSTAT_DATA_UINT64 },
14257 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
14258 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
14259 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
14260 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
14261 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
14262 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
14263 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
14264 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
14265 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
14266 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
14267 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
14268 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
14269 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
14270 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
14271 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
14272 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
14273 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
14274 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
14275 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
14276 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
14277 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
14278 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
14279 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
14280 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
14281 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
14282 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
14283 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
14284 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
14285 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
14286 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
14287 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
14288 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
14289 	};
14290 
14291 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
14292 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
14293 	    KSTAT_FLAG_VIRTUAL, stackid);
14294 
14295 	if (ksp == NULL)
14296 		return (NULL);
14297 
14298 	bcopy(&template, ip_statisticsp, sizeof (template));
14299 	ksp->ks_data = (void *)ip_statisticsp;
14300 	ksp->ks_private = (void *)(uintptr_t)stackid;
14301 
14302 	kstat_install(ksp);
14303 	return (ksp);
14304 }
14305 
14306 static void
14307 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
14308 {
14309 	if (ksp != NULL) {
14310 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14311 		kstat_delete_netstack(ksp, stackid);
14312 	}
14313 }
14314 
14315 static void *
14316 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
14317 {
14318 	kstat_t	*ksp;
14319 
14320 	ip_named_kstat_t template = {
14321 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
14322 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
14323 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
14324 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
14325 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
14326 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
14327 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
14328 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
14329 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
14330 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
14331 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
14332 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
14333 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
14334 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
14335 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
14336 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
14337 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
14338 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
14339 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
14340 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
14341 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
14342 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
14343 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
14344 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
14345 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
14346 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
14347 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
14348 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
14349 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
14350 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
14351 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
14352 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
14353 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
14354 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
14355 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
14356 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
14357 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
14358 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
14359 	};
14360 
14361 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
14362 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
14363 	if (ksp == NULL || ksp->ks_data == NULL)
14364 		return (NULL);
14365 
14366 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
14367 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
14368 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
14369 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
14370 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14371 
14372 	template.netToMediaEntrySize.value.i32 =
14373 	    sizeof (mib2_ipNetToMediaEntry_t);
14374 
14375 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14376 
14377 	bcopy(&template, ksp->ks_data, sizeof (template));
14378 	ksp->ks_update = ip_kstat_update;
14379 	ksp->ks_private = (void *)(uintptr_t)stackid;
14380 
14381 	kstat_install(ksp);
14382 	return (ksp);
14383 }
14384 
14385 static void
14386 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14387 {
14388 	if (ksp != NULL) {
14389 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14390 		kstat_delete_netstack(ksp, stackid);
14391 	}
14392 }
14393 
14394 static int
14395 ip_kstat_update(kstat_t *kp, int rw)
14396 {
14397 	ip_named_kstat_t *ipkp;
14398 	mib2_ipIfStatsEntry_t ipmib;
14399 	ill_walk_context_t ctx;
14400 	ill_t *ill;
14401 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14402 	netstack_t	*ns;
14403 	ip_stack_t	*ipst;
14404 
14405 	if (kp == NULL || kp->ks_data == NULL)
14406 		return (EIO);
14407 
14408 	if (rw == KSTAT_WRITE)
14409 		return (EACCES);
14410 
14411 	ns = netstack_find_by_stackid(stackid);
14412 	if (ns == NULL)
14413 		return (-1);
14414 	ipst = ns->netstack_ip;
14415 	if (ipst == NULL) {
14416 		netstack_rele(ns);
14417 		return (-1);
14418 	}
14419 	ipkp = (ip_named_kstat_t *)kp->ks_data;
14420 
14421 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14422 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14423 	ill = ILL_START_WALK_V4(&ctx, ipst);
14424 	for (; ill != NULL; ill = ill_next(&ctx, ill))
14425 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14426 	rw_exit(&ipst->ips_ill_g_lock);
14427 
14428 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
14429 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
14430 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
14431 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
14432 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
14433 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14434 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
14435 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
14436 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
14437 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
14438 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
14439 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
14440 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
14441 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
14442 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
14443 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
14444 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
14445 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
14446 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
14447 
14448 	ipkp->routingDiscards.value.ui32 =	0;
14449 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
14450 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
14451 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
14452 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
14453 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
14454 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
14455 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
14456 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
14457 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
14458 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
14459 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
14460 
14461 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
14462 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
14463 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14464 
14465 	netstack_rele(ns);
14466 
14467 	return (0);
14468 }
14469 
14470 static void *
14471 icmp_kstat_init(netstackid_t stackid)
14472 {
14473 	kstat_t	*ksp;
14474 
14475 	icmp_named_kstat_t template = {
14476 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14477 		{ "inErrors",		KSTAT_DATA_UINT32 },
14478 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14479 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14480 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14481 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14482 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14483 		{ "inEchos",		KSTAT_DATA_UINT32 },
14484 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14485 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14486 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14487 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14488 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14489 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14490 		{ "outErrors",		KSTAT_DATA_UINT32 },
14491 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14492 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14493 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14494 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14495 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14496 		{ "outEchos",		KSTAT_DATA_UINT32 },
14497 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14498 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14499 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14500 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14501 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14502 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14503 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14504 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14505 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14506 		{ "outDrops",		KSTAT_DATA_UINT32 },
14507 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14508 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14509 	};
14510 
14511 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14512 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14513 	if (ksp == NULL || ksp->ks_data == NULL)
14514 		return (NULL);
14515 
14516 	bcopy(&template, ksp->ks_data, sizeof (template));
14517 
14518 	ksp->ks_update = icmp_kstat_update;
14519 	ksp->ks_private = (void *)(uintptr_t)stackid;
14520 
14521 	kstat_install(ksp);
14522 	return (ksp);
14523 }
14524 
14525 static void
14526 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14527 {
14528 	if (ksp != NULL) {
14529 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14530 		kstat_delete_netstack(ksp, stackid);
14531 	}
14532 }
14533 
14534 static int
14535 icmp_kstat_update(kstat_t *kp, int rw)
14536 {
14537 	icmp_named_kstat_t *icmpkp;
14538 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14539 	netstack_t	*ns;
14540 	ip_stack_t	*ipst;
14541 
14542 	if ((kp == NULL) || (kp->ks_data == NULL))
14543 		return (EIO);
14544 
14545 	if (rw == KSTAT_WRITE)
14546 		return (EACCES);
14547 
14548 	ns = netstack_find_by_stackid(stackid);
14549 	if (ns == NULL)
14550 		return (-1);
14551 	ipst = ns->netstack_ip;
14552 	if (ipst == NULL) {
14553 		netstack_rele(ns);
14554 		return (-1);
14555 	}
14556 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14557 
14558 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14559 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14560 	icmpkp->inDestUnreachs.value.ui32 =
14561 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14562 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14563 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14564 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14565 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14566 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14567 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14568 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14569 	icmpkp->inTimestampReps.value.ui32 =
14570 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14571 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14572 	icmpkp->inAddrMaskReps.value.ui32 =
14573 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14574 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14575 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14576 	icmpkp->outDestUnreachs.value.ui32 =
14577 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14578 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14579 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14580 	icmpkp->outSrcQuenchs.value.ui32 =
14581 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14582 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14583 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14584 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14585 	icmpkp->outTimestamps.value.ui32 =
14586 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14587 	icmpkp->outTimestampReps.value.ui32 =
14588 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14589 	icmpkp->outAddrMasks.value.ui32 =
14590 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14591 	icmpkp->outAddrMaskReps.value.ui32 =
14592 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14593 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14594 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14595 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14596 	icmpkp->outFragNeeded.value.ui32 =
14597 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14598 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14599 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14600 	icmpkp->inBadRedirects.value.ui32 =
14601 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14602 
14603 	netstack_rele(ns);
14604 	return (0);
14605 }
14606 
14607 /*
14608  * This is the fanout function for raw socket opened for SCTP.  Note
14609  * that it is called after SCTP checks that there is no socket which
14610  * wants a packet.  Then before SCTP handles this out of the blue packet,
14611  * this function is called to see if there is any raw socket for SCTP.
14612  * If there is and it is bound to the correct address, the packet will
14613  * be sent to that socket.  Note that only one raw socket can be bound to
14614  * a port.  This is assured in ipcl_sctp_hash_insert();
14615  */
14616 void
14617 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14618     ip_recv_attr_t *ira)
14619 {
14620 	conn_t		*connp;
14621 	queue_t		*rq;
14622 	boolean_t	secure;
14623 	ill_t		*ill = ira->ira_ill;
14624 	ip_stack_t	*ipst = ill->ill_ipst;
14625 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14626 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14627 	iaflags_t	iraflags = ira->ira_flags;
14628 	ill_t		*rill = ira->ira_rill;
14629 
14630 	secure = iraflags & IRAF_IPSEC_SECURE;
14631 
14632 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14633 	    ira, ipst);
14634 	if (connp == NULL) {
14635 		/*
14636 		 * Although raw sctp is not summed, OOB chunks must be.
14637 		 * Drop the packet here if the sctp checksum failed.
14638 		 */
14639 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14640 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
14641 			freemsg(mp);
14642 			return;
14643 		}
14644 		ira->ira_ill = ira->ira_rill = NULL;
14645 		sctp_ootb_input(mp, ira, ipst);
14646 		ira->ira_ill = ill;
14647 		ira->ira_rill = rill;
14648 		return;
14649 	}
14650 	rq = connp->conn_rq;
14651 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14652 		CONN_DEC_REF(connp);
14653 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14654 		freemsg(mp);
14655 		return;
14656 	}
14657 	if (((iraflags & IRAF_IS_IPV4) ?
14658 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14659 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14660 	    secure) {
14661 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14662 		    ip6h, ira);
14663 		if (mp == NULL) {
14664 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14665 			/* Note that mp is NULL */
14666 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14667 			CONN_DEC_REF(connp);
14668 			return;
14669 		}
14670 	}
14671 
14672 	if (iraflags & IRAF_ICMP_ERROR) {
14673 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14674 	} else {
14675 		ill_t *rill = ira->ira_rill;
14676 
14677 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14678 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14679 		ira->ira_ill = ira->ira_rill = NULL;
14680 		(connp->conn_recv)(connp, mp, NULL, ira);
14681 		ira->ira_ill = ill;
14682 		ira->ira_rill = rill;
14683 	}
14684 	CONN_DEC_REF(connp);
14685 }
14686 
14687 /*
14688  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14689  * header before the ip payload.
14690  */
14691 static void
14692 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14693 {
14694 	int len = (mp->b_wptr - mp->b_rptr);
14695 	mblk_t *ip_mp;
14696 
14697 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14698 	if (is_fp_mp || len != fp_mp_len) {
14699 		if (len > fp_mp_len) {
14700 			/*
14701 			 * fastpath header and ip header in the first mblk
14702 			 */
14703 			mp->b_rptr += fp_mp_len;
14704 		} else {
14705 			/*
14706 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14707 			 * attach the fastpath header before ip header.
14708 			 */
14709 			ip_mp = mp->b_cont;
14710 			freeb(mp);
14711 			mp = ip_mp;
14712 			mp->b_rptr += (fp_mp_len - len);
14713 		}
14714 	} else {
14715 		ip_mp = mp->b_cont;
14716 		freeb(mp);
14717 		mp = ip_mp;
14718 	}
14719 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14720 	freemsg(mp);
14721 }
14722 
14723 /*
14724  * Normal post fragmentation function.
14725  *
14726  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14727  * using the same state machine.
14728  *
14729  * We return an error on failure. In particular we return EWOULDBLOCK
14730  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14731  * (currently by canputnext failure resulting in backenabling from GLD.)
14732  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14733  * indication that they can flow control until ip_wsrv() tells then to restart.
14734  *
14735  * If the nce passed by caller is incomplete, this function
14736  * queues the packet and if necessary, sends ARP request and bails.
14737  * If the Neighbor Cache passed is fully resolved, we simply prepend
14738  * the link-layer header to the packet, do ipsec hw acceleration
14739  * work if necessary, and send the packet out on the wire.
14740  */
14741 /* ARGSUSED6 */
14742 int
14743 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14744     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14745 {
14746 	queue_t		*wq;
14747 	ill_t		*ill = nce->nce_ill;
14748 	ip_stack_t	*ipst = ill->ill_ipst;
14749 	uint64_t	delta;
14750 	boolean_t	isv6 = ill->ill_isv6;
14751 	boolean_t	fp_mp;
14752 	ncec_t		*ncec = nce->nce_common;
14753 	int64_t		now = LBOLT_FASTPATH64;
14754 	boolean_t	is_probe;
14755 
14756 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14757 
14758 	ASSERT(mp != NULL);
14759 	ASSERT(mp->b_datap->db_type == M_DATA);
14760 	ASSERT(pkt_len == msgdsize(mp));
14761 
14762 	/*
14763 	 * If we have already been here and are coming back after ARP/ND.
14764 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14765 	 * in that case since they have seen the packet when it came here
14766 	 * the first time.
14767 	 */
14768 	if (ixaflags & IXAF_NO_TRACE)
14769 		goto sendit;
14770 
14771 	if (ixaflags & IXAF_IS_IPV4) {
14772 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14773 
14774 		ASSERT(!isv6);
14775 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14776 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14777 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14778 			int	error;
14779 
14780 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14781 			    ipst->ips_ipv4firewall_physical_out,
14782 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14783 			DTRACE_PROBE1(ip4__physical__out__end,
14784 			    mblk_t *, mp);
14785 			if (mp == NULL)
14786 				return (error);
14787 
14788 			/* The length could have changed */
14789 			pkt_len = msgdsize(mp);
14790 		}
14791 		if (ipst->ips_ip4_observe.he_interested) {
14792 			/*
14793 			 * Note that for TX the zoneid is the sending
14794 			 * zone, whether or not MLP is in play.
14795 			 * Since the szone argument is the IP zoneid (i.e.,
14796 			 * zero for exclusive-IP zones) and ipobs wants
14797 			 * the system zoneid, we map it here.
14798 			 */
14799 			szone = IP_REAL_ZONEID(szone, ipst);
14800 
14801 			/*
14802 			 * On the outbound path the destination zone will be
14803 			 * unknown as we're sending this packet out on the
14804 			 * wire.
14805 			 */
14806 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14807 			    ill, ipst);
14808 		}
14809 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14810 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14811 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14812 	} else {
14813 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14814 
14815 		ASSERT(isv6);
14816 		ASSERT(pkt_len ==
14817 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14818 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14819 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14820 			int	error;
14821 
14822 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14823 			    ipst->ips_ipv6firewall_physical_out,
14824 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14825 			DTRACE_PROBE1(ip6__physical__out__end,
14826 			    mblk_t *, mp);
14827 			if (mp == NULL)
14828 				return (error);
14829 
14830 			/* The length could have changed */
14831 			pkt_len = msgdsize(mp);
14832 		}
14833 		if (ipst->ips_ip6_observe.he_interested) {
14834 			/* See above */
14835 			szone = IP_REAL_ZONEID(szone, ipst);
14836 
14837 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14838 			    ill, ipst);
14839 		}
14840 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14841 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14842 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14843 	}
14844 
14845 sendit:
14846 	/*
14847 	 * We check the state without a lock because the state can never
14848 	 * move "backwards" to initial or incomplete.
14849 	 */
14850 	switch (ncec->ncec_state) {
14851 	case ND_REACHABLE:
14852 	case ND_STALE:
14853 	case ND_DELAY:
14854 	case ND_PROBE:
14855 		mp = ip_xmit_attach_llhdr(mp, nce);
14856 		if (mp == NULL) {
14857 			/*
14858 			 * ip_xmit_attach_llhdr has increased
14859 			 * ipIfStatsOutDiscards and called ip_drop_output()
14860 			 */
14861 			return (ENOBUFS);
14862 		}
14863 		/*
14864 		 * check if nce_fastpath completed and we tagged on a
14865 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14866 		 */
14867 		fp_mp = (mp->b_datap->db_type == M_DATA);
14868 
14869 		if (fp_mp &&
14870 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14871 			ill_dld_direct_t *idd;
14872 
14873 			idd = &ill->ill_dld_capab->idc_direct;
14874 			/*
14875 			 * Send the packet directly to DLD, where it
14876 			 * may be queued depending on the availability
14877 			 * of transmit resources at the media layer.
14878 			 * Return value should be taken into
14879 			 * account and flow control the TCP.
14880 			 */
14881 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14882 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14883 			    pkt_len);
14884 
14885 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14886 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14887 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14888 			} else {
14889 				uintptr_t cookie;
14890 
14891 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14892 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14893 					if (ixacookie != NULL)
14894 						*ixacookie = cookie;
14895 					return (EWOULDBLOCK);
14896 				}
14897 			}
14898 		} else {
14899 			wq = ill->ill_wq;
14900 
14901 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14902 			    !canputnext(wq)) {
14903 				if (ixacookie != NULL)
14904 					*ixacookie = 0;
14905 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14906 				    nce->nce_fp_mp != NULL ?
14907 				    MBLKL(nce->nce_fp_mp) : 0);
14908 				return (EWOULDBLOCK);
14909 			}
14910 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14911 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14912 			    pkt_len);
14913 			putnext(wq, mp);
14914 		}
14915 
14916 		/*
14917 		 * The rest of this function implements Neighbor Unreachability
14918 		 * detection. Determine if the ncec is eligible for NUD.
14919 		 */
14920 		if (ncec->ncec_flags & NCE_F_NONUD)
14921 			return (0);
14922 
14923 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14924 
14925 		/*
14926 		 * Check for upper layer advice
14927 		 */
14928 		if (ixaflags & IXAF_REACH_CONF) {
14929 			timeout_id_t tid;
14930 
14931 			/*
14932 			 * It should be o.k. to check the state without
14933 			 * a lock here, at most we lose an advice.
14934 			 */
14935 			ncec->ncec_last = TICK_TO_MSEC(now);
14936 			if (ncec->ncec_state != ND_REACHABLE) {
14937 				mutex_enter(&ncec->ncec_lock);
14938 				ncec->ncec_state = ND_REACHABLE;
14939 				tid = ncec->ncec_timeout_id;
14940 				ncec->ncec_timeout_id = 0;
14941 				mutex_exit(&ncec->ncec_lock);
14942 				(void) untimeout(tid);
14943 				if (ip_debug > 2) {
14944 					/* ip1dbg */
14945 					pr_addr_dbg("ip_xmit: state"
14946 					    " for %s changed to"
14947 					    " REACHABLE\n", AF_INET6,
14948 					    &ncec->ncec_addr);
14949 				}
14950 			}
14951 			return (0);
14952 		}
14953 
14954 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14955 		ip1dbg(("ip_xmit: delta = %" PRId64
14956 		    " ill_reachable_time = %d \n", delta,
14957 		    ill->ill_reachable_time));
14958 		if (delta > (uint64_t)ill->ill_reachable_time) {
14959 			mutex_enter(&ncec->ncec_lock);
14960 			switch (ncec->ncec_state) {
14961 			case ND_REACHABLE:
14962 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14963 				/* FALLTHROUGH */
14964 			case ND_STALE:
14965 				/*
14966 				 * ND_REACHABLE is identical to
14967 				 * ND_STALE in this specific case. If
14968 				 * reachable time has expired for this
14969 				 * neighbor (delta is greater than
14970 				 * reachable time), conceptually, the
14971 				 * neighbor cache is no longer in
14972 				 * REACHABLE state, but already in
14973 				 * STALE state.  So the correct
14974 				 * transition here is to ND_DELAY.
14975 				 */
14976 				ncec->ncec_state = ND_DELAY;
14977 				mutex_exit(&ncec->ncec_lock);
14978 				nce_restart_timer(ncec,
14979 				    ipst->ips_delay_first_probe_time);
14980 				if (ip_debug > 3) {
14981 					/* ip2dbg */
14982 					pr_addr_dbg("ip_xmit: state"
14983 					    " for %s changed to"
14984 					    " DELAY\n", AF_INET6,
14985 					    &ncec->ncec_addr);
14986 				}
14987 				break;
14988 			case ND_DELAY:
14989 			case ND_PROBE:
14990 				mutex_exit(&ncec->ncec_lock);
14991 				/* Timers have already started */
14992 				break;
14993 			case ND_UNREACHABLE:
14994 				/*
14995 				 * nce_timer has detected that this ncec
14996 				 * is unreachable and initiated deleting
14997 				 * this ncec.
14998 				 * This is a harmless race where we found the
14999 				 * ncec before it was deleted and have
15000 				 * just sent out a packet using this
15001 				 * unreachable ncec.
15002 				 */
15003 				mutex_exit(&ncec->ncec_lock);
15004 				break;
15005 			default:
15006 				ASSERT(0);
15007 				mutex_exit(&ncec->ncec_lock);
15008 			}
15009 		}
15010 		return (0);
15011 
15012 	case ND_INCOMPLETE:
15013 		/*
15014 		 * the state could have changed since we didn't hold the lock.
15015 		 * Re-verify state under lock.
15016 		 */
15017 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
15018 		mutex_enter(&ncec->ncec_lock);
15019 		if (NCE_ISREACHABLE(ncec)) {
15020 			mutex_exit(&ncec->ncec_lock);
15021 			goto sendit;
15022 		}
15023 		/* queue the packet */
15024 		nce_queue_mp(ncec, mp, is_probe);
15025 		mutex_exit(&ncec->ncec_lock);
15026 		DTRACE_PROBE2(ip__xmit__incomplete,
15027 		    (ncec_t *), ncec, (mblk_t *), mp);
15028 		return (0);
15029 
15030 	case ND_INITIAL:
15031 		/*
15032 		 * State could have changed since we didn't hold the lock, so
15033 		 * re-verify state.
15034 		 */
15035 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
15036 		mutex_enter(&ncec->ncec_lock);
15037 		if (NCE_ISREACHABLE(ncec))  {
15038 			mutex_exit(&ncec->ncec_lock);
15039 			goto sendit;
15040 		}
15041 		nce_queue_mp(ncec, mp, is_probe);
15042 		if (ncec->ncec_state == ND_INITIAL) {
15043 			ncec->ncec_state = ND_INCOMPLETE;
15044 			mutex_exit(&ncec->ncec_lock);
15045 			/*
15046 			 * figure out the source we want to use
15047 			 * and resolve it.
15048 			 */
15049 			ip_ndp_resolve(ncec);
15050 		} else  {
15051 			mutex_exit(&ncec->ncec_lock);
15052 		}
15053 		return (0);
15054 
15055 	case ND_UNREACHABLE:
15056 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
15057 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
15058 		    mp, ill);
15059 		freemsg(mp);
15060 		return (0);
15061 
15062 	default:
15063 		ASSERT(0);
15064 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
15065 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
15066 		    mp, ill);
15067 		freemsg(mp);
15068 		return (ENETUNREACH);
15069 	}
15070 }
15071 
15072 /*
15073  * Return B_TRUE if the buffers differ in length or content.
15074  * This is used for comparing extension header buffers.
15075  * Note that an extension header would be declared different
15076  * even if all that changed was the next header value in that header i.e.
15077  * what really changed is the next extension header.
15078  */
15079 boolean_t
15080 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
15081     uint_t blen)
15082 {
15083 	if (!b_valid)
15084 		blen = 0;
15085 
15086 	if (alen != blen)
15087 		return (B_TRUE);
15088 	if (alen == 0)
15089 		return (B_FALSE);	/* Both zero length */
15090 	return (bcmp(abuf, bbuf, alen));
15091 }
15092 
15093 /*
15094  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
15095  * Return B_FALSE if memory allocation fails - don't change any state!
15096  */
15097 boolean_t
15098 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
15099     const void *src, uint_t srclen)
15100 {
15101 	void *dst;
15102 
15103 	if (!src_valid)
15104 		srclen = 0;
15105 
15106 	ASSERT(*dstlenp == 0);
15107 	if (src != NULL && srclen != 0) {
15108 		dst = mi_alloc(srclen, BPRI_MED);
15109 		if (dst == NULL)
15110 			return (B_FALSE);
15111 	} else {
15112 		dst = NULL;
15113 	}
15114 	if (*dstp != NULL)
15115 		mi_free(*dstp);
15116 	*dstp = dst;
15117 	*dstlenp = dst == NULL ? 0 : srclen;
15118 	return (B_TRUE);
15119 }
15120 
15121 /*
15122  * Replace what is in *dst, *dstlen with the source.
15123  * Assumes ip_allocbuf has already been called.
15124  */
15125 void
15126 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
15127     const void *src, uint_t srclen)
15128 {
15129 	if (!src_valid)
15130 		srclen = 0;
15131 
15132 	ASSERT(*dstlenp == srclen);
15133 	if (src != NULL && srclen != 0)
15134 		bcopy(src, *dstp, srclen);
15135 }
15136 
15137 /*
15138  * Free the storage pointed to by the members of an ip_pkt_t.
15139  */
15140 void
15141 ip_pkt_free(ip_pkt_t *ipp)
15142 {
15143 	uint_t	fields = ipp->ipp_fields;
15144 
15145 	if (fields & IPPF_HOPOPTS) {
15146 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15147 		ipp->ipp_hopopts = NULL;
15148 		ipp->ipp_hopoptslen = 0;
15149 	}
15150 	if (fields & IPPF_RTHDRDSTOPTS) {
15151 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
15152 		ipp->ipp_rthdrdstopts = NULL;
15153 		ipp->ipp_rthdrdstoptslen = 0;
15154 	}
15155 	if (fields & IPPF_DSTOPTS) {
15156 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15157 		ipp->ipp_dstopts = NULL;
15158 		ipp->ipp_dstoptslen = 0;
15159 	}
15160 	if (fields & IPPF_RTHDR) {
15161 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15162 		ipp->ipp_rthdr = NULL;
15163 		ipp->ipp_rthdrlen = 0;
15164 	}
15165 	if (fields & IPPF_IPV4_OPTIONS) {
15166 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
15167 		ipp->ipp_ipv4_options = NULL;
15168 		ipp->ipp_ipv4_options_len = 0;
15169 	}
15170 	if (fields & IPPF_LABEL_V4) {
15171 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
15172 		ipp->ipp_label_v4 = NULL;
15173 		ipp->ipp_label_len_v4 = 0;
15174 	}
15175 	if (fields & IPPF_LABEL_V6) {
15176 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
15177 		ipp->ipp_label_v6 = NULL;
15178 		ipp->ipp_label_len_v6 = 0;
15179 	}
15180 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15181 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
15182 }
15183 
15184 /*
15185  * Copy from src to dst and allocate as needed.
15186  * Returns zero or ENOMEM.
15187  *
15188  * The caller must initialize dst to zero.
15189  */
15190 int
15191 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
15192 {
15193 	uint_t	fields = src->ipp_fields;
15194 
15195 	/* Start with fields that don't require memory allocation */
15196 	dst->ipp_fields = fields &
15197 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15198 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
15199 
15200 	dst->ipp_addr = src->ipp_addr;
15201 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
15202 	dst->ipp_hoplimit = src->ipp_hoplimit;
15203 	dst->ipp_tclass = src->ipp_tclass;
15204 	dst->ipp_type_of_service = src->ipp_type_of_service;
15205 
15206 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15207 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
15208 		return (0);
15209 
15210 	if (fields & IPPF_HOPOPTS) {
15211 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
15212 		if (dst->ipp_hopopts == NULL) {
15213 			ip_pkt_free(dst);
15214 			return (ENOMEM);
15215 		}
15216 		dst->ipp_fields |= IPPF_HOPOPTS;
15217 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
15218 		    src->ipp_hopoptslen);
15219 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
15220 	}
15221 	if (fields & IPPF_RTHDRDSTOPTS) {
15222 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
15223 		    kmflag);
15224 		if (dst->ipp_rthdrdstopts == NULL) {
15225 			ip_pkt_free(dst);
15226 			return (ENOMEM);
15227 		}
15228 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
15229 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
15230 		    src->ipp_rthdrdstoptslen);
15231 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
15232 	}
15233 	if (fields & IPPF_DSTOPTS) {
15234 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
15235 		if (dst->ipp_dstopts == NULL) {
15236 			ip_pkt_free(dst);
15237 			return (ENOMEM);
15238 		}
15239 		dst->ipp_fields |= IPPF_DSTOPTS;
15240 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
15241 		    src->ipp_dstoptslen);
15242 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
15243 	}
15244 	if (fields & IPPF_RTHDR) {
15245 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
15246 		if (dst->ipp_rthdr == NULL) {
15247 			ip_pkt_free(dst);
15248 			return (ENOMEM);
15249 		}
15250 		dst->ipp_fields |= IPPF_RTHDR;
15251 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
15252 		    src->ipp_rthdrlen);
15253 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
15254 	}
15255 	if (fields & IPPF_IPV4_OPTIONS) {
15256 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
15257 		    kmflag);
15258 		if (dst->ipp_ipv4_options == NULL) {
15259 			ip_pkt_free(dst);
15260 			return (ENOMEM);
15261 		}
15262 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
15263 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
15264 		    src->ipp_ipv4_options_len);
15265 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
15266 	}
15267 	if (fields & IPPF_LABEL_V4) {
15268 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
15269 		if (dst->ipp_label_v4 == NULL) {
15270 			ip_pkt_free(dst);
15271 			return (ENOMEM);
15272 		}
15273 		dst->ipp_fields |= IPPF_LABEL_V4;
15274 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
15275 		    src->ipp_label_len_v4);
15276 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
15277 	}
15278 	if (fields & IPPF_LABEL_V6) {
15279 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
15280 		if (dst->ipp_label_v6 == NULL) {
15281 			ip_pkt_free(dst);
15282 			return (ENOMEM);
15283 		}
15284 		dst->ipp_fields |= IPPF_LABEL_V6;
15285 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
15286 		    src->ipp_label_len_v6);
15287 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
15288 	}
15289 	if (fields & IPPF_FRAGHDR) {
15290 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
15291 		if (dst->ipp_fraghdr == NULL) {
15292 			ip_pkt_free(dst);
15293 			return (ENOMEM);
15294 		}
15295 		dst->ipp_fields |= IPPF_FRAGHDR;
15296 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
15297 		    src->ipp_fraghdrlen);
15298 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
15299 	}
15300 	return (0);
15301 }
15302 
15303 /*
15304  * Returns INADDR_ANY if no source route
15305  */
15306 ipaddr_t
15307 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
15308 {
15309 	ipaddr_t	nexthop = INADDR_ANY;
15310 	ipoptp_t	opts;
15311 	uchar_t		*opt;
15312 	uint8_t		optval;
15313 	uint8_t		optlen;
15314 	uint32_t	totallen;
15315 
15316 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15317 		return (INADDR_ANY);
15318 
15319 	totallen = ipp->ipp_ipv4_options_len;
15320 	if (totallen & 0x3)
15321 		return (INADDR_ANY);
15322 
15323 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15324 	    optval != IPOPT_EOL;
15325 	    optval = ipoptp_next(&opts)) {
15326 		opt = opts.ipoptp_cur;
15327 		switch (optval) {
15328 			uint8_t off;
15329 		case IPOPT_SSRR:
15330 		case IPOPT_LSRR:
15331 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15332 				break;
15333 			}
15334 			optlen = opts.ipoptp_len;
15335 			off = opt[IPOPT_OFFSET];
15336 			off--;
15337 			if (optlen < IP_ADDR_LEN ||
15338 			    off > optlen - IP_ADDR_LEN) {
15339 				/* End of source route */
15340 				break;
15341 			}
15342 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
15343 			if (nexthop == htonl(INADDR_LOOPBACK)) {
15344 				/* Ignore */
15345 				nexthop = INADDR_ANY;
15346 				break;
15347 			}
15348 			break;
15349 		}
15350 	}
15351 	return (nexthop);
15352 }
15353 
15354 /*
15355  * Reverse a source route.
15356  */
15357 void
15358 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
15359 {
15360 	ipaddr_t	tmp;
15361 	ipoptp_t	opts;
15362 	uchar_t		*opt;
15363 	uint8_t		optval;
15364 	uint32_t	totallen;
15365 
15366 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15367 		return;
15368 
15369 	totallen = ipp->ipp_ipv4_options_len;
15370 	if (totallen & 0x3)
15371 		return;
15372 
15373 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15374 	    optval != IPOPT_EOL;
15375 	    optval = ipoptp_next(&opts)) {
15376 		uint8_t off1, off2;
15377 
15378 		opt = opts.ipoptp_cur;
15379 		switch (optval) {
15380 		case IPOPT_SSRR:
15381 		case IPOPT_LSRR:
15382 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15383 				break;
15384 			}
15385 			off1 = IPOPT_MINOFF_SR - 1;
15386 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15387 			while (off2 > off1) {
15388 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15389 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15390 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15391 				off2 -= IP_ADDR_LEN;
15392 				off1 += IP_ADDR_LEN;
15393 			}
15394 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15395 			break;
15396 		}
15397 	}
15398 }
15399 
15400 /*
15401  * Returns NULL if no routing header
15402  */
15403 in6_addr_t *
15404 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15405 {
15406 	in6_addr_t	*nexthop = NULL;
15407 	ip6_rthdr0_t	*rthdr;
15408 
15409 	if (!(ipp->ipp_fields & IPPF_RTHDR))
15410 		return (NULL);
15411 
15412 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15413 	if (rthdr->ip6r0_segleft == 0)
15414 		return (NULL);
15415 
15416 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15417 	return (nexthop);
15418 }
15419 
15420 zoneid_t
15421 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15422     zoneid_t lookup_zoneid)
15423 {
15424 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15425 	ire_t		*ire;
15426 	int		ire_flags = MATCH_IRE_TYPE;
15427 	zoneid_t	zoneid = ALL_ZONES;
15428 
15429 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15430 		return (ALL_ZONES);
15431 
15432 	if (lookup_zoneid != ALL_ZONES)
15433 		ire_flags |= MATCH_IRE_ZONEONLY;
15434 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15435 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15436 	if (ire != NULL) {
15437 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15438 		ire_refrele(ire);
15439 	}
15440 	return (zoneid);
15441 }
15442 
15443 zoneid_t
15444 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15445     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15446 {
15447 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15448 	ire_t		*ire;
15449 	int		ire_flags = MATCH_IRE_TYPE;
15450 	zoneid_t	zoneid = ALL_ZONES;
15451 
15452 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15453 		return (ALL_ZONES);
15454 
15455 	if (IN6_IS_ADDR_LINKLOCAL(addr))
15456 		ire_flags |= MATCH_IRE_ILL;
15457 
15458 	if (lookup_zoneid != ALL_ZONES)
15459 		ire_flags |= MATCH_IRE_ZONEONLY;
15460 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15461 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15462 	if (ire != NULL) {
15463 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15464 		ire_refrele(ire);
15465 	}
15466 	return (zoneid);
15467 }
15468 
15469 /*
15470  * IP obserability hook support functions.
15471  */
15472 static void
15473 ipobs_init(ip_stack_t *ipst)
15474 {
15475 	netid_t id;
15476 
15477 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15478 
15479 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15480 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15481 
15482 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15483 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15484 }
15485 
15486 static void
15487 ipobs_fini(ip_stack_t *ipst)
15488 {
15489 
15490 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15491 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15492 }
15493 
15494 /*
15495  * hook_pkt_observe_t is composed in network byte order so that the
15496  * entire mblk_t chain handed into hook_run can be used as-is.
15497  * The caveat is that use of the fields, such as the zone fields,
15498  * requires conversion into host byte order first.
15499  */
15500 void
15501 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15502     const ill_t *ill, ip_stack_t *ipst)
15503 {
15504 	hook_pkt_observe_t *hdr;
15505 	uint64_t grifindex;
15506 	mblk_t *imp;
15507 
15508 	imp = allocb(sizeof (*hdr), BPRI_HI);
15509 	if (imp == NULL)
15510 		return;
15511 
15512 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15513 	/*
15514 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15515 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15516 	 */
15517 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15518 	imp->b_cont = mp;
15519 
15520 	ASSERT(DB_TYPE(mp) == M_DATA);
15521 
15522 	if (IS_UNDER_IPMP(ill))
15523 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15524 	else
15525 		grifindex = 0;
15526 
15527 	hdr->hpo_version = 1;
15528 	hdr->hpo_htype = htons(htype);
15529 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15530 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15531 	hdr->hpo_grifindex = htonl(grifindex);
15532 	hdr->hpo_zsrc = htonl(zsrc);
15533 	hdr->hpo_zdst = htonl(zdst);
15534 	hdr->hpo_pkt = imp;
15535 	hdr->hpo_ctx = ipst->ips_netstack;
15536 
15537 	if (ill->ill_isv6) {
15538 		hdr->hpo_family = AF_INET6;
15539 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15540 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15541 	} else {
15542 		hdr->hpo_family = AF_INET;
15543 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15544 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15545 	}
15546 
15547 	imp->b_cont = NULL;
15548 	freemsg(imp);
15549 }
15550 
15551 /*
15552  * Utility routine that checks if `v4srcp' is a valid address on underlying
15553  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15554  * associated with `v4srcp' on success.  NOTE: if this is not called from
15555  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15556  * group during or after this lookup.
15557  */
15558 boolean_t
15559 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15560 {
15561 	ipif_t *ipif;
15562 
15563 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15564 	if (ipif != NULL) {
15565 		if (ipifp != NULL)
15566 			*ipifp = ipif;
15567 		else
15568 			ipif_refrele(ipif);
15569 		return (B_TRUE);
15570 	}
15571 
15572 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15573 	    *v4srcp));
15574 	return (B_FALSE);
15575 }
15576