xref: /titanic_41/usr/src/uts/common/inet/ip/ip.c (revision 82629e3015252bf18319ba3815c773df23e21436)
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 	connp->conn_ixa->ixa_cred = connp->conn_cred;
6217 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6218 	if (is_system_labeled())
6219 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6220 
6221 	/*
6222 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6223 	 */
6224 	connp->conn_recv = ip_conn_input;
6225 	connp->conn_recvicmp = ip_conn_input_icmp;
6226 
6227 	crhold(connp->conn_cred);
6228 
6229 	/*
6230 	 * If the caller has the process-wide flag set, then default to MAC
6231 	 * exempt mode.  This allows read-down to unlabeled hosts.
6232 	 */
6233 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6234 		connp->conn_mac_mode = CONN_MAC_AWARE;
6235 
6236 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6237 
6238 	connp->conn_rq = q;
6239 	connp->conn_wq = WR(q);
6240 
6241 	/* Non-zero default values */
6242 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6243 
6244 	/*
6245 	 * Make the conn globally visible to walkers
6246 	 */
6247 	ASSERT(connp->conn_ref == 1);
6248 	mutex_enter(&connp->conn_lock);
6249 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6250 	mutex_exit(&connp->conn_lock);
6251 
6252 	qprocson(q);
6253 
6254 	return (0);
6255 }
6256 
6257 /*
6258  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6259  * all of them are copied to the conn_t. If the req is "zero", the policy is
6260  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6261  * fields.
6262  * We keep only the latest setting of the policy and thus policy setting
6263  * is not incremental/cumulative.
6264  *
6265  * Requests to set policies with multiple alternative actions will
6266  * go through a different API.
6267  */
6268 int
6269 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6270 {
6271 	uint_t ah_req = 0;
6272 	uint_t esp_req = 0;
6273 	uint_t se_req = 0;
6274 	ipsec_act_t *actp = NULL;
6275 	uint_t nact;
6276 	ipsec_policy_head_t *ph;
6277 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6278 	int error = 0;
6279 	netstack_t	*ns = connp->conn_netstack;
6280 	ip_stack_t	*ipst = ns->netstack_ip;
6281 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6282 
6283 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6284 
6285 	/*
6286 	 * The IP_SEC_OPT option does not allow variable length parameters,
6287 	 * hence a request cannot be NULL.
6288 	 */
6289 	if (req == NULL)
6290 		return (EINVAL);
6291 
6292 	ah_req = req->ipsr_ah_req;
6293 	esp_req = req->ipsr_esp_req;
6294 	se_req = req->ipsr_self_encap_req;
6295 
6296 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6297 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6298 		return (EINVAL);
6299 
6300 	/*
6301 	 * Are we dealing with a request to reset the policy (i.e.
6302 	 * zero requests).
6303 	 */
6304 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6305 	    (esp_req & REQ_MASK) == 0 &&
6306 	    (se_req & REQ_MASK) == 0);
6307 
6308 	if (!is_pol_reset) {
6309 		/*
6310 		 * If we couldn't load IPsec, fail with "protocol
6311 		 * not supported".
6312 		 * IPsec may not have been loaded for a request with zero
6313 		 * policies, so we don't fail in this case.
6314 		 */
6315 		mutex_enter(&ipss->ipsec_loader_lock);
6316 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6317 			mutex_exit(&ipss->ipsec_loader_lock);
6318 			return (EPROTONOSUPPORT);
6319 		}
6320 		mutex_exit(&ipss->ipsec_loader_lock);
6321 
6322 		/*
6323 		 * Test for valid requests. Invalid algorithms
6324 		 * need to be tested by IPsec code because new
6325 		 * algorithms can be added dynamically.
6326 		 */
6327 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6328 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6329 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6330 			return (EINVAL);
6331 		}
6332 
6333 		/*
6334 		 * Only privileged users can issue these
6335 		 * requests.
6336 		 */
6337 		if (((ah_req & IPSEC_PREF_NEVER) ||
6338 		    (esp_req & IPSEC_PREF_NEVER) ||
6339 		    (se_req & IPSEC_PREF_NEVER)) &&
6340 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6341 			return (EPERM);
6342 		}
6343 
6344 		/*
6345 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6346 		 * are mutually exclusive.
6347 		 */
6348 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6349 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6350 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6351 			/* Both of them are set */
6352 			return (EINVAL);
6353 		}
6354 	}
6355 
6356 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6357 
6358 	/*
6359 	 * If we have already cached policies in conn_connect(), don't
6360 	 * let them change now. We cache policies for connections
6361 	 * whose src,dst [addr, port] is known.
6362 	 */
6363 	if (connp->conn_policy_cached) {
6364 		return (EINVAL);
6365 	}
6366 
6367 	/*
6368 	 * We have a zero policies, reset the connection policy if already
6369 	 * set. This will cause the connection to inherit the
6370 	 * global policy, if any.
6371 	 */
6372 	if (is_pol_reset) {
6373 		if (connp->conn_policy != NULL) {
6374 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6375 			connp->conn_policy = NULL;
6376 		}
6377 		connp->conn_in_enforce_policy = B_FALSE;
6378 		connp->conn_out_enforce_policy = B_FALSE;
6379 		return (0);
6380 	}
6381 
6382 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6383 	    ipst->ips_netstack);
6384 	if (ph == NULL)
6385 		goto enomem;
6386 
6387 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6388 	if (actp == NULL)
6389 		goto enomem;
6390 
6391 	/*
6392 	 * Always insert IPv4 policy entries, since they can also apply to
6393 	 * ipv6 sockets being used in ipv4-compat mode.
6394 	 */
6395 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6396 	    IPSEC_TYPE_INBOUND, ns))
6397 		goto enomem;
6398 	is_pol_inserted = B_TRUE;
6399 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6400 	    IPSEC_TYPE_OUTBOUND, ns))
6401 		goto enomem;
6402 
6403 	/*
6404 	 * We're looking at a v6 socket, also insert the v6-specific
6405 	 * entries.
6406 	 */
6407 	if (connp->conn_family == AF_INET6) {
6408 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6409 		    IPSEC_TYPE_INBOUND, ns))
6410 			goto enomem;
6411 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6412 		    IPSEC_TYPE_OUTBOUND, ns))
6413 			goto enomem;
6414 	}
6415 
6416 	ipsec_actvec_free(actp, nact);
6417 
6418 	/*
6419 	 * If the requests need security, set enforce_policy.
6420 	 * If the requests are IPSEC_PREF_NEVER, one should
6421 	 * still set conn_out_enforce_policy so that ip_set_destination
6422 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6423 	 * for connections that we don't cache policy in at connect time,
6424 	 * if global policy matches in ip_output_attach_policy, we
6425 	 * don't wrongly inherit global policy. Similarly, we need
6426 	 * to set conn_in_enforce_policy also so that we don't verify
6427 	 * policy wrongly.
6428 	 */
6429 	if ((ah_req & REQ_MASK) != 0 ||
6430 	    (esp_req & REQ_MASK) != 0 ||
6431 	    (se_req & REQ_MASK) != 0) {
6432 		connp->conn_in_enforce_policy = B_TRUE;
6433 		connp->conn_out_enforce_policy = B_TRUE;
6434 	}
6435 
6436 	return (error);
6437 #undef REQ_MASK
6438 
6439 	/*
6440 	 * Common memory-allocation-failure exit path.
6441 	 */
6442 enomem:
6443 	if (actp != NULL)
6444 		ipsec_actvec_free(actp, nact);
6445 	if (is_pol_inserted)
6446 		ipsec_polhead_flush(ph, ns);
6447 	return (ENOMEM);
6448 }
6449 
6450 /*
6451  * Set socket options for joining and leaving multicast groups.
6452  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6453  * The caller has already check that the option name is consistent with
6454  * the address family of the socket.
6455  */
6456 int
6457 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6458     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6459 {
6460 	int		*i1 = (int *)invalp;
6461 	int		error = 0;
6462 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6463 	struct ip_mreq	*v4_mreqp;
6464 	struct ipv6_mreq *v6_mreqp;
6465 	struct group_req *greqp;
6466 	ire_t *ire;
6467 	boolean_t done = B_FALSE;
6468 	ipaddr_t ifaddr;
6469 	in6_addr_t v6group;
6470 	uint_t ifindex;
6471 	boolean_t mcast_opt = B_TRUE;
6472 	mcast_record_t fmode;
6473 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6474 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6475 
6476 	switch (name) {
6477 	case IP_ADD_MEMBERSHIP:
6478 	case IPV6_JOIN_GROUP:
6479 		mcast_opt = B_FALSE;
6480 		/* FALLTHRU */
6481 	case MCAST_JOIN_GROUP:
6482 		fmode = MODE_IS_EXCLUDE;
6483 		optfn = ip_opt_add_group;
6484 		break;
6485 
6486 	case IP_DROP_MEMBERSHIP:
6487 	case IPV6_LEAVE_GROUP:
6488 		mcast_opt = B_FALSE;
6489 		/* FALLTHRU */
6490 	case MCAST_LEAVE_GROUP:
6491 		fmode = MODE_IS_INCLUDE;
6492 		optfn = ip_opt_delete_group;
6493 		break;
6494 	default:
6495 		ASSERT(0);
6496 	}
6497 
6498 	if (mcast_opt) {
6499 		struct sockaddr_in *sin;
6500 		struct sockaddr_in6 *sin6;
6501 
6502 		greqp = (struct group_req *)i1;
6503 		if (greqp->gr_group.ss_family == AF_INET) {
6504 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6505 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6506 		} else {
6507 			if (!inet6)
6508 				return (EINVAL);	/* Not on INET socket */
6509 
6510 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6511 			v6group = sin6->sin6_addr;
6512 		}
6513 		ifaddr = INADDR_ANY;
6514 		ifindex = greqp->gr_interface;
6515 	} else if (inet6) {
6516 		v6_mreqp = (struct ipv6_mreq *)i1;
6517 		v6group = v6_mreqp->ipv6mr_multiaddr;
6518 		ifaddr = INADDR_ANY;
6519 		ifindex = v6_mreqp->ipv6mr_interface;
6520 	} else {
6521 		v4_mreqp = (struct ip_mreq *)i1;
6522 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6523 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6524 		ifindex = 0;
6525 	}
6526 
6527 	/*
6528 	 * In the multirouting case, we need to replicate
6529 	 * the request on all interfaces that will take part
6530 	 * in replication.  We do so because multirouting is
6531 	 * reflective, thus we will probably receive multi-
6532 	 * casts on those interfaces.
6533 	 * The ip_multirt_apply_membership() succeeds if
6534 	 * the operation succeeds on at least one interface.
6535 	 */
6536 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6537 		ipaddr_t group;
6538 
6539 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6540 
6541 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6542 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6543 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6544 	} else {
6545 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6546 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6547 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6548 	}
6549 	if (ire != NULL) {
6550 		if (ire->ire_flags & RTF_MULTIRT) {
6551 			error = ip_multirt_apply_membership(optfn, ire, connp,
6552 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6553 			done = B_TRUE;
6554 		}
6555 		ire_refrele(ire);
6556 	}
6557 
6558 	if (!done) {
6559 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6560 		    fmode, &ipv6_all_zeros);
6561 	}
6562 	return (error);
6563 }
6564 
6565 /*
6566  * Set socket options for joining and leaving multicast groups
6567  * for specific sources.
6568  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6569  * The caller has already check that the option name is consistent with
6570  * the address family of the socket.
6571  */
6572 int
6573 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6574     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6575 {
6576 	int		*i1 = (int *)invalp;
6577 	int		error = 0;
6578 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6579 	struct ip_mreq_source *imreqp;
6580 	struct group_source_req *gsreqp;
6581 	in6_addr_t v6group, v6src;
6582 	uint32_t ifindex;
6583 	ipaddr_t ifaddr;
6584 	boolean_t mcast_opt = B_TRUE;
6585 	mcast_record_t fmode;
6586 	ire_t *ire;
6587 	boolean_t done = B_FALSE;
6588 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6589 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6590 
6591 	switch (name) {
6592 	case IP_BLOCK_SOURCE:
6593 		mcast_opt = B_FALSE;
6594 		/* FALLTHRU */
6595 	case MCAST_BLOCK_SOURCE:
6596 		fmode = MODE_IS_EXCLUDE;
6597 		optfn = ip_opt_add_group;
6598 		break;
6599 
6600 	case IP_UNBLOCK_SOURCE:
6601 		mcast_opt = B_FALSE;
6602 		/* FALLTHRU */
6603 	case MCAST_UNBLOCK_SOURCE:
6604 		fmode = MODE_IS_EXCLUDE;
6605 		optfn = ip_opt_delete_group;
6606 		break;
6607 
6608 	case IP_ADD_SOURCE_MEMBERSHIP:
6609 		mcast_opt = B_FALSE;
6610 		/* FALLTHRU */
6611 	case MCAST_JOIN_SOURCE_GROUP:
6612 		fmode = MODE_IS_INCLUDE;
6613 		optfn = ip_opt_add_group;
6614 		break;
6615 
6616 	case IP_DROP_SOURCE_MEMBERSHIP:
6617 		mcast_opt = B_FALSE;
6618 		/* FALLTHRU */
6619 	case MCAST_LEAVE_SOURCE_GROUP:
6620 		fmode = MODE_IS_INCLUDE;
6621 		optfn = ip_opt_delete_group;
6622 		break;
6623 	default:
6624 		ASSERT(0);
6625 	}
6626 
6627 	if (mcast_opt) {
6628 		gsreqp = (struct group_source_req *)i1;
6629 		ifindex = gsreqp->gsr_interface;
6630 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6631 			struct sockaddr_in *s;
6632 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6633 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6634 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6635 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6636 		} else {
6637 			struct sockaddr_in6 *s6;
6638 
6639 			if (!inet6)
6640 				return (EINVAL);	/* Not on INET socket */
6641 
6642 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6643 			v6group = s6->sin6_addr;
6644 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6645 			v6src = s6->sin6_addr;
6646 		}
6647 		ifaddr = INADDR_ANY;
6648 	} else {
6649 		imreqp = (struct ip_mreq_source *)i1;
6650 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6651 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6652 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6653 		ifindex = 0;
6654 	}
6655 
6656 	/*
6657 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6658 	 */
6659 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6660 		v6src = ipv6_all_zeros;
6661 
6662 	/*
6663 	 * In the multirouting case, we need to replicate
6664 	 * the request as noted in the mcast cases above.
6665 	 */
6666 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6667 		ipaddr_t group;
6668 
6669 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6670 
6671 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6672 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6673 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6674 	} else {
6675 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6676 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6677 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6678 	}
6679 	if (ire != NULL) {
6680 		if (ire->ire_flags & RTF_MULTIRT) {
6681 			error = ip_multirt_apply_membership(optfn, ire, connp,
6682 			    checkonly, &v6group, fmode, &v6src);
6683 			done = B_TRUE;
6684 		}
6685 		ire_refrele(ire);
6686 	}
6687 	if (!done) {
6688 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6689 		    fmode, &v6src);
6690 	}
6691 	return (error);
6692 }
6693 
6694 /*
6695  * Given a destination address and a pointer to where to put the information
6696  * this routine fills in the mtuinfo.
6697  * The socket must be connected.
6698  * For sctp conn_faddr is the primary address.
6699  */
6700 int
6701 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6702 {
6703 	uint32_t	pmtu = IP_MAXPACKET;
6704 	uint_t		scopeid;
6705 
6706 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6707 		return (-1);
6708 
6709 	/* In case we never sent or called ip_set_destination_v4/v6 */
6710 	if (ixa->ixa_ire != NULL)
6711 		pmtu = ip_get_pmtu(ixa);
6712 
6713 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6714 		scopeid = ixa->ixa_scopeid;
6715 	else
6716 		scopeid = 0;
6717 
6718 	bzero(mtuinfo, sizeof (*mtuinfo));
6719 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6720 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6721 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6722 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6723 	mtuinfo->ip6m_mtu = pmtu;
6724 
6725 	return (sizeof (struct ip6_mtuinfo));
6726 }
6727 
6728 /* Named Dispatch routine to get a current value out of our parameter table. */
6729 /* ARGSUSED */
6730 static int
6731 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
6732 {
6733 	ipparam_t *ippa = (ipparam_t *)cp;
6734 
6735 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
6736 	return (0);
6737 }
6738 
6739 /* ARGSUSED */
6740 static int
6741 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
6742 {
6743 
6744 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
6745 	return (0);
6746 }
6747 
6748 /*
6749  * Set ip{,6}_forwarding values.  This means walking through all of the
6750  * ill's and toggling their forwarding values.
6751  */
6752 /* ARGSUSED */
6753 static int
6754 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
6755 {
6756 	long new_value;
6757 	int *forwarding_value = (int *)cp;
6758 	ill_t *ill;
6759 	boolean_t isv6;
6760 	ill_walk_context_t ctx;
6761 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
6762 
6763 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
6764 
6765 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6766 	    new_value < 0 || new_value > 1) {
6767 		return (EINVAL);
6768 	}
6769 
6770 	*forwarding_value = new_value;
6771 
6772 	/*
6773 	 * Regardless of the current value of ip_forwarding, set all per-ill
6774 	 * values of ip_forwarding to the value being set.
6775 	 *
6776 	 * Bring all the ill's up to date with the new global value.
6777 	 */
6778 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
6779 
6780 	if (isv6)
6781 		ill = ILL_START_WALK_V6(&ctx, ipst);
6782 	else
6783 		ill = ILL_START_WALK_V4(&ctx, ipst);
6784 
6785 	for (; ill != NULL; ill = ill_next(&ctx, ill))
6786 		(void) ill_forward_set(ill, new_value != 0);
6787 
6788 	rw_exit(&ipst->ips_ill_g_lock);
6789 	return (0);
6790 }
6791 
6792 /*
6793  * Walk through the param array specified registering each element with the
6794  * Named Dispatch handler. This is called only during init. So it is ok
6795  * not to acquire any locks
6796  */
6797 static boolean_t
6798 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
6799     ipndp_t *ipnd, size_t ipnd_cnt)
6800 {
6801 	for (; ippa_cnt-- > 0; ippa++) {
6802 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
6803 			if (!nd_load(ndp, ippa->ip_param_name,
6804 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
6805 				nd_free(ndp);
6806 				return (B_FALSE);
6807 			}
6808 		}
6809 	}
6810 
6811 	for (; ipnd_cnt-- > 0; ipnd++) {
6812 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
6813 			if (!nd_load(ndp, ipnd->ip_ndp_name,
6814 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
6815 			    ipnd->ip_ndp_data)) {
6816 				nd_free(ndp);
6817 				return (B_FALSE);
6818 			}
6819 		}
6820 	}
6821 
6822 	return (B_TRUE);
6823 }
6824 
6825 /*
6826  * When the src multihoming is changed from weak to [strong, preferred]
6827  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6828  * and identify routes that were created by user-applications in the
6829  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6830  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6831  * is selected by finding an interface route for the gateway.
6832  */
6833 /* ARGSUSED */
6834 static void
6835 ip_ire_rebind_walker(ire_t *ire, void *notused)
6836 {
6837 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6838 		return;
6839 	ire_rebind(ire);
6840 	ire_delete(ire);
6841 }
6842 
6843 /*
6844  * When the src multihoming is changed from  [strong, preferred] to weak,
6845  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6846  * set any entries that were created by user-applications in the unbound state
6847  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6848  */
6849 /* ARGSUSED */
6850 static void
6851 ip_ire_unbind_walker(ire_t *ire, void *notused)
6852 {
6853 	ire_t *new_ire;
6854 
6855 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6856 		return;
6857 	if (ire->ire_ipversion == IPV6_VERSION) {
6858 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6859 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6860 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6861 	} else {
6862 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6863 		    (uchar_t *)&ire->ire_mask,
6864 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6865 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6866 	}
6867 	if (new_ire == NULL)
6868 		return;
6869 	new_ire->ire_unbound = B_TRUE;
6870 	/*
6871 	 * The bound ire must first be deleted so that we don't return
6872 	 * the existing one on the attempt to add the unbound new_ire.
6873 	 */
6874 	ire_delete(ire);
6875 	new_ire = ire_add(new_ire);
6876 	if (new_ire != NULL)
6877 		ire_refrele(new_ire);
6878 }
6879 
6880 /*
6881  * When the settings of ip*_strict_src_multihoming tunables are changed,
6882  * all cached routes need to be recomputed. This recomputation needs to be
6883  * done when going from weaker to stronger modes so that the cached ire
6884  * for the connection does not violate the current ip*_strict_src_multihoming
6885  * setting. It also needs to be done when going from stronger to weaker modes,
6886  * so that we fall back to matching on the longest-matching-route (as opposed
6887  * to a shorter match that may have been selected in the strong mode
6888  * to satisfy src_multihoming settings).
6889  *
6890  * The cached ixa_ire entires for all conn_t entries are marked as
6891  * "verify" so that they will be recomputed for the next packet.
6892  */
6893 static void
6894 conn_ire_revalidate(conn_t *connp, void *arg)
6895 {
6896 	boolean_t isv6 = (boolean_t)arg;
6897 
6898 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6899 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6900 		return;
6901 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6902 }
6903 
6904 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
6905 /* ARGSUSED */
6906 static int
6907 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
6908 {
6909 	long		new_value;
6910 	ipparam_t	*ippa = (ipparam_t *)cp;
6911 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
6912 	int		strict_src4, strict_src6;
6913 
6914 	strict_src4 = ipst->ips_ip_strict_src_multihoming;
6915 	strict_src6 = ipst->ips_ipv6_strict_src_multihoming;
6916 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6917 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
6918 		return (EINVAL);
6919 	}
6920 	ippa->ip_param_value = new_value;
6921 	if (ipst->ips_ip_strict_src_multihoming != strict_src4) {
6922 		if (strict_src4 == 0) {
6923 			ire_walk_v4(ip_ire_rebind_walker, NULL, ALL_ZONES,
6924 			    ipst);
6925 		} else {
6926 			ire_walk_v4(ip_ire_unbind_walker, NULL, ALL_ZONES,
6927 			    ipst);
6928 		}
6929 		ipcl_walk(conn_ire_revalidate, (void *)B_FALSE, ipst);
6930 	} else if (ipst->ips_ipv6_strict_src_multihoming != strict_src6) {
6931 		if (strict_src6 == 0) {
6932 			ire_walk_v6(ip_ire_rebind_walker, NULL, ALL_ZONES,
6933 			    ipst);
6934 		} else {
6935 			ire_walk_v4(ip_ire_unbind_walker, NULL, ALL_ZONES,
6936 			    ipst);
6937 		}
6938 		ipcl_walk(conn_ire_revalidate, (void *)B_TRUE, ipst);
6939 	}
6940 	return (0);
6941 }
6942 
6943 /*
6944  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6945  * When an ipf is passed here for the first time, if
6946  * we already have in-order fragments on the queue, we convert from the fast-
6947  * path reassembly scheme to the hard-case scheme.  From then on, additional
6948  * fragments are reassembled here.  We keep track of the start and end offsets
6949  * of each piece, and the number of holes in the chain.  When the hole count
6950  * goes to zero, we are done!
6951  *
6952  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6953  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6954  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6955  * after the call to ip_reassemble().
6956  */
6957 int
6958 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6959     size_t msg_len)
6960 {
6961 	uint_t	end;
6962 	mblk_t	*next_mp;
6963 	mblk_t	*mp1;
6964 	uint_t	offset;
6965 	boolean_t incr_dups = B_TRUE;
6966 	boolean_t offset_zero_seen = B_FALSE;
6967 	boolean_t pkt_boundary_checked = B_FALSE;
6968 
6969 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6970 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6971 
6972 	/* Add in byte count */
6973 	ipf->ipf_count += msg_len;
6974 	if (ipf->ipf_end) {
6975 		/*
6976 		 * We were part way through in-order reassembly, but now there
6977 		 * is a hole.  We walk through messages already queued, and
6978 		 * mark them for hard case reassembly.  We know that up till
6979 		 * now they were in order starting from offset zero.
6980 		 */
6981 		offset = 0;
6982 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6983 			IP_REASS_SET_START(mp1, offset);
6984 			if (offset == 0) {
6985 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6986 				offset = -ipf->ipf_nf_hdr_len;
6987 			}
6988 			offset += mp1->b_wptr - mp1->b_rptr;
6989 			IP_REASS_SET_END(mp1, offset);
6990 		}
6991 		/* One hole at the end. */
6992 		ipf->ipf_hole_cnt = 1;
6993 		/* Brand it as a hard case, forever. */
6994 		ipf->ipf_end = 0;
6995 	}
6996 	/* Walk through all the new pieces. */
6997 	do {
6998 		end = start + (mp->b_wptr - mp->b_rptr);
6999 		/*
7000 		 * If start is 0, decrease 'end' only for the first mblk of
7001 		 * the fragment. Otherwise 'end' can get wrong value in the
7002 		 * second pass of the loop if first mblk is exactly the
7003 		 * size of ipf_nf_hdr_len.
7004 		 */
7005 		if (start == 0 && !offset_zero_seen) {
7006 			/* First segment */
7007 			ASSERT(ipf->ipf_nf_hdr_len != 0);
7008 			end -= ipf->ipf_nf_hdr_len;
7009 			offset_zero_seen = B_TRUE;
7010 		}
7011 		next_mp = mp->b_cont;
7012 		/*
7013 		 * We are checking to see if there is any interesing data
7014 		 * to process.  If there isn't and the mblk isn't the
7015 		 * one which carries the unfragmentable header then we
7016 		 * drop it.  It's possible to have just the unfragmentable
7017 		 * header come through without any data.  That needs to be
7018 		 * saved.
7019 		 *
7020 		 * If the assert at the top of this function holds then the
7021 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
7022 		 * is infrequently traveled enough that the test is left in
7023 		 * to protect against future code changes which break that
7024 		 * invariant.
7025 		 */
7026 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
7027 			/* Empty.  Blast it. */
7028 			IP_REASS_SET_START(mp, 0);
7029 			IP_REASS_SET_END(mp, 0);
7030 			/*
7031 			 * If the ipf points to the mblk we are about to free,
7032 			 * update ipf to point to the next mblk (or NULL
7033 			 * if none).
7034 			 */
7035 			if (ipf->ipf_mp->b_cont == mp)
7036 				ipf->ipf_mp->b_cont = next_mp;
7037 			freeb(mp);
7038 			continue;
7039 		}
7040 		mp->b_cont = NULL;
7041 		IP_REASS_SET_START(mp, start);
7042 		IP_REASS_SET_END(mp, end);
7043 		if (!ipf->ipf_tail_mp) {
7044 			ipf->ipf_tail_mp = mp;
7045 			ipf->ipf_mp->b_cont = mp;
7046 			if (start == 0 || !more) {
7047 				ipf->ipf_hole_cnt = 1;
7048 				/*
7049 				 * if the first fragment comes in more than one
7050 				 * mblk, this loop will be executed for each
7051 				 * mblk. Need to adjust hole count so exiting
7052 				 * this routine will leave hole count at 1.
7053 				 */
7054 				if (next_mp)
7055 					ipf->ipf_hole_cnt++;
7056 			} else
7057 				ipf->ipf_hole_cnt = 2;
7058 			continue;
7059 		} else if (ipf->ipf_last_frag_seen && !more &&
7060 		    !pkt_boundary_checked) {
7061 			/*
7062 			 * We check datagram boundary only if this fragment
7063 			 * claims to be the last fragment and we have seen a
7064 			 * last fragment in the past too. We do this only
7065 			 * once for a given fragment.
7066 			 *
7067 			 * start cannot be 0 here as fragments with start=0
7068 			 * and MF=0 gets handled as a complete packet. These
7069 			 * fragments should not reach here.
7070 			 */
7071 
7072 			if (start + msgdsize(mp) !=
7073 			    IP_REASS_END(ipf->ipf_tail_mp)) {
7074 				/*
7075 				 * We have two fragments both of which claim
7076 				 * to be the last fragment but gives conflicting
7077 				 * information about the whole datagram size.
7078 				 * Something fishy is going on. Drop the
7079 				 * fragment and free up the reassembly list.
7080 				 */
7081 				return (IP_REASS_FAILED);
7082 			}
7083 
7084 			/*
7085 			 * We shouldn't come to this code block again for this
7086 			 * particular fragment.
7087 			 */
7088 			pkt_boundary_checked = B_TRUE;
7089 		}
7090 
7091 		/* New stuff at or beyond tail? */
7092 		offset = IP_REASS_END(ipf->ipf_tail_mp);
7093 		if (start >= offset) {
7094 			if (ipf->ipf_last_frag_seen) {
7095 				/* current fragment is beyond last fragment */
7096 				return (IP_REASS_FAILED);
7097 			}
7098 			/* Link it on end. */
7099 			ipf->ipf_tail_mp->b_cont = mp;
7100 			ipf->ipf_tail_mp = mp;
7101 			if (more) {
7102 				if (start != offset)
7103 					ipf->ipf_hole_cnt++;
7104 			} else if (start == offset && next_mp == NULL)
7105 					ipf->ipf_hole_cnt--;
7106 			continue;
7107 		}
7108 		mp1 = ipf->ipf_mp->b_cont;
7109 		offset = IP_REASS_START(mp1);
7110 		/* New stuff at the front? */
7111 		if (start < offset) {
7112 			if (start == 0) {
7113 				if (end >= offset) {
7114 					/* Nailed the hole at the begining. */
7115 					ipf->ipf_hole_cnt--;
7116 				}
7117 			} else if (end < offset) {
7118 				/*
7119 				 * A hole, stuff, and a hole where there used
7120 				 * to be just a hole.
7121 				 */
7122 				ipf->ipf_hole_cnt++;
7123 			}
7124 			mp->b_cont = mp1;
7125 			/* Check for overlap. */
7126 			while (end > offset) {
7127 				if (end < IP_REASS_END(mp1)) {
7128 					mp->b_wptr -= end - offset;
7129 					IP_REASS_SET_END(mp, offset);
7130 					BUMP_MIB(ill->ill_ip_mib,
7131 					    ipIfStatsReasmPartDups);
7132 					break;
7133 				}
7134 				/* Did we cover another hole? */
7135 				if ((mp1->b_cont &&
7136 				    IP_REASS_END(mp1) !=
7137 				    IP_REASS_START(mp1->b_cont) &&
7138 				    end >= IP_REASS_START(mp1->b_cont)) ||
7139 				    (!ipf->ipf_last_frag_seen && !more)) {
7140 					ipf->ipf_hole_cnt--;
7141 				}
7142 				/* Clip out mp1. */
7143 				if ((mp->b_cont = mp1->b_cont) == NULL) {
7144 					/*
7145 					 * After clipping out mp1, this guy
7146 					 * is now hanging off the end.
7147 					 */
7148 					ipf->ipf_tail_mp = mp;
7149 				}
7150 				IP_REASS_SET_START(mp1, 0);
7151 				IP_REASS_SET_END(mp1, 0);
7152 				/* Subtract byte count */
7153 				ipf->ipf_count -= mp1->b_datap->db_lim -
7154 				    mp1->b_datap->db_base;
7155 				freeb(mp1);
7156 				BUMP_MIB(ill->ill_ip_mib,
7157 				    ipIfStatsReasmPartDups);
7158 				mp1 = mp->b_cont;
7159 				if (!mp1)
7160 					break;
7161 				offset = IP_REASS_START(mp1);
7162 			}
7163 			ipf->ipf_mp->b_cont = mp;
7164 			continue;
7165 		}
7166 		/*
7167 		 * The new piece starts somewhere between the start of the head
7168 		 * and before the end of the tail.
7169 		 */
7170 		for (; mp1; mp1 = mp1->b_cont) {
7171 			offset = IP_REASS_END(mp1);
7172 			if (start < offset) {
7173 				if (end <= offset) {
7174 					/* Nothing new. */
7175 					IP_REASS_SET_START(mp, 0);
7176 					IP_REASS_SET_END(mp, 0);
7177 					/* Subtract byte count */
7178 					ipf->ipf_count -= mp->b_datap->db_lim -
7179 					    mp->b_datap->db_base;
7180 					if (incr_dups) {
7181 						ipf->ipf_num_dups++;
7182 						incr_dups = B_FALSE;
7183 					}
7184 					freeb(mp);
7185 					BUMP_MIB(ill->ill_ip_mib,
7186 					    ipIfStatsReasmDuplicates);
7187 					break;
7188 				}
7189 				/*
7190 				 * Trim redundant stuff off beginning of new
7191 				 * piece.
7192 				 */
7193 				IP_REASS_SET_START(mp, offset);
7194 				mp->b_rptr += offset - start;
7195 				BUMP_MIB(ill->ill_ip_mib,
7196 				    ipIfStatsReasmPartDups);
7197 				start = offset;
7198 				if (!mp1->b_cont) {
7199 					/*
7200 					 * After trimming, this guy is now
7201 					 * hanging off the end.
7202 					 */
7203 					mp1->b_cont = mp;
7204 					ipf->ipf_tail_mp = mp;
7205 					if (!more) {
7206 						ipf->ipf_hole_cnt--;
7207 					}
7208 					break;
7209 				}
7210 			}
7211 			if (start >= IP_REASS_START(mp1->b_cont))
7212 				continue;
7213 			/* Fill a hole */
7214 			if (start > offset)
7215 				ipf->ipf_hole_cnt++;
7216 			mp->b_cont = mp1->b_cont;
7217 			mp1->b_cont = mp;
7218 			mp1 = mp->b_cont;
7219 			offset = IP_REASS_START(mp1);
7220 			if (end >= offset) {
7221 				ipf->ipf_hole_cnt--;
7222 				/* Check for overlap. */
7223 				while (end > offset) {
7224 					if (end < IP_REASS_END(mp1)) {
7225 						mp->b_wptr -= end - offset;
7226 						IP_REASS_SET_END(mp, offset);
7227 						/*
7228 						 * TODO we might bump
7229 						 * this up twice if there is
7230 						 * overlap at both ends.
7231 						 */
7232 						BUMP_MIB(ill->ill_ip_mib,
7233 						    ipIfStatsReasmPartDups);
7234 						break;
7235 					}
7236 					/* Did we cover another hole? */
7237 					if ((mp1->b_cont &&
7238 					    IP_REASS_END(mp1)
7239 					    != IP_REASS_START(mp1->b_cont) &&
7240 					    end >=
7241 					    IP_REASS_START(mp1->b_cont)) ||
7242 					    (!ipf->ipf_last_frag_seen &&
7243 					    !more)) {
7244 						ipf->ipf_hole_cnt--;
7245 					}
7246 					/* Clip out mp1. */
7247 					if ((mp->b_cont = mp1->b_cont) ==
7248 					    NULL) {
7249 						/*
7250 						 * After clipping out mp1,
7251 						 * this guy is now hanging
7252 						 * off the end.
7253 						 */
7254 						ipf->ipf_tail_mp = mp;
7255 					}
7256 					IP_REASS_SET_START(mp1, 0);
7257 					IP_REASS_SET_END(mp1, 0);
7258 					/* Subtract byte count */
7259 					ipf->ipf_count -=
7260 					    mp1->b_datap->db_lim -
7261 					    mp1->b_datap->db_base;
7262 					freeb(mp1);
7263 					BUMP_MIB(ill->ill_ip_mib,
7264 					    ipIfStatsReasmPartDups);
7265 					mp1 = mp->b_cont;
7266 					if (!mp1)
7267 						break;
7268 					offset = IP_REASS_START(mp1);
7269 				}
7270 			}
7271 			break;
7272 		}
7273 	} while (start = end, mp = next_mp);
7274 
7275 	/* Fragment just processed could be the last one. Remember this fact */
7276 	if (!more)
7277 		ipf->ipf_last_frag_seen = B_TRUE;
7278 
7279 	/* Still got holes? */
7280 	if (ipf->ipf_hole_cnt)
7281 		return (IP_REASS_PARTIAL);
7282 	/* Clean up overloaded fields to avoid upstream disasters. */
7283 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
7284 		IP_REASS_SET_START(mp1, 0);
7285 		IP_REASS_SET_END(mp1, 0);
7286 	}
7287 	return (IP_REASS_COMPLETE);
7288 }
7289 
7290 /*
7291  * Fragmentation reassembly.  Each ILL has a hash table for
7292  * queuing packets undergoing reassembly for all IPIFs
7293  * associated with the ILL.  The hash is based on the packet
7294  * IP ident field.  The ILL frag hash table was allocated
7295  * as a timer block at the time the ILL was created.  Whenever
7296  * there is anything on the reassembly queue, the timer will
7297  * be running.  Returns the reassembled packet if reassembly completes.
7298  */
7299 mblk_t *
7300 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
7301 {
7302 	uint32_t	frag_offset_flags;
7303 	mblk_t		*t_mp;
7304 	ipaddr_t	dst;
7305 	uint8_t		proto = ipha->ipha_protocol;
7306 	uint32_t	sum_val;
7307 	uint16_t	sum_flags;
7308 	ipf_t		*ipf;
7309 	ipf_t		**ipfp;
7310 	ipfb_t		*ipfb;
7311 	uint16_t	ident;
7312 	uint32_t	offset;
7313 	ipaddr_t	src;
7314 	uint_t		hdr_length;
7315 	uint32_t	end;
7316 	mblk_t		*mp1;
7317 	mblk_t		*tail_mp;
7318 	size_t		count;
7319 	size_t		msg_len;
7320 	uint8_t		ecn_info = 0;
7321 	uint32_t	packet_size;
7322 	boolean_t	pruned = B_FALSE;
7323 	ill_t		*ill = ira->ira_ill;
7324 	ip_stack_t	*ipst = ill->ill_ipst;
7325 
7326 	/*
7327 	 * Drop the fragmented as early as possible, if
7328 	 * we don't have resource(s) to re-assemble.
7329 	 */
7330 	if (ipst->ips_ip_reass_queue_bytes == 0) {
7331 		freemsg(mp);
7332 		return (NULL);
7333 	}
7334 
7335 	/* Check for fragmentation offset; return if there's none */
7336 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7337 	    (IPH_MF | IPH_OFFSET)) == 0)
7338 		return (mp);
7339 
7340 	/*
7341 	 * We utilize hardware computed checksum info only for UDP since
7342 	 * IP fragmentation is a normal occurrence for the protocol.  In
7343 	 * addition, checksum offload support for IP fragments carrying
7344 	 * UDP payload is commonly implemented across network adapters.
7345 	 */
7346 	ASSERT(ira->ira_rill != NULL);
7347 	if (proto == IPPROTO_UDP && dohwcksum &&
7348 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7349 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7350 		mblk_t *mp1 = mp->b_cont;
7351 		int32_t len;
7352 
7353 		/* Record checksum information from the packet */
7354 		sum_val = (uint32_t)DB_CKSUM16(mp);
7355 		sum_flags = DB_CKSUMFLAGS(mp);
7356 
7357 		/* IP payload offset from beginning of mblk */
7358 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7359 
7360 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7361 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7362 		    offset >= DB_CKSUMSTART(mp) &&
7363 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7364 			uint32_t adj;
7365 			/*
7366 			 * Partial checksum has been calculated by hardware
7367 			 * and attached to the packet; in addition, any
7368 			 * prepended extraneous data is even byte aligned.
7369 			 * If any such data exists, we adjust the checksum;
7370 			 * this would also handle any postpended data.
7371 			 */
7372 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7373 			    mp, mp1, len, adj);
7374 
7375 			/* One's complement subtract extraneous checksum */
7376 			if (adj >= sum_val)
7377 				sum_val = ~(adj - sum_val) & 0xFFFF;
7378 			else
7379 				sum_val -= adj;
7380 		}
7381 	} else {
7382 		sum_val = 0;
7383 		sum_flags = 0;
7384 	}
7385 
7386 	/* Clear hardware checksumming flag */
7387 	DB_CKSUMFLAGS(mp) = 0;
7388 
7389 	ident = ipha->ipha_ident;
7390 	offset = (frag_offset_flags << 3) & 0xFFFF;
7391 	src = ipha->ipha_src;
7392 	dst = ipha->ipha_dst;
7393 	hdr_length = IPH_HDR_LENGTH(ipha);
7394 	end = ntohs(ipha->ipha_length) - hdr_length;
7395 
7396 	/* If end == 0 then we have a packet with no data, so just free it */
7397 	if (end == 0) {
7398 		freemsg(mp);
7399 		return (NULL);
7400 	}
7401 
7402 	/* Record the ECN field info. */
7403 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7404 	if (offset != 0) {
7405 		/*
7406 		 * If this isn't the first piece, strip the header, and
7407 		 * add the offset to the end value.
7408 		 */
7409 		mp->b_rptr += hdr_length;
7410 		end += offset;
7411 	}
7412 
7413 	/* Handle vnic loopback of fragments */
7414 	if (mp->b_datap->db_ref > 2)
7415 		msg_len = 0;
7416 	else
7417 		msg_len = MBLKSIZE(mp);
7418 
7419 	tail_mp = mp;
7420 	while (tail_mp->b_cont != NULL) {
7421 		tail_mp = tail_mp->b_cont;
7422 		if (tail_mp->b_datap->db_ref <= 2)
7423 			msg_len += MBLKSIZE(tail_mp);
7424 	}
7425 
7426 	/* If the reassembly list for this ILL will get too big, prune it */
7427 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7428 	    ipst->ips_ip_reass_queue_bytes) {
7429 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7430 		    uint_t, ill->ill_frag_count,
7431 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7432 		ill_frag_prune(ill,
7433 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7434 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7435 		pruned = B_TRUE;
7436 	}
7437 
7438 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7439 	mutex_enter(&ipfb->ipfb_lock);
7440 
7441 	ipfp = &ipfb->ipfb_ipf;
7442 	/* Try to find an existing fragment queue for this packet. */
7443 	for (;;) {
7444 		ipf = ipfp[0];
7445 		if (ipf != NULL) {
7446 			/*
7447 			 * It has to match on ident and src/dst address.
7448 			 */
7449 			if (ipf->ipf_ident == ident &&
7450 			    ipf->ipf_src == src &&
7451 			    ipf->ipf_dst == dst &&
7452 			    ipf->ipf_protocol == proto) {
7453 				/*
7454 				 * If we have received too many
7455 				 * duplicate fragments for this packet
7456 				 * free it.
7457 				 */
7458 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7459 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7460 					freemsg(mp);
7461 					mutex_exit(&ipfb->ipfb_lock);
7462 					return (NULL);
7463 				}
7464 				/* Found it. */
7465 				break;
7466 			}
7467 			ipfp = &ipf->ipf_hash_next;
7468 			continue;
7469 		}
7470 
7471 		/*
7472 		 * If we pruned the list, do we want to store this new
7473 		 * fragment?. We apply an optimization here based on the
7474 		 * fact that most fragments will be received in order.
7475 		 * So if the offset of this incoming fragment is zero,
7476 		 * it is the first fragment of a new packet. We will
7477 		 * keep it.  Otherwise drop the fragment, as we have
7478 		 * probably pruned the packet already (since the
7479 		 * packet cannot be found).
7480 		 */
7481 		if (pruned && offset != 0) {
7482 			mutex_exit(&ipfb->ipfb_lock);
7483 			freemsg(mp);
7484 			return (NULL);
7485 		}
7486 
7487 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7488 			/*
7489 			 * Too many fragmented packets in this hash
7490 			 * bucket. Free the oldest.
7491 			 */
7492 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7493 		}
7494 
7495 		/* New guy.  Allocate a frag message. */
7496 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7497 		if (mp1 == NULL) {
7498 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7499 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7500 			freemsg(mp);
7501 reass_done:
7502 			mutex_exit(&ipfb->ipfb_lock);
7503 			return (NULL);
7504 		}
7505 
7506 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7507 		mp1->b_cont = mp;
7508 
7509 		/* Initialize the fragment header. */
7510 		ipf = (ipf_t *)mp1->b_rptr;
7511 		ipf->ipf_mp = mp1;
7512 		ipf->ipf_ptphn = ipfp;
7513 		ipfp[0] = ipf;
7514 		ipf->ipf_hash_next = NULL;
7515 		ipf->ipf_ident = ident;
7516 		ipf->ipf_protocol = proto;
7517 		ipf->ipf_src = src;
7518 		ipf->ipf_dst = dst;
7519 		ipf->ipf_nf_hdr_len = 0;
7520 		/* Record reassembly start time. */
7521 		ipf->ipf_timestamp = gethrestime_sec();
7522 		/* Record ipf generation and account for frag header */
7523 		ipf->ipf_gen = ill->ill_ipf_gen++;
7524 		ipf->ipf_count = MBLKSIZE(mp1);
7525 		ipf->ipf_last_frag_seen = B_FALSE;
7526 		ipf->ipf_ecn = ecn_info;
7527 		ipf->ipf_num_dups = 0;
7528 		ipfb->ipfb_frag_pkts++;
7529 		ipf->ipf_checksum = 0;
7530 		ipf->ipf_checksum_flags = 0;
7531 
7532 		/* Store checksum value in fragment header */
7533 		if (sum_flags != 0) {
7534 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7535 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7536 			ipf->ipf_checksum = sum_val;
7537 			ipf->ipf_checksum_flags = sum_flags;
7538 		}
7539 
7540 		/*
7541 		 * We handle reassembly two ways.  In the easy case,
7542 		 * where all the fragments show up in order, we do
7543 		 * minimal bookkeeping, and just clip new pieces on
7544 		 * the end.  If we ever see a hole, then we go off
7545 		 * to ip_reassemble which has to mark the pieces and
7546 		 * keep track of the number of holes, etc.  Obviously,
7547 		 * the point of having both mechanisms is so we can
7548 		 * handle the easy case as efficiently as possible.
7549 		 */
7550 		if (offset == 0) {
7551 			/* Easy case, in-order reassembly so far. */
7552 			ipf->ipf_count += msg_len;
7553 			ipf->ipf_tail_mp = tail_mp;
7554 			/*
7555 			 * Keep track of next expected offset in
7556 			 * ipf_end.
7557 			 */
7558 			ipf->ipf_end = end;
7559 			ipf->ipf_nf_hdr_len = hdr_length;
7560 		} else {
7561 			/* Hard case, hole at the beginning. */
7562 			ipf->ipf_tail_mp = NULL;
7563 			/*
7564 			 * ipf_end == 0 means that we have given up
7565 			 * on easy reassembly.
7566 			 */
7567 			ipf->ipf_end = 0;
7568 
7569 			/* Forget checksum offload from now on */
7570 			ipf->ipf_checksum_flags = 0;
7571 
7572 			/*
7573 			 * ipf_hole_cnt is set by ip_reassemble.
7574 			 * ipf_count is updated by ip_reassemble.
7575 			 * No need to check for return value here
7576 			 * as we don't expect reassembly to complete
7577 			 * or fail for the first fragment itself.
7578 			 */
7579 			(void) ip_reassemble(mp, ipf,
7580 			    (frag_offset_flags & IPH_OFFSET) << 3,
7581 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7582 		}
7583 		/* Update per ipfb and ill byte counts */
7584 		ipfb->ipfb_count += ipf->ipf_count;
7585 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7586 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7587 		/* If the frag timer wasn't already going, start it. */
7588 		mutex_enter(&ill->ill_lock);
7589 		ill_frag_timer_start(ill);
7590 		mutex_exit(&ill->ill_lock);
7591 		goto reass_done;
7592 	}
7593 
7594 	/*
7595 	 * If the packet's flag has changed (it could be coming up
7596 	 * from an interface different than the previous, therefore
7597 	 * possibly different checksum capability), then forget about
7598 	 * any stored checksum states.  Otherwise add the value to
7599 	 * the existing one stored in the fragment header.
7600 	 */
7601 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7602 		sum_val += ipf->ipf_checksum;
7603 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7604 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7605 		ipf->ipf_checksum = sum_val;
7606 	} else if (ipf->ipf_checksum_flags != 0) {
7607 		/* Forget checksum offload from now on */
7608 		ipf->ipf_checksum_flags = 0;
7609 	}
7610 
7611 	/*
7612 	 * We have a new piece of a datagram which is already being
7613 	 * reassembled.  Update the ECN info if all IP fragments
7614 	 * are ECN capable.  If there is one which is not, clear
7615 	 * all the info.  If there is at least one which has CE
7616 	 * code point, IP needs to report that up to transport.
7617 	 */
7618 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7619 		if (ecn_info == IPH_ECN_CE)
7620 			ipf->ipf_ecn = IPH_ECN_CE;
7621 	} else {
7622 		ipf->ipf_ecn = IPH_ECN_NECT;
7623 	}
7624 	if (offset && ipf->ipf_end == offset) {
7625 		/* The new fragment fits at the end */
7626 		ipf->ipf_tail_mp->b_cont = mp;
7627 		/* Update the byte count */
7628 		ipf->ipf_count += msg_len;
7629 		/* Update per ipfb and ill byte counts */
7630 		ipfb->ipfb_count += msg_len;
7631 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7632 		atomic_add_32(&ill->ill_frag_count, msg_len);
7633 		if (frag_offset_flags & IPH_MF) {
7634 			/* More to come. */
7635 			ipf->ipf_end = end;
7636 			ipf->ipf_tail_mp = tail_mp;
7637 			goto reass_done;
7638 		}
7639 	} else {
7640 		/* Go do the hard cases. */
7641 		int ret;
7642 
7643 		if (offset == 0)
7644 			ipf->ipf_nf_hdr_len = hdr_length;
7645 
7646 		/* Save current byte count */
7647 		count = ipf->ipf_count;
7648 		ret = ip_reassemble(mp, ipf,
7649 		    (frag_offset_flags & IPH_OFFSET) << 3,
7650 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7651 		/* Count of bytes added and subtracted (freeb()ed) */
7652 		count = ipf->ipf_count - count;
7653 		if (count) {
7654 			/* Update per ipfb and ill byte counts */
7655 			ipfb->ipfb_count += count;
7656 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7657 			atomic_add_32(&ill->ill_frag_count, count);
7658 		}
7659 		if (ret == IP_REASS_PARTIAL) {
7660 			goto reass_done;
7661 		} else if (ret == IP_REASS_FAILED) {
7662 			/* Reassembly failed. Free up all resources */
7663 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7664 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7665 				IP_REASS_SET_START(t_mp, 0);
7666 				IP_REASS_SET_END(t_mp, 0);
7667 			}
7668 			freemsg(mp);
7669 			goto reass_done;
7670 		}
7671 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7672 	}
7673 	/*
7674 	 * We have completed reassembly.  Unhook the frag header from
7675 	 * the reassembly list.
7676 	 *
7677 	 * Before we free the frag header, record the ECN info
7678 	 * to report back to the transport.
7679 	 */
7680 	ecn_info = ipf->ipf_ecn;
7681 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7682 	ipfp = ipf->ipf_ptphn;
7683 
7684 	/* We need to supply these to caller */
7685 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7686 		sum_val = ipf->ipf_checksum;
7687 	else
7688 		sum_val = 0;
7689 
7690 	mp1 = ipf->ipf_mp;
7691 	count = ipf->ipf_count;
7692 	ipf = ipf->ipf_hash_next;
7693 	if (ipf != NULL)
7694 		ipf->ipf_ptphn = ipfp;
7695 	ipfp[0] = ipf;
7696 	atomic_add_32(&ill->ill_frag_count, -count);
7697 	ASSERT(ipfb->ipfb_count >= count);
7698 	ipfb->ipfb_count -= count;
7699 	ipfb->ipfb_frag_pkts--;
7700 	mutex_exit(&ipfb->ipfb_lock);
7701 	/* Ditch the frag header. */
7702 	mp = mp1->b_cont;
7703 
7704 	freeb(mp1);
7705 
7706 	/* Restore original IP length in header. */
7707 	packet_size = (uint32_t)msgdsize(mp);
7708 	if (packet_size > IP_MAXPACKET) {
7709 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7710 		ip_drop_input("Reassembled packet too large", mp, ill);
7711 		freemsg(mp);
7712 		return (NULL);
7713 	}
7714 
7715 	if (DB_REF(mp) > 1) {
7716 		mblk_t *mp2 = copymsg(mp);
7717 
7718 		if (mp2 == NULL) {
7719 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7720 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7721 			freemsg(mp);
7722 			return (NULL);
7723 		}
7724 		freemsg(mp);
7725 		mp = mp2;
7726 	}
7727 	ipha = (ipha_t *)mp->b_rptr;
7728 
7729 	ipha->ipha_length = htons((uint16_t)packet_size);
7730 	/* We're now complete, zip the frag state */
7731 	ipha->ipha_fragment_offset_and_flags = 0;
7732 	/* Record the ECN info. */
7733 	ipha->ipha_type_of_service &= 0xFC;
7734 	ipha->ipha_type_of_service |= ecn_info;
7735 
7736 	/* Update the receive attributes */
7737 	ira->ira_pktlen = packet_size;
7738 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7739 
7740 	/* Reassembly is successful; set checksum information in packet */
7741 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7742 	DB_CKSUMFLAGS(mp) = sum_flags;
7743 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7744 
7745 	return (mp);
7746 }
7747 
7748 /*
7749  * Pullup function that should be used for IP input in order to
7750  * ensure we do not loose the L2 source address; we need the l2 source
7751  * address for IP_RECVSLLA and for ndp_input.
7752  *
7753  * We return either NULL or b_rptr.
7754  */
7755 void *
7756 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7757 {
7758 	ill_t		*ill = ira->ira_ill;
7759 
7760 	if (ip_rput_pullups++ == 0) {
7761 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7762 		    "ip_pullup: %s forced us to "
7763 		    " pullup pkt, hdr len %ld, hdr addr %p",
7764 		    ill->ill_name, len, (void *)mp->b_rptr);
7765 	}
7766 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7767 		ip_setl2src(mp, ira, ira->ira_rill);
7768 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7769 	if (!pullupmsg(mp, len))
7770 		return (NULL);
7771 	else
7772 		return (mp->b_rptr);
7773 }
7774 
7775 /*
7776  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7777  * When called from the ULP ira_rill will be NULL hence the caller has to
7778  * pass in the ill.
7779  */
7780 /* ARGSUSED */
7781 void
7782 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7783 {
7784 	const uchar_t *addr;
7785 	int alen;
7786 
7787 	if (ira->ira_flags & IRAF_L2SRC_SET)
7788 		return;
7789 
7790 	ASSERT(ill != NULL);
7791 	alen = ill->ill_phys_addr_length;
7792 	ASSERT(alen <= sizeof (ira->ira_l2src));
7793 	if (ira->ira_mhip != NULL &&
7794 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7795 		bcopy(addr, ira->ira_l2src, alen);
7796 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7797 	    (addr = ill->ill_phys_addr) != NULL) {
7798 		bcopy(addr, ira->ira_l2src, alen);
7799 	} else {
7800 		bzero(ira->ira_l2src, alen);
7801 	}
7802 	ira->ira_flags |= IRAF_L2SRC_SET;
7803 }
7804 
7805 /*
7806  * check ip header length and align it.
7807  */
7808 mblk_t *
7809 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7810 {
7811 	ill_t	*ill = ira->ira_ill;
7812 	ssize_t len;
7813 
7814 	len = MBLKL(mp);
7815 
7816 	if (!OK_32PTR(mp->b_rptr))
7817 		IP_STAT(ill->ill_ipst, ip_notaligned);
7818 	else
7819 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7820 
7821 	/* Guard against bogus device drivers */
7822 	if (len < 0) {
7823 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7824 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7825 		freemsg(mp);
7826 		return (NULL);
7827 	}
7828 
7829 	if (len == 0) {
7830 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7831 		mblk_t *mp1 = mp->b_cont;
7832 
7833 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7834 			ip_setl2src(mp, ira, ira->ira_rill);
7835 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7836 
7837 		freeb(mp);
7838 		mp = mp1;
7839 		if (mp == NULL)
7840 			return (NULL);
7841 
7842 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7843 			return (mp);
7844 	}
7845 	if (ip_pullup(mp, min_size, ira) == NULL) {
7846 		if (msgdsize(mp) < min_size) {
7847 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7848 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7849 		} else {
7850 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7851 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7852 		}
7853 		freemsg(mp);
7854 		return (NULL);
7855 	}
7856 	return (mp);
7857 }
7858 
7859 /*
7860  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7861  */
7862 mblk_t *
7863 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7864     uint_t min_size, ip_recv_attr_t *ira)
7865 {
7866 	ill_t	*ill = ira->ira_ill;
7867 
7868 	/*
7869 	 * Make sure we have data length consistent
7870 	 * with the IP header.
7871 	 */
7872 	if (mp->b_cont == NULL) {
7873 		/* pkt_len is based on ipha_len, not the mblk length */
7874 		if (pkt_len < min_size) {
7875 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7876 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7877 			freemsg(mp);
7878 			return (NULL);
7879 		}
7880 		if (len < 0) {
7881 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7882 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7883 			freemsg(mp);
7884 			return (NULL);
7885 		}
7886 		/* Drop any pad */
7887 		mp->b_wptr = rptr + pkt_len;
7888 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7889 		ASSERT(pkt_len >= min_size);
7890 		if (pkt_len < min_size) {
7891 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7892 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7893 			freemsg(mp);
7894 			return (NULL);
7895 		}
7896 		if (len < 0) {
7897 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7898 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7899 			freemsg(mp);
7900 			return (NULL);
7901 		}
7902 		/* Drop any pad */
7903 		(void) adjmsg(mp, -len);
7904 		/*
7905 		 * adjmsg may have freed an mblk from the chain, hence
7906 		 * invalidate any hw checksum here. This will force IP to
7907 		 * calculate the checksum in sw, but only for this packet.
7908 		 */
7909 		DB_CKSUMFLAGS(mp) = 0;
7910 		IP_STAT(ill->ill_ipst, ip_multimblk);
7911 	}
7912 	return (mp);
7913 }
7914 
7915 /*
7916  * Check that the IPv4 opt_len is consistent with the packet and pullup
7917  * the options.
7918  */
7919 mblk_t *
7920 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7921     ip_recv_attr_t *ira)
7922 {
7923 	ill_t	*ill = ira->ira_ill;
7924 	ssize_t len;
7925 
7926 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7927 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7928 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7929 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7930 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7931 		freemsg(mp);
7932 		return (NULL);
7933 	}
7934 
7935 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7936 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7937 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7938 		freemsg(mp);
7939 		return (NULL);
7940 	}
7941 	/*
7942 	 * Recompute complete header length and make sure we
7943 	 * have access to all of it.
7944 	 */
7945 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7946 	if (len > (mp->b_wptr - mp->b_rptr)) {
7947 		if (len > pkt_len) {
7948 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7949 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7950 			freemsg(mp);
7951 			return (NULL);
7952 		}
7953 		if (ip_pullup(mp, len, ira) == NULL) {
7954 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7955 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7956 			freemsg(mp);
7957 			return (NULL);
7958 		}
7959 	}
7960 	return (mp);
7961 }
7962 
7963 /*
7964  * Returns a new ire, or the same ire, or NULL.
7965  * If a different IRE is returned, then it is held; the caller
7966  * needs to release it.
7967  * In no case is there any hold/release on the ire argument.
7968  */
7969 ire_t *
7970 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7971 {
7972 	ire_t		*new_ire;
7973 	ill_t		*ire_ill;
7974 	uint_t		ifindex;
7975 	ip_stack_t	*ipst = ill->ill_ipst;
7976 	boolean_t	strict_check = B_FALSE;
7977 
7978 	/*
7979 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7980 	 * issue (e.g. packet received on an underlying interface matched an
7981 	 * IRE_LOCAL on its associated group interface).
7982 	 */
7983 	ASSERT(ire->ire_ill != NULL);
7984 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7985 		return (ire);
7986 
7987 	/*
7988 	 * Do another ire lookup here, using the ingress ill, to see if the
7989 	 * interface is in a usesrc group.
7990 	 * As long as the ills belong to the same group, we don't consider
7991 	 * them to be arriving on the wrong interface. Thus, if the switch
7992 	 * is doing inbound load spreading, we won't drop packets when the
7993 	 * ip*_strict_dst_multihoming switch is on.
7994 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7995 	 * where the local address may not be unique. In this case we were
7996 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7997 	 * actually returned. The new lookup, which is more specific, should
7998 	 * only find the IRE_LOCAL associated with the ingress ill if one
7999 	 * exists.
8000 	 */
8001 	if (ire->ire_ipversion == IPV4_VERSION) {
8002 		if (ipst->ips_ip_strict_dst_multihoming)
8003 			strict_check = B_TRUE;
8004 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
8005 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
8006 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
8007 	} else {
8008 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
8009 		if (ipst->ips_ipv6_strict_dst_multihoming)
8010 			strict_check = B_TRUE;
8011 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
8012 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
8013 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
8014 	}
8015 	/*
8016 	 * If the same ire that was returned in ip_input() is found then this
8017 	 * is an indication that usesrc groups are in use. The packet
8018 	 * arrived on a different ill in the group than the one associated with
8019 	 * the destination address.  If a different ire was found then the same
8020 	 * IP address must be hosted on multiple ills. This is possible with
8021 	 * unnumbered point2point interfaces. We switch to use this new ire in
8022 	 * order to have accurate interface statistics.
8023 	 */
8024 	if (new_ire != NULL) {
8025 		/* Note: held in one case but not the other? Caller handles */
8026 		if (new_ire != ire)
8027 			return (new_ire);
8028 		/* Unchanged */
8029 		ire_refrele(new_ire);
8030 		return (ire);
8031 	}
8032 
8033 	/*
8034 	 * Chase pointers once and store locally.
8035 	 */
8036 	ASSERT(ire->ire_ill != NULL);
8037 	ire_ill = ire->ire_ill;
8038 	ifindex = ill->ill_usesrc_ifindex;
8039 
8040 	/*
8041 	 * Check if it's a legal address on the 'usesrc' interface.
8042 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
8043 	 * can just check phyint_ifindex.
8044 	 */
8045 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
8046 		return (ire);
8047 	}
8048 
8049 	/*
8050 	 * If the ip*_strict_dst_multihoming switch is on then we can
8051 	 * only accept this packet if the interface is marked as routing.
8052 	 */
8053 	if (!(strict_check))
8054 		return (ire);
8055 
8056 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
8057 		return (ire);
8058 	}
8059 	return (NULL);
8060 }
8061 
8062 /*
8063  * This function is used to construct a mac_header_info_s from a
8064  * DL_UNITDATA_IND message.
8065  * The address fields in the mhi structure points into the message,
8066  * thus the caller can't use those fields after freeing the message.
8067  *
8068  * We determine whether the packet received is a non-unicast packet
8069  * and in doing so, determine whether or not it is broadcast vs multicast.
8070  * For it to be a broadcast packet, we must have the appropriate mblk_t
8071  * hanging off the ill_t.  If this is either not present or doesn't match
8072  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
8073  * to be multicast.  Thus NICs that have no broadcast address (or no
8074  * capability for one, such as point to point links) cannot return as
8075  * the packet being broadcast.
8076  */
8077 void
8078 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
8079 {
8080 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
8081 	mblk_t *bmp;
8082 	uint_t extra_offset;
8083 
8084 	bzero(mhip, sizeof (struct mac_header_info_s));
8085 
8086 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
8087 
8088 	if (ill->ill_sap_length < 0)
8089 		extra_offset = 0;
8090 	else
8091 		extra_offset = ill->ill_sap_length;
8092 
8093 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
8094 	    extra_offset;
8095 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
8096 	    extra_offset;
8097 
8098 	if (!ind->dl_group_address)
8099 		return;
8100 
8101 	/* Multicast or broadcast */
8102 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
8103 
8104 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
8105 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
8106 	    (bmp = ill->ill_bcast_mp) != NULL) {
8107 		dl_unitdata_req_t *dlur;
8108 		uint8_t *bphys_addr;
8109 
8110 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
8111 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
8112 		    extra_offset;
8113 
8114 		if (bcmp(mhip->mhi_daddr, bphys_addr,
8115 		    ind->dl_dest_addr_length) == 0)
8116 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
8117 	}
8118 }
8119 
8120 /*
8121  * This function is used to construct a mac_header_info_s from a
8122  * M_DATA fastpath message from a DLPI driver.
8123  * The address fields in the mhi structure points into the message,
8124  * thus the caller can't use those fields after freeing the message.
8125  *
8126  * We determine whether the packet received is a non-unicast packet
8127  * and in doing so, determine whether or not it is broadcast vs multicast.
8128  * For it to be a broadcast packet, we must have the appropriate mblk_t
8129  * hanging off the ill_t.  If this is either not present or doesn't match
8130  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
8131  * to be multicast.  Thus NICs that have no broadcast address (or no
8132  * capability for one, such as point to point links) cannot return as
8133  * the packet being broadcast.
8134  */
8135 void
8136 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
8137 {
8138 	mblk_t *bmp;
8139 	struct ether_header *pether;
8140 
8141 	bzero(mhip, sizeof (struct mac_header_info_s));
8142 
8143 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
8144 
8145 	pether = (struct ether_header *)((char *)mp->b_rptr
8146 	    - sizeof (struct ether_header));
8147 
8148 	/*
8149 	 * Make sure the interface is an ethernet type, since we don't
8150 	 * know the header format for anything but Ethernet. Also make
8151 	 * sure we are pointing correctly above db_base.
8152 	 */
8153 	if (ill->ill_type != IFT_ETHER)
8154 		return;
8155 
8156 retry:
8157 	if ((uchar_t *)pether < mp->b_datap->db_base)
8158 		return;
8159 
8160 	/* Is there a VLAN tag? */
8161 	if (ill->ill_isv6) {
8162 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
8163 			pether = (struct ether_header *)((char *)pether - 4);
8164 			goto retry;
8165 		}
8166 	} else {
8167 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
8168 			pether = (struct ether_header *)((char *)pether - 4);
8169 			goto retry;
8170 		}
8171 	}
8172 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
8173 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
8174 
8175 	if (!(mhip->mhi_daddr[0] & 0x01))
8176 		return;
8177 
8178 	/* Multicast or broadcast */
8179 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
8180 
8181 	if ((bmp = ill->ill_bcast_mp) != NULL) {
8182 		dl_unitdata_req_t *dlur;
8183 		uint8_t *bphys_addr;
8184 		uint_t	addrlen;
8185 
8186 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
8187 		addrlen = dlur->dl_dest_addr_length;
8188 		if (ill->ill_sap_length < 0) {
8189 			bphys_addr = (uchar_t *)dlur +
8190 			    dlur->dl_dest_addr_offset;
8191 			addrlen += ill->ill_sap_length;
8192 		} else {
8193 			bphys_addr = (uchar_t *)dlur +
8194 			    dlur->dl_dest_addr_offset +
8195 			    ill->ill_sap_length;
8196 			addrlen -= ill->ill_sap_length;
8197 		}
8198 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
8199 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
8200 	}
8201 }
8202 
8203 /*
8204  * Handle anything but M_DATA messages
8205  * We see the DL_UNITDATA_IND which are part
8206  * of the data path, and also the other messages from the driver.
8207  */
8208 void
8209 ip_rput_notdata(ill_t *ill, mblk_t *mp)
8210 {
8211 	mblk_t		*first_mp;
8212 	struct iocblk   *iocp;
8213 	struct mac_header_info_s mhi;
8214 
8215 	switch (DB_TYPE(mp)) {
8216 	case M_PROTO:
8217 	case M_PCPROTO: {
8218 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
8219 		    DL_UNITDATA_IND) {
8220 			/* Go handle anything other than data elsewhere. */
8221 			ip_rput_dlpi(ill, mp);
8222 			return;
8223 		}
8224 
8225 		first_mp = mp;
8226 		mp = first_mp->b_cont;
8227 		first_mp->b_cont = NULL;
8228 
8229 		if (mp == NULL) {
8230 			freeb(first_mp);
8231 			return;
8232 		}
8233 		ip_dlur_to_mhi(ill, first_mp, &mhi);
8234 		if (ill->ill_isv6)
8235 			ip_input_v6(ill, NULL, mp, &mhi);
8236 		else
8237 			ip_input(ill, NULL, mp, &mhi);
8238 
8239 		/* Ditch the DLPI header. */
8240 		freeb(first_mp);
8241 		return;
8242 	}
8243 	case M_IOCACK:
8244 		iocp = (struct iocblk *)mp->b_rptr;
8245 		switch (iocp->ioc_cmd) {
8246 		case DL_IOC_HDR_INFO:
8247 			ill_fastpath_ack(ill, mp);
8248 			return;
8249 		default:
8250 			putnext(ill->ill_rq, mp);
8251 			return;
8252 		}
8253 		/* FALLTHRU */
8254 	case M_ERROR:
8255 	case M_HANGUP:
8256 		mutex_enter(&ill->ill_lock);
8257 		if (ill->ill_state_flags & ILL_CONDEMNED) {
8258 			mutex_exit(&ill->ill_lock);
8259 			freemsg(mp);
8260 			return;
8261 		}
8262 		ill_refhold_locked(ill);
8263 		mutex_exit(&ill->ill_lock);
8264 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
8265 		    B_FALSE);
8266 		return;
8267 	case M_CTL:
8268 		putnext(ill->ill_rq, mp);
8269 		return;
8270 	case M_IOCNAK:
8271 		ip1dbg(("got iocnak "));
8272 		iocp = (struct iocblk *)mp->b_rptr;
8273 		switch (iocp->ioc_cmd) {
8274 		case DL_IOC_HDR_INFO:
8275 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
8276 			return;
8277 		default:
8278 			break;
8279 		}
8280 		/* FALLTHRU */
8281 	default:
8282 		putnext(ill->ill_rq, mp);
8283 		return;
8284 	}
8285 }
8286 
8287 /* Read side put procedure.  Packets coming from the wire arrive here. */
8288 void
8289 ip_rput(queue_t *q, mblk_t *mp)
8290 {
8291 	ill_t	*ill;
8292 	union DL_primitives *dl;
8293 
8294 	ill = (ill_t *)q->q_ptr;
8295 
8296 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
8297 		/*
8298 		 * If things are opening or closing, only accept high-priority
8299 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
8300 		 * created; on close, things hanging off the ill may have been
8301 		 * freed already.)
8302 		 */
8303 		dl = (union DL_primitives *)mp->b_rptr;
8304 		if (DB_TYPE(mp) != M_PCPROTO ||
8305 		    dl->dl_primitive == DL_UNITDATA_IND) {
8306 			inet_freemsg(mp);
8307 			return;
8308 		}
8309 	}
8310 	if (DB_TYPE(mp) == M_DATA) {
8311 		struct mac_header_info_s mhi;
8312 
8313 		ip_mdata_to_mhi(ill, mp, &mhi);
8314 		ip_input(ill, NULL, mp, &mhi);
8315 	} else {
8316 		ip_rput_notdata(ill, mp);
8317 	}
8318 }
8319 
8320 /*
8321  * Move the information to a copy.
8322  */
8323 mblk_t *
8324 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8325 {
8326 	mblk_t		*mp1;
8327 	ill_t		*ill = ira->ira_ill;
8328 	ip_stack_t	*ipst = ill->ill_ipst;
8329 
8330 	IP_STAT(ipst, ip_db_ref);
8331 
8332 	/* Make sure we have ira_l2src before we loose the original mblk */
8333 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
8334 		ip_setl2src(mp, ira, ira->ira_rill);
8335 
8336 	mp1 = copymsg(mp);
8337 	if (mp1 == NULL) {
8338 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8339 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
8340 		freemsg(mp);
8341 		return (NULL);
8342 	}
8343 	/* preserve the hardware checksum flags and data, if present */
8344 	if (DB_CKSUMFLAGS(mp) != 0) {
8345 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8346 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8347 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8348 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8349 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8350 	}
8351 	freemsg(mp);
8352 	return (mp1);
8353 }
8354 
8355 static void
8356 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8357     t_uscalar_t err)
8358 {
8359 	if (dl_err == DL_SYSERR) {
8360 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8361 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8362 		    ill->ill_name, dl_primstr(prim), err);
8363 		return;
8364 	}
8365 
8366 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8367 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8368 	    dl_errstr(dl_err));
8369 }
8370 
8371 /*
8372  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8373  * than DL_UNITDATA_IND messages. If we need to process this message
8374  * exclusively, we call qwriter_ip, in which case we also need to call
8375  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8376  */
8377 void
8378 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8379 {
8380 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8381 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8382 	queue_t		*q = ill->ill_rq;
8383 	t_uscalar_t	prim = dloa->dl_primitive;
8384 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8385 
8386 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8387 	    char *, dl_primstr(prim), ill_t *, ill);
8388 	ip1dbg(("ip_rput_dlpi"));
8389 
8390 	/*
8391 	 * If we received an ACK but didn't send a request for it, then it
8392 	 * can't be part of any pending operation; discard up-front.
8393 	 */
8394 	switch (prim) {
8395 	case DL_ERROR_ACK:
8396 		reqprim = dlea->dl_error_primitive;
8397 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8398 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8399 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8400 		    dlea->dl_unix_errno));
8401 		break;
8402 	case DL_OK_ACK:
8403 		reqprim = dloa->dl_correct_primitive;
8404 		break;
8405 	case DL_INFO_ACK:
8406 		reqprim = DL_INFO_REQ;
8407 		break;
8408 	case DL_BIND_ACK:
8409 		reqprim = DL_BIND_REQ;
8410 		break;
8411 	case DL_PHYS_ADDR_ACK:
8412 		reqprim = DL_PHYS_ADDR_REQ;
8413 		break;
8414 	case DL_NOTIFY_ACK:
8415 		reqprim = DL_NOTIFY_REQ;
8416 		break;
8417 	case DL_CAPABILITY_ACK:
8418 		reqprim = DL_CAPABILITY_REQ;
8419 		break;
8420 	}
8421 
8422 	if (prim != DL_NOTIFY_IND) {
8423 		if (reqprim == DL_PRIM_INVAL ||
8424 		    !ill_dlpi_pending(ill, reqprim)) {
8425 			/* Not a DLPI message we support or expected */
8426 			freemsg(mp);
8427 			return;
8428 		}
8429 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8430 		    dl_primstr(reqprim)));
8431 	}
8432 
8433 	switch (reqprim) {
8434 	case DL_UNBIND_REQ:
8435 		/*
8436 		 * NOTE: we mark the unbind as complete even if we got a
8437 		 * DL_ERROR_ACK, since there's not much else we can do.
8438 		 */
8439 		mutex_enter(&ill->ill_lock);
8440 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8441 		cv_signal(&ill->ill_cv);
8442 		mutex_exit(&ill->ill_lock);
8443 		break;
8444 
8445 	case DL_ENABMULTI_REQ:
8446 		if (prim == DL_OK_ACK) {
8447 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8448 				ill->ill_dlpi_multicast_state = IDS_OK;
8449 		}
8450 		break;
8451 	}
8452 
8453 	/*
8454 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8455 	 * need to become writer to continue to process it.  Because an
8456 	 * exclusive operation doesn't complete until replies to all queued
8457 	 * DLPI messages have been received, we know we're in the middle of an
8458 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8459 	 *
8460 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8461 	 * Since this is on the ill stream we unconditionally bump up the
8462 	 * refcount without doing ILL_CAN_LOOKUP().
8463 	 */
8464 	ill_refhold(ill);
8465 	if (prim == DL_NOTIFY_IND)
8466 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8467 	else
8468 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8469 }
8470 
8471 /*
8472  * Handling of DLPI messages that require exclusive access to the ipsq.
8473  *
8474  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8475  * happen here. (along with mi_copy_done)
8476  */
8477 /* ARGSUSED */
8478 static void
8479 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8480 {
8481 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8482 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8483 	int		err = 0;
8484 	ill_t		*ill = (ill_t *)q->q_ptr;
8485 	ipif_t		*ipif = NULL;
8486 	mblk_t		*mp1 = NULL;
8487 	conn_t		*connp = NULL;
8488 	t_uscalar_t	paddrreq;
8489 	mblk_t		*mp_hw;
8490 	boolean_t	success;
8491 	boolean_t	ioctl_aborted = B_FALSE;
8492 	boolean_t	log = B_TRUE;
8493 
8494 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8495 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8496 
8497 	ip1dbg(("ip_rput_dlpi_writer .."));
8498 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8499 	ASSERT(IAM_WRITER_ILL(ill));
8500 
8501 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8502 	/*
8503 	 * The current ioctl could have been aborted by the user and a new
8504 	 * ioctl to bring up another ill could have started. We could still
8505 	 * get a response from the driver later.
8506 	 */
8507 	if (ipif != NULL && ipif->ipif_ill != ill)
8508 		ioctl_aborted = B_TRUE;
8509 
8510 	switch (dloa->dl_primitive) {
8511 	case DL_ERROR_ACK:
8512 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8513 		    dl_primstr(dlea->dl_error_primitive)));
8514 
8515 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8516 		    char *, dl_primstr(dlea->dl_error_primitive),
8517 		    ill_t *, ill);
8518 
8519 		switch (dlea->dl_error_primitive) {
8520 		case DL_DISABMULTI_REQ:
8521 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8522 			break;
8523 		case DL_PROMISCON_REQ:
8524 		case DL_PROMISCOFF_REQ:
8525 		case DL_UNBIND_REQ:
8526 		case DL_ATTACH_REQ:
8527 		case DL_INFO_REQ:
8528 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8529 			break;
8530 		case DL_NOTIFY_REQ:
8531 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8532 			log = B_FALSE;
8533 			break;
8534 		case DL_PHYS_ADDR_REQ:
8535 			/*
8536 			 * For IPv6 only, there are two additional
8537 			 * phys_addr_req's sent to the driver to get the
8538 			 * IPv6 token and lla. This allows IP to acquire
8539 			 * the hardware address format for a given interface
8540 			 * without having built in knowledge of the hardware
8541 			 * address. ill_phys_addr_pend keeps track of the last
8542 			 * DL_PAR sent so we know which response we are
8543 			 * dealing with. ill_dlpi_done will update
8544 			 * ill_phys_addr_pend when it sends the next req.
8545 			 * We don't complete the IOCTL until all three DL_PARs
8546 			 * have been attempted, so set *_len to 0 and break.
8547 			 */
8548 			paddrreq = ill->ill_phys_addr_pend;
8549 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8550 			if (paddrreq == DL_IPV6_TOKEN) {
8551 				ill->ill_token_length = 0;
8552 				log = B_FALSE;
8553 				break;
8554 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8555 				ill->ill_nd_lla_len = 0;
8556 				log = B_FALSE;
8557 				break;
8558 			}
8559 			/*
8560 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8561 			 * We presumably have an IOCTL hanging out waiting
8562 			 * for completion. Find it and complete the IOCTL
8563 			 * with the error noted.
8564 			 * However, ill_dl_phys was called on an ill queue
8565 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8566 			 * set. But the ioctl is known to be pending on ill_wq.
8567 			 */
8568 			if (!ill->ill_ifname_pending)
8569 				break;
8570 			ill->ill_ifname_pending = 0;
8571 			if (!ioctl_aborted)
8572 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8573 			if (mp1 != NULL) {
8574 				/*
8575 				 * This operation (SIOCSLIFNAME) must have
8576 				 * happened on the ill. Assert there is no conn
8577 				 */
8578 				ASSERT(connp == NULL);
8579 				q = ill->ill_wq;
8580 			}
8581 			break;
8582 		case DL_BIND_REQ:
8583 			ill_dlpi_done(ill, DL_BIND_REQ);
8584 			if (ill->ill_ifname_pending)
8585 				break;
8586 			/*
8587 			 * Something went wrong with the bind.  We presumably
8588 			 * have an IOCTL hanging out waiting for completion.
8589 			 * Find it, take down the interface that was coming
8590 			 * up, and complete the IOCTL with the error noted.
8591 			 */
8592 			if (!ioctl_aborted)
8593 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8594 			if (mp1 != NULL) {
8595 				/*
8596 				 * This might be a result of a DL_NOTE_REPLUMB
8597 				 * notification. In that case, connp is NULL.
8598 				 */
8599 				if (connp != NULL)
8600 					q = CONNP_TO_WQ(connp);
8601 
8602 				(void) ipif_down(ipif, NULL, NULL);
8603 				/* error is set below the switch */
8604 			}
8605 			break;
8606 		case DL_ENABMULTI_REQ:
8607 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8608 
8609 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8610 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8611 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8612 
8613 				printf("ip: joining multicasts failed (%d)"
8614 				    " on %s - will use link layer "
8615 				    "broadcasts for multicast\n",
8616 				    dlea->dl_errno, ill->ill_name);
8617 
8618 				/*
8619 				 * Set up for multi_bcast; We are the
8620 				 * writer, so ok to access ill->ill_ipif
8621 				 * without any lock.
8622 				 */
8623 				mutex_enter(&ill->ill_phyint->phyint_lock);
8624 				ill->ill_phyint->phyint_flags |=
8625 				    PHYI_MULTI_BCAST;
8626 				mutex_exit(&ill->ill_phyint->phyint_lock);
8627 
8628 			}
8629 			freemsg(mp);	/* Don't want to pass this up */
8630 			return;
8631 		case DL_CAPABILITY_REQ:
8632 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8633 			    "DL_CAPABILITY REQ\n"));
8634 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8635 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8636 			ill_capability_done(ill);
8637 			freemsg(mp);
8638 			return;
8639 		}
8640 		/*
8641 		 * Note the error for IOCTL completion (mp1 is set when
8642 		 * ready to complete ioctl). If ill_ifname_pending_err is
8643 		 * set, an error occured during plumbing (ill_ifname_pending),
8644 		 * so we want to report that error.
8645 		 *
8646 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8647 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8648 		 * expected to get errack'd if the driver doesn't support
8649 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8650 		 * if these error conditions are encountered.
8651 		 */
8652 		if (mp1 != NULL) {
8653 			if (ill->ill_ifname_pending_err != 0)  {
8654 				err = ill->ill_ifname_pending_err;
8655 				ill->ill_ifname_pending_err = 0;
8656 			} else {
8657 				err = dlea->dl_unix_errno ?
8658 				    dlea->dl_unix_errno : ENXIO;
8659 			}
8660 		/*
8661 		 * If we're plumbing an interface and an error hasn't already
8662 		 * been saved, set ill_ifname_pending_err to the error passed
8663 		 * up. Ignore the error if log is B_FALSE (see comment above).
8664 		 */
8665 		} else if (log && ill->ill_ifname_pending &&
8666 		    ill->ill_ifname_pending_err == 0) {
8667 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8668 			    dlea->dl_unix_errno : ENXIO;
8669 		}
8670 
8671 		if (log)
8672 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8673 			    dlea->dl_errno, dlea->dl_unix_errno);
8674 		break;
8675 	case DL_CAPABILITY_ACK:
8676 		ill_capability_ack(ill, mp);
8677 		/*
8678 		 * The message has been handed off to ill_capability_ack
8679 		 * and must not be freed below
8680 		 */
8681 		mp = NULL;
8682 		break;
8683 
8684 	case DL_INFO_ACK:
8685 		/* Call a routine to handle this one. */
8686 		ill_dlpi_done(ill, DL_INFO_REQ);
8687 		ip_ll_subnet_defaults(ill, mp);
8688 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8689 		return;
8690 	case DL_BIND_ACK:
8691 		/*
8692 		 * We should have an IOCTL waiting on this unless
8693 		 * sent by ill_dl_phys, in which case just return
8694 		 */
8695 		ill_dlpi_done(ill, DL_BIND_REQ);
8696 		if (ill->ill_ifname_pending) {
8697 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8698 			    ill_t *, ill, mblk_t *, mp);
8699 			break;
8700 		}
8701 		if (!ioctl_aborted)
8702 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8703 		if (mp1 == NULL) {
8704 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8705 			break;
8706 		}
8707 		/*
8708 		 * mp1 was added by ill_dl_up(). if that is a result of
8709 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8710 		 */
8711 		if (connp != NULL)
8712 			q = CONNP_TO_WQ(connp);
8713 		/*
8714 		 * We are exclusive. So nothing can change even after
8715 		 * we get the pending mp.
8716 		 */
8717 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8718 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8719 
8720 		mutex_enter(&ill->ill_lock);
8721 		ill->ill_dl_up = 1;
8722 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8723 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8724 		mutex_exit(&ill->ill_lock);
8725 
8726 		/*
8727 		 * Now bring up the resolver; when that is complete, we'll
8728 		 * create IREs.  Note that we intentionally mirror what
8729 		 * ipif_up() would have done, because we got here by way of
8730 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8731 		 */
8732 		if (ill->ill_isv6) {
8733 			/*
8734 			 * v6 interfaces.
8735 			 * Unlike ARP which has to do another bind
8736 			 * and attach, once we get here we are
8737 			 * done with NDP
8738 			 */
8739 			(void) ipif_resolver_up(ipif, Res_act_initial);
8740 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8741 				err = ipif_up_done_v6(ipif);
8742 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8743 			/*
8744 			 * ARP and other v4 external resolvers.
8745 			 * Leave the pending mblk intact so that
8746 			 * the ioctl completes in ip_rput().
8747 			 */
8748 			if (connp != NULL)
8749 				mutex_enter(&connp->conn_lock);
8750 			mutex_enter(&ill->ill_lock);
8751 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8752 			mutex_exit(&ill->ill_lock);
8753 			if (connp != NULL)
8754 				mutex_exit(&connp->conn_lock);
8755 			if (success) {
8756 				err = ipif_resolver_up(ipif, Res_act_initial);
8757 				if (err == EINPROGRESS) {
8758 					freemsg(mp);
8759 					return;
8760 				}
8761 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8762 			} else {
8763 				/* The conn has started closing */
8764 				err = EINTR;
8765 			}
8766 		} else {
8767 			/*
8768 			 * This one is complete. Reply to pending ioctl.
8769 			 */
8770 			(void) ipif_resolver_up(ipif, Res_act_initial);
8771 			err = ipif_up_done(ipif);
8772 		}
8773 
8774 		if ((err == 0) && (ill->ill_up_ipifs)) {
8775 			err = ill_up_ipifs(ill, q, mp1);
8776 			if (err == EINPROGRESS) {
8777 				freemsg(mp);
8778 				return;
8779 			}
8780 		}
8781 
8782 		/*
8783 		 * If we have a moved ipif to bring up, and everything has
8784 		 * succeeded to this point, bring it up on the IPMP ill.
8785 		 * Otherwise, leave it down -- the admin can try to bring it
8786 		 * up by hand if need be.
8787 		 */
8788 		if (ill->ill_move_ipif != NULL) {
8789 			if (err != 0) {
8790 				ill->ill_move_ipif = NULL;
8791 			} else {
8792 				ipif = ill->ill_move_ipif;
8793 				ill->ill_move_ipif = NULL;
8794 				err = ipif_up(ipif, q, mp1);
8795 				if (err == EINPROGRESS) {
8796 					freemsg(mp);
8797 					return;
8798 				}
8799 			}
8800 		}
8801 		break;
8802 
8803 	case DL_NOTIFY_IND: {
8804 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8805 		uint_t orig_mtu;
8806 
8807 		switch (notify->dl_notification) {
8808 		case DL_NOTE_PHYS_ADDR:
8809 			err = ill_set_phys_addr(ill, mp);
8810 			break;
8811 
8812 		case DL_NOTE_REPLUMB:
8813 			/*
8814 			 * Directly return after calling ill_replumb().
8815 			 * Note that we should not free mp as it is reused
8816 			 * in the ill_replumb() function.
8817 			 */
8818 			err = ill_replumb(ill, mp);
8819 			return;
8820 
8821 		case DL_NOTE_FASTPATH_FLUSH:
8822 			nce_flush(ill, B_FALSE);
8823 			break;
8824 
8825 		case DL_NOTE_SDU_SIZE:
8826 			/*
8827 			 * The dce and fragmentation code can cope with
8828 			 * this changing while packets are being sent.
8829 			 * When packets are sent ip_output will discover
8830 			 * a change.
8831 			 *
8832 			 * Change the MTU size of the interface.
8833 			 */
8834 			mutex_enter(&ill->ill_lock);
8835 			ill->ill_current_frag = (uint_t)notify->dl_data;
8836 			if (ill->ill_current_frag > ill->ill_max_frag)
8837 				ill->ill_max_frag = ill->ill_current_frag;
8838 
8839 			orig_mtu = ill->ill_mtu;
8840 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8841 				ill->ill_mtu = ill->ill_current_frag;
8842 
8843 				/*
8844 				 * If ill_user_mtu was set (via
8845 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8846 				 */
8847 				if (ill->ill_user_mtu != 0 &&
8848 				    ill->ill_user_mtu < ill->ill_mtu)
8849 					ill->ill_mtu = ill->ill_user_mtu;
8850 
8851 				if (ill->ill_isv6) {
8852 					if (ill->ill_mtu < IPV6_MIN_MTU)
8853 						ill->ill_mtu = IPV6_MIN_MTU;
8854 				} else {
8855 					if (ill->ill_mtu < IP_MIN_MTU)
8856 						ill->ill_mtu = IP_MIN_MTU;
8857 				}
8858 			}
8859 			mutex_exit(&ill->ill_lock);
8860 			/*
8861 			 * Make sure all dce_generation checks find out
8862 			 * that ill_mtu has changed.
8863 			 */
8864 			if (orig_mtu != ill->ill_mtu) {
8865 				dce_increment_all_generations(ill->ill_isv6,
8866 				    ill->ill_ipst);
8867 			}
8868 
8869 			/*
8870 			 * Refresh IPMP meta-interface MTU if necessary.
8871 			 */
8872 			if (IS_UNDER_IPMP(ill))
8873 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8874 			break;
8875 
8876 		case DL_NOTE_LINK_UP:
8877 		case DL_NOTE_LINK_DOWN: {
8878 			/*
8879 			 * We are writer. ill / phyint / ipsq assocs stable.
8880 			 * The RUNNING flag reflects the state of the link.
8881 			 */
8882 			phyint_t *phyint = ill->ill_phyint;
8883 			uint64_t new_phyint_flags;
8884 			boolean_t changed = B_FALSE;
8885 			boolean_t went_up;
8886 
8887 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8888 			mutex_enter(&phyint->phyint_lock);
8889 
8890 			new_phyint_flags = went_up ?
8891 			    phyint->phyint_flags | PHYI_RUNNING :
8892 			    phyint->phyint_flags & ~PHYI_RUNNING;
8893 
8894 			if (IS_IPMP(ill)) {
8895 				new_phyint_flags = went_up ?
8896 				    new_phyint_flags & ~PHYI_FAILED :
8897 				    new_phyint_flags | PHYI_FAILED;
8898 			}
8899 
8900 			if (new_phyint_flags != phyint->phyint_flags) {
8901 				phyint->phyint_flags = new_phyint_flags;
8902 				changed = B_TRUE;
8903 			}
8904 			mutex_exit(&phyint->phyint_lock);
8905 			/*
8906 			 * ill_restart_dad handles the DAD restart and routing
8907 			 * socket notification logic.
8908 			 */
8909 			if (changed) {
8910 				ill_restart_dad(phyint->phyint_illv4, went_up);
8911 				ill_restart_dad(phyint->phyint_illv6, went_up);
8912 			}
8913 			break;
8914 		}
8915 		case DL_NOTE_PROMISC_ON_PHYS: {
8916 			phyint_t *phyint = ill->ill_phyint;
8917 
8918 			mutex_enter(&phyint->phyint_lock);
8919 			phyint->phyint_flags |= PHYI_PROMISC;
8920 			mutex_exit(&phyint->phyint_lock);
8921 			break;
8922 		}
8923 		case DL_NOTE_PROMISC_OFF_PHYS: {
8924 			phyint_t *phyint = ill->ill_phyint;
8925 
8926 			mutex_enter(&phyint->phyint_lock);
8927 			phyint->phyint_flags &= ~PHYI_PROMISC;
8928 			mutex_exit(&phyint->phyint_lock);
8929 			break;
8930 		}
8931 		case DL_NOTE_CAPAB_RENEG:
8932 			/*
8933 			 * Something changed on the driver side.
8934 			 * It wants us to renegotiate the capabilities
8935 			 * on this ill. One possible cause is the aggregation
8936 			 * interface under us where a port got added or
8937 			 * went away.
8938 			 *
8939 			 * If the capability negotiation is already done
8940 			 * or is in progress, reset the capabilities and
8941 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8942 			 * so that when the ack comes back, we can start
8943 			 * the renegotiation process.
8944 			 *
8945 			 * Note that if ill_capab_reneg is already B_TRUE
8946 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8947 			 * the capability resetting request has been sent
8948 			 * and the renegotiation has not been started yet;
8949 			 * nothing needs to be done in this case.
8950 			 */
8951 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8952 			ill_capability_reset(ill, B_TRUE);
8953 			ipsq_current_finish(ipsq);
8954 			break;
8955 		default:
8956 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8957 			    "type 0x%x for DL_NOTIFY_IND\n",
8958 			    notify->dl_notification));
8959 			break;
8960 		}
8961 
8962 		/*
8963 		 * As this is an asynchronous operation, we
8964 		 * should not call ill_dlpi_done
8965 		 */
8966 		break;
8967 	}
8968 	case DL_NOTIFY_ACK: {
8969 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8970 
8971 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8972 			ill->ill_note_link = 1;
8973 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8974 		break;
8975 	}
8976 	case DL_PHYS_ADDR_ACK: {
8977 		/*
8978 		 * As part of plumbing the interface via SIOCSLIFNAME,
8979 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8980 		 * whose answers we receive here.  As each answer is received,
8981 		 * we call ill_dlpi_done() to dispatch the next request as
8982 		 * we're processing the current one.  Once all answers have
8983 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8984 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8985 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8986 		 * available, but we know the ioctl is pending on ill_wq.)
8987 		 */
8988 		uint_t	paddrlen, paddroff;
8989 		uint8_t	*addr;
8990 
8991 		paddrreq = ill->ill_phys_addr_pend;
8992 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8993 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8994 		addr = mp->b_rptr + paddroff;
8995 
8996 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8997 		if (paddrreq == DL_IPV6_TOKEN) {
8998 			/*
8999 			 * bcopy to low-order bits of ill_token
9000 			 *
9001 			 * XXX Temporary hack - currently, all known tokens
9002 			 * are 64 bits, so I'll cheat for the moment.
9003 			 */
9004 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
9005 			ill->ill_token_length = paddrlen;
9006 			break;
9007 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
9008 			ASSERT(ill->ill_nd_lla_mp == NULL);
9009 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
9010 			mp = NULL;
9011 			break;
9012 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
9013 			ASSERT(ill->ill_dest_addr_mp == NULL);
9014 			ill->ill_dest_addr_mp = mp;
9015 			ill->ill_dest_addr = addr;
9016 			mp = NULL;
9017 			if (ill->ill_isv6) {
9018 				ill_setdesttoken(ill);
9019 				ipif_setdestlinklocal(ill->ill_ipif);
9020 			}
9021 			break;
9022 		}
9023 
9024 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
9025 		ASSERT(ill->ill_phys_addr_mp == NULL);
9026 		if (!ill->ill_ifname_pending)
9027 			break;
9028 		ill->ill_ifname_pending = 0;
9029 		if (!ioctl_aborted)
9030 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
9031 		if (mp1 != NULL) {
9032 			ASSERT(connp == NULL);
9033 			q = ill->ill_wq;
9034 		}
9035 		/*
9036 		 * If any error acks received during the plumbing sequence,
9037 		 * ill_ifname_pending_err will be set. Break out and send up
9038 		 * the error to the pending ioctl.
9039 		 */
9040 		if (ill->ill_ifname_pending_err != 0) {
9041 			err = ill->ill_ifname_pending_err;
9042 			ill->ill_ifname_pending_err = 0;
9043 			break;
9044 		}
9045 
9046 		ill->ill_phys_addr_mp = mp;
9047 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
9048 		mp = NULL;
9049 
9050 		/*
9051 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
9052 		 * provider doesn't support physical addresses.  We check both
9053 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
9054 		 * not have physical addresses, but historically adversises a
9055 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
9056 		 * its DL_PHYS_ADDR_ACK.
9057 		 */
9058 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
9059 			ill->ill_phys_addr = NULL;
9060 		} else if (paddrlen != ill->ill_phys_addr_length) {
9061 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
9062 			    paddrlen, ill->ill_phys_addr_length));
9063 			err = EINVAL;
9064 			break;
9065 		}
9066 
9067 		if (ill->ill_nd_lla_mp == NULL) {
9068 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
9069 				err = ENOMEM;
9070 				break;
9071 			}
9072 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
9073 		}
9074 
9075 		if (ill->ill_isv6) {
9076 			ill_setdefaulttoken(ill);
9077 			ipif_setlinklocal(ill->ill_ipif);
9078 		}
9079 		break;
9080 	}
9081 	case DL_OK_ACK:
9082 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
9083 		    dl_primstr((int)dloa->dl_correct_primitive),
9084 		    dloa->dl_correct_primitive));
9085 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
9086 		    char *, dl_primstr(dloa->dl_correct_primitive),
9087 		    ill_t *, ill);
9088 
9089 		switch (dloa->dl_correct_primitive) {
9090 		case DL_ENABMULTI_REQ:
9091 		case DL_DISABMULTI_REQ:
9092 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
9093 			break;
9094 		case DL_PROMISCON_REQ:
9095 		case DL_PROMISCOFF_REQ:
9096 		case DL_UNBIND_REQ:
9097 		case DL_ATTACH_REQ:
9098 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
9099 			break;
9100 		}
9101 		break;
9102 	default:
9103 		break;
9104 	}
9105 
9106 	freemsg(mp);
9107 	if (mp1 == NULL)
9108 		return;
9109 
9110 	/*
9111 	 * The operation must complete without EINPROGRESS since
9112 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
9113 	 * the operation will be stuck forever inside the IPSQ.
9114 	 */
9115 	ASSERT(err != EINPROGRESS);
9116 
9117 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
9118 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
9119 	    ipif_t *, NULL);
9120 
9121 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
9122 	case 0:
9123 		ipsq_current_finish(ipsq);
9124 		break;
9125 
9126 	case SIOCSLIFNAME:
9127 	case IF_UNITSEL: {
9128 		ill_t *ill_other = ILL_OTHER(ill);
9129 
9130 		/*
9131 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
9132 		 * ill has a peer which is in an IPMP group, then place ill
9133 		 * into the same group.  One catch: although ifconfig plumbs
9134 		 * the appropriate IPMP meta-interface prior to plumbing this
9135 		 * ill, it is possible for multiple ifconfig applications to
9136 		 * race (or for another application to adjust plumbing), in
9137 		 * which case the IPMP meta-interface we need will be missing.
9138 		 * If so, kick the phyint out of the group.
9139 		 */
9140 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
9141 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
9142 			ipmp_illgrp_t	*illg;
9143 
9144 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
9145 			if (illg == NULL)
9146 				ipmp_phyint_leave_grp(ill->ill_phyint);
9147 			else
9148 				ipmp_ill_join_illgrp(ill, illg);
9149 		}
9150 
9151 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
9152 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
9153 		else
9154 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
9155 		break;
9156 	}
9157 	case SIOCLIFADDIF:
9158 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
9159 		break;
9160 
9161 	default:
9162 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
9163 		break;
9164 	}
9165 }
9166 
9167 /*
9168  * ip_rput_other is called by ip_rput to handle messages modifying the global
9169  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
9170  */
9171 /* ARGSUSED */
9172 void
9173 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
9174 {
9175 	ill_t		*ill = q->q_ptr;
9176 	struct iocblk	*iocp;
9177 
9178 	ip1dbg(("ip_rput_other "));
9179 	if (ipsq != NULL) {
9180 		ASSERT(IAM_WRITER_IPSQ(ipsq));
9181 		ASSERT(ipsq->ipsq_xop ==
9182 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
9183 	}
9184 
9185 	switch (mp->b_datap->db_type) {
9186 	case M_ERROR:
9187 	case M_HANGUP:
9188 		/*
9189 		 * The device has a problem.  We force the ILL down.  It can
9190 		 * be brought up again manually using SIOCSIFFLAGS (via
9191 		 * ifconfig or equivalent).
9192 		 */
9193 		ASSERT(ipsq != NULL);
9194 		if (mp->b_rptr < mp->b_wptr)
9195 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
9196 		if (ill->ill_error == 0)
9197 			ill->ill_error = ENXIO;
9198 		if (!ill_down_start(q, mp))
9199 			return;
9200 		ipif_all_down_tail(ipsq, q, mp, NULL);
9201 		break;
9202 	case M_IOCNAK: {
9203 		iocp = (struct iocblk *)mp->b_rptr;
9204 
9205 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
9206 		/*
9207 		 * If this was the first attempt, turn off the fastpath
9208 		 * probing.
9209 		 */
9210 		mutex_enter(&ill->ill_lock);
9211 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
9212 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
9213 			mutex_exit(&ill->ill_lock);
9214 			/*
9215 			 * don't flush the nce_t entries: we use them
9216 			 * as an index to the ncec itself.
9217 			 */
9218 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
9219 			    ill->ill_name));
9220 		} else {
9221 			mutex_exit(&ill->ill_lock);
9222 		}
9223 		freemsg(mp);
9224 		break;
9225 	}
9226 	default:
9227 		ASSERT(0);
9228 		break;
9229 	}
9230 }
9231 
9232 /*
9233  * Update any source route, record route or timestamp options
9234  * When it fails it has consumed the message and BUMPed the MIB.
9235  */
9236 boolean_t
9237 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
9238     ip_recv_attr_t *ira)
9239 {
9240 	ipoptp_t	opts;
9241 	uchar_t		*opt;
9242 	uint8_t		optval;
9243 	uint8_t		optlen;
9244 	ipaddr_t	dst;
9245 	ipaddr_t	ifaddr;
9246 	uint32_t	ts;
9247 	timestruc_t	now;
9248 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9249 
9250 	ip2dbg(("ip_forward_options\n"));
9251 	dst = ipha->ipha_dst;
9252 	for (optval = ipoptp_first(&opts, ipha);
9253 	    optval != IPOPT_EOL;
9254 	    optval = ipoptp_next(&opts)) {
9255 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9256 		opt = opts.ipoptp_cur;
9257 		optlen = opts.ipoptp_len;
9258 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
9259 		    optval, opts.ipoptp_len));
9260 		switch (optval) {
9261 			uint32_t off;
9262 		case IPOPT_SSRR:
9263 		case IPOPT_LSRR:
9264 			/* Check if adminstratively disabled */
9265 			if (!ipst->ips_ip_forward_src_routed) {
9266 				BUMP_MIB(dst_ill->ill_ip_mib,
9267 				    ipIfStatsForwProhibits);
9268 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
9269 				    mp, dst_ill);
9270 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
9271 				    ira);
9272 				return (B_FALSE);
9273 			}
9274 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9275 				/*
9276 				 * Must be partial since ip_input_options
9277 				 * checked for strict.
9278 				 */
9279 				break;
9280 			}
9281 			off = opt[IPOPT_OFFSET];
9282 			off--;
9283 		redo_srr:
9284 			if (optlen < IP_ADDR_LEN ||
9285 			    off > optlen - IP_ADDR_LEN) {
9286 				/* End of source route */
9287 				ip1dbg((
9288 				    "ip_forward_options: end of SR\n"));
9289 				break;
9290 			}
9291 			/* Pick a reasonable address on the outbound if */
9292 			ASSERT(dst_ill != NULL);
9293 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9294 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9295 			    NULL) != 0) {
9296 				/* No source! Shouldn't happen */
9297 				ifaddr = INADDR_ANY;
9298 			}
9299 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9300 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9301 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
9302 			    ntohl(dst)));
9303 
9304 			/*
9305 			 * Check if our address is present more than
9306 			 * once as consecutive hops in source route.
9307 			 */
9308 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9309 				off += IP_ADDR_LEN;
9310 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9311 				goto redo_srr;
9312 			}
9313 			ipha->ipha_dst = dst;
9314 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9315 			break;
9316 		case IPOPT_RR:
9317 			off = opt[IPOPT_OFFSET];
9318 			off--;
9319 			if (optlen < IP_ADDR_LEN ||
9320 			    off > optlen - IP_ADDR_LEN) {
9321 				/* No more room - ignore */
9322 				ip1dbg((
9323 				    "ip_forward_options: end of RR\n"));
9324 				break;
9325 			}
9326 			/* Pick a reasonable address on the outbound if */
9327 			ASSERT(dst_ill != NULL);
9328 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9329 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9330 			    NULL) != 0) {
9331 				/* No source! Shouldn't happen */
9332 				ifaddr = INADDR_ANY;
9333 			}
9334 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9335 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9336 			break;
9337 		case IPOPT_TS:
9338 			/* Insert timestamp if there is room */
9339 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9340 			case IPOPT_TS_TSONLY:
9341 				off = IPOPT_TS_TIMELEN;
9342 				break;
9343 			case IPOPT_TS_PRESPEC:
9344 			case IPOPT_TS_PRESPEC_RFC791:
9345 				/* Verify that the address matched */
9346 				off = opt[IPOPT_OFFSET] - 1;
9347 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9348 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9349 					/* Not for us */
9350 					break;
9351 				}
9352 				/* FALLTHRU */
9353 			case IPOPT_TS_TSANDADDR:
9354 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9355 				break;
9356 			default:
9357 				/*
9358 				 * ip_*put_options should have already
9359 				 * dropped this packet.
9360 				 */
9361 				cmn_err(CE_PANIC, "ip_forward_options: "
9362 				    "unknown IT - bug in ip_input_options?\n");
9363 				return (B_TRUE);	/* Keep "lint" happy */
9364 			}
9365 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9366 				/* Increase overflow counter */
9367 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9368 				opt[IPOPT_POS_OV_FLG] =
9369 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9370 				    (off << 4));
9371 				break;
9372 			}
9373 			off = opt[IPOPT_OFFSET] - 1;
9374 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9375 			case IPOPT_TS_PRESPEC:
9376 			case IPOPT_TS_PRESPEC_RFC791:
9377 			case IPOPT_TS_TSANDADDR:
9378 				/* Pick a reasonable addr on the outbound if */
9379 				ASSERT(dst_ill != NULL);
9380 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9381 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9382 				    NULL, NULL) != 0) {
9383 					/* No source! Shouldn't happen */
9384 					ifaddr = INADDR_ANY;
9385 				}
9386 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9387 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9388 				/* FALLTHRU */
9389 			case IPOPT_TS_TSONLY:
9390 				off = opt[IPOPT_OFFSET] - 1;
9391 				/* Compute # of milliseconds since midnight */
9392 				gethrestime(&now);
9393 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9394 				    now.tv_nsec / (NANOSEC / MILLISEC);
9395 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9396 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9397 				break;
9398 			}
9399 			break;
9400 		}
9401 	}
9402 	return (B_TRUE);
9403 }
9404 
9405 /*
9406  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9407  * returns 'true' if there are still fragments left on the queue, in
9408  * which case we restart the timer.
9409  */
9410 void
9411 ill_frag_timer(void *arg)
9412 {
9413 	ill_t	*ill = (ill_t *)arg;
9414 	boolean_t frag_pending;
9415 	ip_stack_t	*ipst = ill->ill_ipst;
9416 	time_t	timeout;
9417 
9418 	mutex_enter(&ill->ill_lock);
9419 	ASSERT(!ill->ill_fragtimer_executing);
9420 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9421 		ill->ill_frag_timer_id = 0;
9422 		mutex_exit(&ill->ill_lock);
9423 		return;
9424 	}
9425 	ill->ill_fragtimer_executing = 1;
9426 	mutex_exit(&ill->ill_lock);
9427 
9428 	if (ill->ill_isv6)
9429 		timeout = ipst->ips_ipv6_frag_timeout;
9430 	else
9431 		timeout = ipst->ips_ip_g_frag_timeout;
9432 
9433 	frag_pending = ill_frag_timeout(ill, timeout);
9434 
9435 	/*
9436 	 * Restart the timer, if we have fragments pending or if someone
9437 	 * wanted us to be scheduled again.
9438 	 */
9439 	mutex_enter(&ill->ill_lock);
9440 	ill->ill_fragtimer_executing = 0;
9441 	ill->ill_frag_timer_id = 0;
9442 	if (frag_pending || ill->ill_fragtimer_needrestart)
9443 		ill_frag_timer_start(ill);
9444 	mutex_exit(&ill->ill_lock);
9445 }
9446 
9447 void
9448 ill_frag_timer_start(ill_t *ill)
9449 {
9450 	ip_stack_t	*ipst = ill->ill_ipst;
9451 	clock_t	timeo_ms;
9452 
9453 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9454 
9455 	/* If the ill is closing or opening don't proceed */
9456 	if (ill->ill_state_flags & ILL_CONDEMNED)
9457 		return;
9458 
9459 	if (ill->ill_fragtimer_executing) {
9460 		/*
9461 		 * ill_frag_timer is currently executing. Just record the
9462 		 * the fact that we want the timer to be restarted.
9463 		 * ill_frag_timer will post a timeout before it returns,
9464 		 * ensuring it will be called again.
9465 		 */
9466 		ill->ill_fragtimer_needrestart = 1;
9467 		return;
9468 	}
9469 
9470 	if (ill->ill_frag_timer_id == 0) {
9471 		if (ill->ill_isv6)
9472 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
9473 		else
9474 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
9475 		/*
9476 		 * The timer is neither running nor is the timeout handler
9477 		 * executing. Post a timeout so that ill_frag_timer will be
9478 		 * called
9479 		 */
9480 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9481 		    MSEC_TO_TICK(timeo_ms >> 1));
9482 		ill->ill_fragtimer_needrestart = 0;
9483 	}
9484 }
9485 
9486 /*
9487  * Update any source route, record route or timestamp options.
9488  * Check that we are at end of strict source route.
9489  * The options have already been checked for sanity in ip_input_options().
9490  */
9491 boolean_t
9492 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9493 {
9494 	ipoptp_t	opts;
9495 	uchar_t		*opt;
9496 	uint8_t		optval;
9497 	uint8_t		optlen;
9498 	ipaddr_t	dst;
9499 	ipaddr_t	ifaddr;
9500 	uint32_t	ts;
9501 	timestruc_t	now;
9502 	ill_t		*ill = ira->ira_ill;
9503 	ip_stack_t	*ipst = ill->ill_ipst;
9504 
9505 	ip2dbg(("ip_input_local_options\n"));
9506 
9507 	for (optval = ipoptp_first(&opts, ipha);
9508 	    optval != IPOPT_EOL;
9509 	    optval = ipoptp_next(&opts)) {
9510 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9511 		opt = opts.ipoptp_cur;
9512 		optlen = opts.ipoptp_len;
9513 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9514 		    optval, optlen));
9515 		switch (optval) {
9516 			uint32_t off;
9517 		case IPOPT_SSRR:
9518 		case IPOPT_LSRR:
9519 			off = opt[IPOPT_OFFSET];
9520 			off--;
9521 			if (optlen < IP_ADDR_LEN ||
9522 			    off > optlen - IP_ADDR_LEN) {
9523 				/* End of source route */
9524 				ip1dbg(("ip_input_local_options: end of SR\n"));
9525 				break;
9526 			}
9527 			/*
9528 			 * This will only happen if two consecutive entries
9529 			 * in the source route contains our address or if
9530 			 * it is a packet with a loose source route which
9531 			 * reaches us before consuming the whole source route
9532 			 */
9533 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9534 			if (optval == IPOPT_SSRR) {
9535 				goto bad_src_route;
9536 			}
9537 			/*
9538 			 * Hack: instead of dropping the packet truncate the
9539 			 * source route to what has been used by filling the
9540 			 * rest with IPOPT_NOP.
9541 			 */
9542 			opt[IPOPT_OLEN] = (uint8_t)off;
9543 			while (off < optlen) {
9544 				opt[off++] = IPOPT_NOP;
9545 			}
9546 			break;
9547 		case IPOPT_RR:
9548 			off = opt[IPOPT_OFFSET];
9549 			off--;
9550 			if (optlen < IP_ADDR_LEN ||
9551 			    off > optlen - IP_ADDR_LEN) {
9552 				/* No more room - ignore */
9553 				ip1dbg((
9554 				    "ip_input_local_options: end of RR\n"));
9555 				break;
9556 			}
9557 			/* Pick a reasonable address on the outbound if */
9558 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9559 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9560 			    NULL) != 0) {
9561 				/* No source! Shouldn't happen */
9562 				ifaddr = INADDR_ANY;
9563 			}
9564 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9565 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9566 			break;
9567 		case IPOPT_TS:
9568 			/* Insert timestamp if there is romm */
9569 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9570 			case IPOPT_TS_TSONLY:
9571 				off = IPOPT_TS_TIMELEN;
9572 				break;
9573 			case IPOPT_TS_PRESPEC:
9574 			case IPOPT_TS_PRESPEC_RFC791:
9575 				/* Verify that the address matched */
9576 				off = opt[IPOPT_OFFSET] - 1;
9577 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9578 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9579 					/* Not for us */
9580 					break;
9581 				}
9582 				/* FALLTHRU */
9583 			case IPOPT_TS_TSANDADDR:
9584 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9585 				break;
9586 			default:
9587 				/*
9588 				 * ip_*put_options should have already
9589 				 * dropped this packet.
9590 				 */
9591 				cmn_err(CE_PANIC, "ip_input_local_options: "
9592 				    "unknown IT - bug in ip_input_options?\n");
9593 				return (B_TRUE);	/* Keep "lint" happy */
9594 			}
9595 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9596 				/* Increase overflow counter */
9597 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9598 				opt[IPOPT_POS_OV_FLG] =
9599 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9600 				    (off << 4));
9601 				break;
9602 			}
9603 			off = opt[IPOPT_OFFSET] - 1;
9604 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9605 			case IPOPT_TS_PRESPEC:
9606 			case IPOPT_TS_PRESPEC_RFC791:
9607 			case IPOPT_TS_TSANDADDR:
9608 				/* Pick a reasonable addr on the outbound if */
9609 				if (ip_select_source_v4(ill, INADDR_ANY,
9610 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9611 				    &ifaddr, NULL, NULL) != 0) {
9612 					/* No source! Shouldn't happen */
9613 					ifaddr = INADDR_ANY;
9614 				}
9615 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9616 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9617 				/* FALLTHRU */
9618 			case IPOPT_TS_TSONLY:
9619 				off = opt[IPOPT_OFFSET] - 1;
9620 				/* Compute # of milliseconds since midnight */
9621 				gethrestime(&now);
9622 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9623 				    now.tv_nsec / (NANOSEC / MILLISEC);
9624 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9625 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9626 				break;
9627 			}
9628 			break;
9629 		}
9630 	}
9631 	return (B_TRUE);
9632 
9633 bad_src_route:
9634 	/* make sure we clear any indication of a hardware checksum */
9635 	DB_CKSUMFLAGS(mp) = 0;
9636 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9637 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9638 	return (B_FALSE);
9639 
9640 }
9641 
9642 /*
9643  * Process IP options in an inbound packet.  Always returns the nexthop.
9644  * Normally this is the passed in nexthop, but if there is an option
9645  * that effects the nexthop (such as a source route) that will be returned.
9646  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9647  * and mp freed.
9648  */
9649 ipaddr_t
9650 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9651     ip_recv_attr_t *ira, int *errorp)
9652 {
9653 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9654 	ipoptp_t	opts;
9655 	uchar_t		*opt;
9656 	uint8_t		optval;
9657 	uint8_t		optlen;
9658 	intptr_t	code = 0;
9659 	ire_t		*ire;
9660 
9661 	ip2dbg(("ip_input_options\n"));
9662 	*errorp = 0;
9663 	for (optval = ipoptp_first(&opts, ipha);
9664 	    optval != IPOPT_EOL;
9665 	    optval = ipoptp_next(&opts)) {
9666 		opt = opts.ipoptp_cur;
9667 		optlen = opts.ipoptp_len;
9668 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9669 		    optval, optlen));
9670 		/*
9671 		 * Note: we need to verify the checksum before we
9672 		 * modify anything thus this routine only extracts the next
9673 		 * hop dst from any source route.
9674 		 */
9675 		switch (optval) {
9676 			uint32_t off;
9677 		case IPOPT_SSRR:
9678 		case IPOPT_LSRR:
9679 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9680 				if (optval == IPOPT_SSRR) {
9681 					ip1dbg(("ip_input_options: not next"
9682 					    " strict source route 0x%x\n",
9683 					    ntohl(dst)));
9684 					code = (char *)&ipha->ipha_dst -
9685 					    (char *)ipha;
9686 					goto param_prob; /* RouterReq's */
9687 				}
9688 				ip2dbg(("ip_input_options: "
9689 				    "not next source route 0x%x\n",
9690 				    ntohl(dst)));
9691 				break;
9692 			}
9693 
9694 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9695 				ip1dbg((
9696 				    "ip_input_options: bad option offset\n"));
9697 				code = (char *)&opt[IPOPT_OLEN] -
9698 				    (char *)ipha;
9699 				goto param_prob;
9700 			}
9701 			off = opt[IPOPT_OFFSET];
9702 			off--;
9703 		redo_srr:
9704 			if (optlen < IP_ADDR_LEN ||
9705 			    off > optlen - IP_ADDR_LEN) {
9706 				/* End of source route */
9707 				ip1dbg(("ip_input_options: end of SR\n"));
9708 				break;
9709 			}
9710 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9711 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9712 			    ntohl(dst)));
9713 
9714 			/*
9715 			 * Check if our address is present more than
9716 			 * once as consecutive hops in source route.
9717 			 * XXX verify per-interface ip_forwarding
9718 			 * for source route?
9719 			 */
9720 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9721 				off += IP_ADDR_LEN;
9722 				goto redo_srr;
9723 			}
9724 
9725 			if (dst == htonl(INADDR_LOOPBACK)) {
9726 				ip1dbg(("ip_input_options: loopback addr in "
9727 				    "source route!\n"));
9728 				goto bad_src_route;
9729 			}
9730 			/*
9731 			 * For strict: verify that dst is directly
9732 			 * reachable.
9733 			 */
9734 			if (optval == IPOPT_SSRR) {
9735 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9736 				    IRE_IF_ALL, NULL, ALL_ZONES,
9737 				    ira->ira_tsl,
9738 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9739 				    NULL);
9740 				if (ire == NULL) {
9741 					ip1dbg(("ip_input_options: SSRR not "
9742 					    "directly reachable: 0x%x\n",
9743 					    ntohl(dst)));
9744 					goto bad_src_route;
9745 				}
9746 				ire_refrele(ire);
9747 			}
9748 			/*
9749 			 * Defer update of the offset and the record route
9750 			 * until the packet is forwarded.
9751 			 */
9752 			break;
9753 		case IPOPT_RR:
9754 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9755 				ip1dbg((
9756 				    "ip_input_options: bad option offset\n"));
9757 				code = (char *)&opt[IPOPT_OLEN] -
9758 				    (char *)ipha;
9759 				goto param_prob;
9760 			}
9761 			break;
9762 		case IPOPT_TS:
9763 			/*
9764 			 * Verify that length >= 5 and that there is either
9765 			 * room for another timestamp or that the overflow
9766 			 * counter is not maxed out.
9767 			 */
9768 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9769 			if (optlen < IPOPT_MINLEN_IT) {
9770 				goto param_prob;
9771 			}
9772 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9773 				ip1dbg((
9774 				    "ip_input_options: bad option offset\n"));
9775 				code = (char *)&opt[IPOPT_OFFSET] -
9776 				    (char *)ipha;
9777 				goto param_prob;
9778 			}
9779 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9780 			case IPOPT_TS_TSONLY:
9781 				off = IPOPT_TS_TIMELEN;
9782 				break;
9783 			case IPOPT_TS_TSANDADDR:
9784 			case IPOPT_TS_PRESPEC:
9785 			case IPOPT_TS_PRESPEC_RFC791:
9786 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9787 				break;
9788 			default:
9789 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9790 				    (char *)ipha;
9791 				goto param_prob;
9792 			}
9793 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9794 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9795 				/*
9796 				 * No room and the overflow counter is 15
9797 				 * already.
9798 				 */
9799 				goto param_prob;
9800 			}
9801 			break;
9802 		}
9803 	}
9804 
9805 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9806 		return (dst);
9807 	}
9808 
9809 	ip1dbg(("ip_input_options: error processing IP options."));
9810 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9811 
9812 param_prob:
9813 	/* make sure we clear any indication of a hardware checksum */
9814 	DB_CKSUMFLAGS(mp) = 0;
9815 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9816 	icmp_param_problem(mp, (uint8_t)code, ira);
9817 	*errorp = -1;
9818 	return (dst);
9819 
9820 bad_src_route:
9821 	/* make sure we clear any indication of a hardware checksum */
9822 	DB_CKSUMFLAGS(mp) = 0;
9823 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9824 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9825 	*errorp = -1;
9826 	return (dst);
9827 }
9828 
9829 /*
9830  * IP & ICMP info in >=14 msg's ...
9831  *  - ip fixed part (mib2_ip_t)
9832  *  - icmp fixed part (mib2_icmp_t)
9833  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9834  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9835  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9836  *  - ipRouteAttributeTable (ip 102)	labeled routes
9837  *  - ip multicast membership (ip_member_t)
9838  *  - ip multicast source filtering (ip_grpsrc_t)
9839  *  - igmp fixed part (struct igmpstat)
9840  *  - multicast routing stats (struct mrtstat)
9841  *  - multicast routing vifs (array of struct vifctl)
9842  *  - multicast routing routes (array of struct mfcctl)
9843  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9844  *					One per ill plus one generic
9845  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9846  *					One per ill plus one generic
9847  *  - ipv6RouteEntry			all IPv6 IREs
9848  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9849  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9850  *  - ipv6AddrEntry			all IPv6 ipifs
9851  *  - ipv6 multicast membership (ipv6_member_t)
9852  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9853  *
9854  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9855  * already filled in by the caller.
9856  * Return value of 0 indicates that no messages were sent and caller
9857  * should free mpctl.
9858  */
9859 int
9860 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
9861 {
9862 	ip_stack_t *ipst;
9863 	sctp_stack_t *sctps;
9864 
9865 	if (q->q_next != NULL) {
9866 		ipst = ILLQ_TO_IPST(q);
9867 	} else {
9868 		ipst = CONNQ_TO_IPST(q);
9869 	}
9870 	ASSERT(ipst != NULL);
9871 	sctps = ipst->ips_netstack->netstack_sctp;
9872 
9873 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9874 		return (0);
9875 	}
9876 
9877 	/*
9878 	 * For the purposes of the (broken) packet shell use
9879 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9880 	 * to make TCP and UDP appear first in the list of mib items.
9881 	 * TBD: We could expand this and use it in netstat so that
9882 	 * the kernel doesn't have to produce large tables (connections,
9883 	 * routes, etc) when netstat only wants the statistics or a particular
9884 	 * table.
9885 	 */
9886 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9887 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9888 			return (1);
9889 		}
9890 	}
9891 
9892 	if (level != MIB2_TCP) {
9893 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
9894 			return (1);
9895 		}
9896 	}
9897 
9898 	if (level != MIB2_UDP) {
9899 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
9900 			return (1);
9901 		}
9902 	}
9903 
9904 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9905 	    ipst)) == NULL) {
9906 		return (1);
9907 	}
9908 
9909 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
9910 		return (1);
9911 	}
9912 
9913 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9914 		return (1);
9915 	}
9916 
9917 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9918 		return (1);
9919 	}
9920 
9921 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9922 		return (1);
9923 	}
9924 
9925 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9926 		return (1);
9927 	}
9928 
9929 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
9930 		return (1);
9931 	}
9932 
9933 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
9934 		return (1);
9935 	}
9936 
9937 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9938 		return (1);
9939 	}
9940 
9941 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9942 		return (1);
9943 	}
9944 
9945 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9946 		return (1);
9947 	}
9948 
9949 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9950 		return (1);
9951 	}
9952 
9953 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9954 		return (1);
9955 	}
9956 
9957 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9958 		return (1);
9959 	}
9960 
9961 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9962 	if (mpctl == NULL)
9963 		return (1);
9964 
9965 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9966 	if (mpctl == NULL)
9967 		return (1);
9968 
9969 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9970 		return (1);
9971 	}
9972 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9973 		return (1);
9974 	}
9975 	freemsg(mpctl);
9976 	return (1);
9977 }
9978 
9979 /* Get global (legacy) IPv4 statistics */
9980 static mblk_t *
9981 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9982     ip_stack_t *ipst)
9983 {
9984 	mib2_ip_t		old_ip_mib;
9985 	struct opthdr		*optp;
9986 	mblk_t			*mp2ctl;
9987 
9988 	/*
9989 	 * make a copy of the original message
9990 	 */
9991 	mp2ctl = copymsg(mpctl);
9992 
9993 	/* fixed length IP structure... */
9994 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9995 	optp->level = MIB2_IP;
9996 	optp->name = 0;
9997 	SET_MIB(old_ip_mib.ipForwarding,
9998 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9999 	SET_MIB(old_ip_mib.ipDefaultTTL,
10000 	    (uint32_t)ipst->ips_ip_def_ttl);
10001 	SET_MIB(old_ip_mib.ipReasmTimeout,
10002 	    ipst->ips_ip_g_frag_timeout);
10003 	SET_MIB(old_ip_mib.ipAddrEntrySize,
10004 	    sizeof (mib2_ipAddrEntry_t));
10005 	SET_MIB(old_ip_mib.ipRouteEntrySize,
10006 	    sizeof (mib2_ipRouteEntry_t));
10007 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
10008 	    sizeof (mib2_ipNetToMediaEntry_t));
10009 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
10010 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
10011 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
10012 	    sizeof (mib2_ipAttributeEntry_t));
10013 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
10014 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
10015 
10016 	/*
10017 	 * Grab the statistics from the new IP MIB
10018 	 */
10019 	SET_MIB(old_ip_mib.ipInReceives,
10020 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
10021 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
10022 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
10023 	SET_MIB(old_ip_mib.ipForwDatagrams,
10024 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
10025 	SET_MIB(old_ip_mib.ipInUnknownProtos,
10026 	    ipmib->ipIfStatsInUnknownProtos);
10027 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
10028 	SET_MIB(old_ip_mib.ipInDelivers,
10029 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
10030 	SET_MIB(old_ip_mib.ipOutRequests,
10031 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
10032 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
10033 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
10034 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
10035 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
10036 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
10037 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
10038 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
10039 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
10040 
10041 	/* ipRoutingDiscards is not being used */
10042 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
10043 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
10044 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
10045 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
10046 	SET_MIB(old_ip_mib.ipReasmDuplicates,
10047 	    ipmib->ipIfStatsReasmDuplicates);
10048 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
10049 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
10050 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
10051 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
10052 	SET_MIB(old_ip_mib.rawipInOverflows,
10053 	    ipmib->rawipIfStatsInOverflows);
10054 
10055 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
10056 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
10057 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
10058 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
10059 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
10060 	    ipmib->ipIfStatsOutSwitchIPVersion);
10061 
10062 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
10063 	    (int)sizeof (old_ip_mib))) {
10064 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
10065 		    (uint_t)sizeof (old_ip_mib)));
10066 	}
10067 
10068 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10069 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
10070 	    (int)optp->level, (int)optp->name, (int)optp->len));
10071 	qreply(q, mpctl);
10072 	return (mp2ctl);
10073 }
10074 
10075 /* Per interface IPv4 statistics */
10076 static mblk_t *
10077 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10078 {
10079 	struct opthdr		*optp;
10080 	mblk_t			*mp2ctl;
10081 	ill_t			*ill;
10082 	ill_walk_context_t	ctx;
10083 	mblk_t			*mp_tail = NULL;
10084 	mib2_ipIfStatsEntry_t	global_ip_mib;
10085 
10086 	/*
10087 	 * Make a copy of the original message
10088 	 */
10089 	mp2ctl = copymsg(mpctl);
10090 
10091 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10092 	optp->level = MIB2_IP;
10093 	optp->name = MIB2_IP_TRAFFIC_STATS;
10094 	/* Include "unknown interface" ip_mib */
10095 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
10096 	ipst->ips_ip_mib.ipIfStatsIfIndex =
10097 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10098 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
10099 	    (ipst->ips_ip_g_forward ? 1 : 2));
10100 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
10101 	    (uint32_t)ipst->ips_ip_def_ttl);
10102 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
10103 	    sizeof (mib2_ipIfStatsEntry_t));
10104 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
10105 	    sizeof (mib2_ipAddrEntry_t));
10106 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
10107 	    sizeof (mib2_ipRouteEntry_t));
10108 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
10109 	    sizeof (mib2_ipNetToMediaEntry_t));
10110 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
10111 	    sizeof (ip_member_t));
10112 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
10113 	    sizeof (ip_grpsrc_t));
10114 
10115 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10116 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
10117 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
10118 		    "failed to allocate %u bytes\n",
10119 		    (uint_t)sizeof (ipst->ips_ip_mib)));
10120 	}
10121 
10122 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
10123 
10124 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10125 	ill = ILL_START_WALK_V4(&ctx, ipst);
10126 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10127 		ill->ill_ip_mib->ipIfStatsIfIndex =
10128 		    ill->ill_phyint->phyint_ifindex;
10129 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10130 		    (ipst->ips_ip_g_forward ? 1 : 2));
10131 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
10132 		    (uint32_t)ipst->ips_ip_def_ttl);
10133 
10134 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
10135 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10136 		    (char *)ill->ill_ip_mib,
10137 		    (int)sizeof (*ill->ill_ip_mib))) {
10138 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
10139 			    "failed to allocate %u bytes\n",
10140 			    (uint_t)sizeof (*ill->ill_ip_mib)));
10141 		}
10142 	}
10143 	rw_exit(&ipst->ips_ill_g_lock);
10144 
10145 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10146 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
10147 	    "level %d, name %d, len %d\n",
10148 	    (int)optp->level, (int)optp->name, (int)optp->len));
10149 	qreply(q, mpctl);
10150 
10151 	if (mp2ctl == NULL)
10152 		return (NULL);
10153 
10154 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
10155 }
10156 
10157 /* Global IPv4 ICMP statistics */
10158 static mblk_t *
10159 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10160 {
10161 	struct opthdr		*optp;
10162 	mblk_t			*mp2ctl;
10163 
10164 	/*
10165 	 * Make a copy of the original message
10166 	 */
10167 	mp2ctl = copymsg(mpctl);
10168 
10169 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10170 	optp->level = MIB2_ICMP;
10171 	optp->name = 0;
10172 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
10173 	    (int)sizeof (ipst->ips_icmp_mib))) {
10174 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
10175 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
10176 	}
10177 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10178 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
10179 	    (int)optp->level, (int)optp->name, (int)optp->len));
10180 	qreply(q, mpctl);
10181 	return (mp2ctl);
10182 }
10183 
10184 /* Global IPv4 IGMP statistics */
10185 static mblk_t *
10186 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10187 {
10188 	struct opthdr		*optp;
10189 	mblk_t			*mp2ctl;
10190 
10191 	/*
10192 	 * make a copy of the original message
10193 	 */
10194 	mp2ctl = copymsg(mpctl);
10195 
10196 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10197 	optp->level = EXPER_IGMP;
10198 	optp->name = 0;
10199 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
10200 	    (int)sizeof (ipst->ips_igmpstat))) {
10201 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
10202 		    (uint_t)sizeof (ipst->ips_igmpstat)));
10203 	}
10204 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10205 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
10206 	    (int)optp->level, (int)optp->name, (int)optp->len));
10207 	qreply(q, mpctl);
10208 	return (mp2ctl);
10209 }
10210 
10211 /* Global IPv4 Multicast Routing statistics */
10212 static mblk_t *
10213 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10214 {
10215 	struct opthdr		*optp;
10216 	mblk_t			*mp2ctl;
10217 
10218 	/*
10219 	 * make a copy of the original message
10220 	 */
10221 	mp2ctl = copymsg(mpctl);
10222 
10223 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10224 	optp->level = EXPER_DVMRP;
10225 	optp->name = 0;
10226 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
10227 		ip0dbg(("ip_mroute_stats: failed\n"));
10228 	}
10229 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10230 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
10231 	    (int)optp->level, (int)optp->name, (int)optp->len));
10232 	qreply(q, mpctl);
10233 	return (mp2ctl);
10234 }
10235 
10236 /* IPv4 address information */
10237 static mblk_t *
10238 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10239 {
10240 	struct opthdr		*optp;
10241 	mblk_t			*mp2ctl;
10242 	mblk_t			*mp_tail = NULL;
10243 	ill_t			*ill;
10244 	ipif_t			*ipif;
10245 	uint_t			bitval;
10246 	mib2_ipAddrEntry_t	mae;
10247 	zoneid_t		zoneid;
10248 	ill_walk_context_t ctx;
10249 
10250 	/*
10251 	 * make a copy of the original message
10252 	 */
10253 	mp2ctl = copymsg(mpctl);
10254 
10255 	/* ipAddrEntryTable */
10256 
10257 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10258 	optp->level = MIB2_IP;
10259 	optp->name = MIB2_IP_ADDR;
10260 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10261 
10262 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10263 	ill = ILL_START_WALK_V4(&ctx, ipst);
10264 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10265 		for (ipif = ill->ill_ipif; ipif != NULL;
10266 		    ipif = ipif->ipif_next) {
10267 			if (ipif->ipif_zoneid != zoneid &&
10268 			    ipif->ipif_zoneid != ALL_ZONES)
10269 				continue;
10270 			/* Sum of count from dead IRE_LO* and our current */
10271 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10272 			if (ipif->ipif_ire_local != NULL) {
10273 				mae.ipAdEntInfo.ae_ibcnt +=
10274 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10275 			}
10276 			mae.ipAdEntInfo.ae_obcnt = 0;
10277 			mae.ipAdEntInfo.ae_focnt = 0;
10278 
10279 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
10280 			    OCTET_LENGTH);
10281 			mae.ipAdEntIfIndex.o_length =
10282 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
10283 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
10284 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
10285 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
10286 			mae.ipAdEntInfo.ae_subnet_len =
10287 			    ip_mask_to_plen(ipif->ipif_net_mask);
10288 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
10289 			for (bitval = 1;
10290 			    bitval &&
10291 			    !(bitval & ipif->ipif_brd_addr);
10292 			    bitval <<= 1)
10293 				noop;
10294 			mae.ipAdEntBcastAddr = bitval;
10295 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10296 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10297 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
10298 			mae.ipAdEntInfo.ae_broadcast_addr =
10299 			    ipif->ipif_brd_addr;
10300 			mae.ipAdEntInfo.ae_pp_dst_addr =
10301 			    ipif->ipif_pp_dst_addr;
10302 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10303 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10304 			mae.ipAdEntRetransmitTime =
10305 			    ill->ill_reachable_retrans_time;
10306 
10307 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10308 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
10309 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10310 				    "allocate %u bytes\n",
10311 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
10312 			}
10313 		}
10314 	}
10315 	rw_exit(&ipst->ips_ill_g_lock);
10316 
10317 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10318 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10319 	    (int)optp->level, (int)optp->name, (int)optp->len));
10320 	qreply(q, mpctl);
10321 	return (mp2ctl);
10322 }
10323 
10324 /* IPv6 address information */
10325 static mblk_t *
10326 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10327 {
10328 	struct opthdr		*optp;
10329 	mblk_t			*mp2ctl;
10330 	mblk_t			*mp_tail = NULL;
10331 	ill_t			*ill;
10332 	ipif_t			*ipif;
10333 	mib2_ipv6AddrEntry_t	mae6;
10334 	zoneid_t		zoneid;
10335 	ill_walk_context_t	ctx;
10336 
10337 	/*
10338 	 * make a copy of the original message
10339 	 */
10340 	mp2ctl = copymsg(mpctl);
10341 
10342 	/* ipv6AddrEntryTable */
10343 
10344 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10345 	optp->level = MIB2_IP6;
10346 	optp->name = MIB2_IP6_ADDR;
10347 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10348 
10349 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10350 	ill = ILL_START_WALK_V6(&ctx, ipst);
10351 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10352 		for (ipif = ill->ill_ipif; ipif != NULL;
10353 		    ipif = ipif->ipif_next) {
10354 			if (ipif->ipif_zoneid != zoneid &&
10355 			    ipif->ipif_zoneid != ALL_ZONES)
10356 				continue;
10357 			/* Sum of count from dead IRE_LO* and our current */
10358 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10359 			if (ipif->ipif_ire_local != NULL) {
10360 				mae6.ipv6AddrInfo.ae_ibcnt +=
10361 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10362 			}
10363 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10364 			mae6.ipv6AddrInfo.ae_focnt = 0;
10365 
10366 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10367 			    OCTET_LENGTH);
10368 			mae6.ipv6AddrIfIndex.o_length =
10369 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10370 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10371 			mae6.ipv6AddrPfxLength =
10372 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10373 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10374 			mae6.ipv6AddrInfo.ae_subnet_len =
10375 			    mae6.ipv6AddrPfxLength;
10376 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10377 
10378 			/* Type: stateless(1), stateful(2), unknown(3) */
10379 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10380 				mae6.ipv6AddrType = 1;
10381 			else
10382 				mae6.ipv6AddrType = 2;
10383 			/* Anycast: true(1), false(2) */
10384 			if (ipif->ipif_flags & IPIF_ANYCAST)
10385 				mae6.ipv6AddrAnycastFlag = 1;
10386 			else
10387 				mae6.ipv6AddrAnycastFlag = 2;
10388 
10389 			/*
10390 			 * Address status: preferred(1), deprecated(2),
10391 			 * invalid(3), inaccessible(4), unknown(5)
10392 			 */
10393 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10394 				mae6.ipv6AddrStatus = 3;
10395 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10396 				mae6.ipv6AddrStatus = 2;
10397 			else
10398 				mae6.ipv6AddrStatus = 1;
10399 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10400 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
10401 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10402 			    ipif->ipif_v6pp_dst_addr;
10403 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10404 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10405 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10406 			mae6.ipv6AddrIdentifier = ill->ill_token;
10407 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10408 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10409 			mae6.ipv6AddrRetransmitTime =
10410 			    ill->ill_reachable_retrans_time;
10411 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10412 			    (char *)&mae6,
10413 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
10414 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10415 				    "allocate %u bytes\n",
10416 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
10417 			}
10418 		}
10419 	}
10420 	rw_exit(&ipst->ips_ill_g_lock);
10421 
10422 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10423 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10424 	    (int)optp->level, (int)optp->name, (int)optp->len));
10425 	qreply(q, mpctl);
10426 	return (mp2ctl);
10427 }
10428 
10429 /* IPv4 multicast group membership. */
10430 static mblk_t *
10431 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10432 {
10433 	struct opthdr		*optp;
10434 	mblk_t			*mp2ctl;
10435 	ill_t			*ill;
10436 	ipif_t			*ipif;
10437 	ilm_t			*ilm;
10438 	ip_member_t		ipm;
10439 	mblk_t			*mp_tail = NULL;
10440 	ill_walk_context_t	ctx;
10441 	zoneid_t		zoneid;
10442 
10443 	/*
10444 	 * make a copy of the original message
10445 	 */
10446 	mp2ctl = copymsg(mpctl);
10447 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10448 
10449 	/* ipGroupMember table */
10450 	optp = (struct opthdr *)&mpctl->b_rptr[
10451 	    sizeof (struct T_optmgmt_ack)];
10452 	optp->level = MIB2_IP;
10453 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10454 
10455 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10456 	ill = ILL_START_WALK_V4(&ctx, ipst);
10457 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10458 		/* Make sure the ill isn't going away. */
10459 		if (!ill_check_and_refhold(ill))
10460 			continue;
10461 		rw_exit(&ipst->ips_ill_g_lock);
10462 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10463 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10464 			if (ilm->ilm_zoneid != zoneid &&
10465 			    ilm->ilm_zoneid != ALL_ZONES)
10466 				continue;
10467 
10468 			/* Is there an ipif for ilm_ifaddr? */
10469 			for (ipif = ill->ill_ipif; ipif != NULL;
10470 			    ipif = ipif->ipif_next) {
10471 				if (!IPIF_IS_CONDEMNED(ipif) &&
10472 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10473 				    ilm->ilm_ifaddr != INADDR_ANY)
10474 					break;
10475 			}
10476 			if (ipif != NULL) {
10477 				ipif_get_name(ipif,
10478 				    ipm.ipGroupMemberIfIndex.o_bytes,
10479 				    OCTET_LENGTH);
10480 			} else {
10481 				ill_get_name(ill,
10482 				    ipm.ipGroupMemberIfIndex.o_bytes,
10483 				    OCTET_LENGTH);
10484 			}
10485 			ipm.ipGroupMemberIfIndex.o_length =
10486 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10487 
10488 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10489 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10490 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10491 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10492 			    (char *)&ipm, (int)sizeof (ipm))) {
10493 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10494 				    "failed to allocate %u bytes\n",
10495 				    (uint_t)sizeof (ipm)));
10496 			}
10497 		}
10498 		rw_exit(&ill->ill_mcast_lock);
10499 		ill_refrele(ill);
10500 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10501 	}
10502 	rw_exit(&ipst->ips_ill_g_lock);
10503 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10504 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10505 	    (int)optp->level, (int)optp->name, (int)optp->len));
10506 	qreply(q, mpctl);
10507 	return (mp2ctl);
10508 }
10509 
10510 /* IPv6 multicast group membership. */
10511 static mblk_t *
10512 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10513 {
10514 	struct opthdr		*optp;
10515 	mblk_t			*mp2ctl;
10516 	ill_t			*ill;
10517 	ilm_t			*ilm;
10518 	ipv6_member_t		ipm6;
10519 	mblk_t			*mp_tail = NULL;
10520 	ill_walk_context_t	ctx;
10521 	zoneid_t		zoneid;
10522 
10523 	/*
10524 	 * make a copy of the original message
10525 	 */
10526 	mp2ctl = copymsg(mpctl);
10527 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10528 
10529 	/* ip6GroupMember table */
10530 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10531 	optp->level = MIB2_IP6;
10532 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10533 
10534 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10535 	ill = ILL_START_WALK_V6(&ctx, ipst);
10536 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10537 		/* Make sure the ill isn't going away. */
10538 		if (!ill_check_and_refhold(ill))
10539 			continue;
10540 		rw_exit(&ipst->ips_ill_g_lock);
10541 		/*
10542 		 * Normally we don't have any members on under IPMP interfaces.
10543 		 * We report them as a debugging aid.
10544 		 */
10545 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10546 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10547 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10548 			if (ilm->ilm_zoneid != zoneid &&
10549 			    ilm->ilm_zoneid != ALL_ZONES)
10550 				continue;	/* not this zone */
10551 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10552 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10553 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10554 			if (!snmp_append_data2(mpctl->b_cont,
10555 			    &mp_tail,
10556 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10557 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10558 				    "failed to allocate %u bytes\n",
10559 				    (uint_t)sizeof (ipm6)));
10560 			}
10561 		}
10562 		rw_exit(&ill->ill_mcast_lock);
10563 		ill_refrele(ill);
10564 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10565 	}
10566 	rw_exit(&ipst->ips_ill_g_lock);
10567 
10568 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10569 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10570 	    (int)optp->level, (int)optp->name, (int)optp->len));
10571 	qreply(q, mpctl);
10572 	return (mp2ctl);
10573 }
10574 
10575 /* IP multicast filtered sources */
10576 static mblk_t *
10577 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10578 {
10579 	struct opthdr		*optp;
10580 	mblk_t			*mp2ctl;
10581 	ill_t			*ill;
10582 	ipif_t			*ipif;
10583 	ilm_t			*ilm;
10584 	ip_grpsrc_t		ips;
10585 	mblk_t			*mp_tail = NULL;
10586 	ill_walk_context_t	ctx;
10587 	zoneid_t		zoneid;
10588 	int			i;
10589 	slist_t			*sl;
10590 
10591 	/*
10592 	 * make a copy of the original message
10593 	 */
10594 	mp2ctl = copymsg(mpctl);
10595 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10596 
10597 	/* ipGroupSource table */
10598 	optp = (struct opthdr *)&mpctl->b_rptr[
10599 	    sizeof (struct T_optmgmt_ack)];
10600 	optp->level = MIB2_IP;
10601 	optp->name = EXPER_IP_GROUP_SOURCES;
10602 
10603 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10604 	ill = ILL_START_WALK_V4(&ctx, ipst);
10605 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10606 		/* Make sure the ill isn't going away. */
10607 		if (!ill_check_and_refhold(ill))
10608 			continue;
10609 		rw_exit(&ipst->ips_ill_g_lock);
10610 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10611 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10612 			sl = ilm->ilm_filter;
10613 			if (ilm->ilm_zoneid != zoneid &&
10614 			    ilm->ilm_zoneid != ALL_ZONES)
10615 				continue;
10616 			if (SLIST_IS_EMPTY(sl))
10617 				continue;
10618 
10619 			/* Is there an ipif for ilm_ifaddr? */
10620 			for (ipif = ill->ill_ipif; ipif != NULL;
10621 			    ipif = ipif->ipif_next) {
10622 				if (!IPIF_IS_CONDEMNED(ipif) &&
10623 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10624 				    ilm->ilm_ifaddr != INADDR_ANY)
10625 					break;
10626 			}
10627 			if (ipif != NULL) {
10628 				ipif_get_name(ipif,
10629 				    ips.ipGroupSourceIfIndex.o_bytes,
10630 				    OCTET_LENGTH);
10631 			} else {
10632 				ill_get_name(ill,
10633 				    ips.ipGroupSourceIfIndex.o_bytes,
10634 				    OCTET_LENGTH);
10635 			}
10636 			ips.ipGroupSourceIfIndex.o_length =
10637 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10638 
10639 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10640 			for (i = 0; i < sl->sl_numsrc; i++) {
10641 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10642 					continue;
10643 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10644 				    ips.ipGroupSourceAddress);
10645 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10646 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10647 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10648 					    " failed to allocate %u bytes\n",
10649 					    (uint_t)sizeof (ips)));
10650 				}
10651 			}
10652 		}
10653 		rw_exit(&ill->ill_mcast_lock);
10654 		ill_refrele(ill);
10655 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10656 	}
10657 	rw_exit(&ipst->ips_ill_g_lock);
10658 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10659 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10660 	    (int)optp->level, (int)optp->name, (int)optp->len));
10661 	qreply(q, mpctl);
10662 	return (mp2ctl);
10663 }
10664 
10665 /* IPv6 multicast filtered sources. */
10666 static mblk_t *
10667 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10668 {
10669 	struct opthdr		*optp;
10670 	mblk_t			*mp2ctl;
10671 	ill_t			*ill;
10672 	ilm_t			*ilm;
10673 	ipv6_grpsrc_t		ips6;
10674 	mblk_t			*mp_tail = NULL;
10675 	ill_walk_context_t	ctx;
10676 	zoneid_t		zoneid;
10677 	int			i;
10678 	slist_t			*sl;
10679 
10680 	/*
10681 	 * make a copy of the original message
10682 	 */
10683 	mp2ctl = copymsg(mpctl);
10684 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10685 
10686 	/* ip6GroupMember table */
10687 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10688 	optp->level = MIB2_IP6;
10689 	optp->name = EXPER_IP6_GROUP_SOURCES;
10690 
10691 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10692 	ill = ILL_START_WALK_V6(&ctx, ipst);
10693 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10694 		/* Make sure the ill isn't going away. */
10695 		if (!ill_check_and_refhold(ill))
10696 			continue;
10697 		rw_exit(&ipst->ips_ill_g_lock);
10698 		/*
10699 		 * Normally we don't have any members on under IPMP interfaces.
10700 		 * We report them as a debugging aid.
10701 		 */
10702 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10703 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10704 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10705 			sl = ilm->ilm_filter;
10706 			if (ilm->ilm_zoneid != zoneid &&
10707 			    ilm->ilm_zoneid != ALL_ZONES)
10708 				continue;
10709 			if (SLIST_IS_EMPTY(sl))
10710 				continue;
10711 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10712 			for (i = 0; i < sl->sl_numsrc; i++) {
10713 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10714 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10715 				    (char *)&ips6, (int)sizeof (ips6))) {
10716 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10717 					    "group_src: failed to allocate "
10718 					    "%u bytes\n",
10719 					    (uint_t)sizeof (ips6)));
10720 				}
10721 			}
10722 		}
10723 		rw_exit(&ill->ill_mcast_lock);
10724 		ill_refrele(ill);
10725 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10726 	}
10727 	rw_exit(&ipst->ips_ill_g_lock);
10728 
10729 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10730 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10731 	    (int)optp->level, (int)optp->name, (int)optp->len));
10732 	qreply(q, mpctl);
10733 	return (mp2ctl);
10734 }
10735 
10736 /* Multicast routing virtual interface table. */
10737 static mblk_t *
10738 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10739 {
10740 	struct opthdr		*optp;
10741 	mblk_t			*mp2ctl;
10742 
10743 	/*
10744 	 * make a copy of the original message
10745 	 */
10746 	mp2ctl = copymsg(mpctl);
10747 
10748 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10749 	optp->level = EXPER_DVMRP;
10750 	optp->name = EXPER_DVMRP_VIF;
10751 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10752 		ip0dbg(("ip_mroute_vif: failed\n"));
10753 	}
10754 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10755 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10756 	    (int)optp->level, (int)optp->name, (int)optp->len));
10757 	qreply(q, mpctl);
10758 	return (mp2ctl);
10759 }
10760 
10761 /* Multicast routing table. */
10762 static mblk_t *
10763 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10764 {
10765 	struct opthdr		*optp;
10766 	mblk_t			*mp2ctl;
10767 
10768 	/*
10769 	 * make a copy of the original message
10770 	 */
10771 	mp2ctl = copymsg(mpctl);
10772 
10773 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10774 	optp->level = EXPER_DVMRP;
10775 	optp->name = EXPER_DVMRP_MRT;
10776 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10777 		ip0dbg(("ip_mroute_mrt: failed\n"));
10778 	}
10779 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10780 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10781 	    (int)optp->level, (int)optp->name, (int)optp->len));
10782 	qreply(q, mpctl);
10783 	return (mp2ctl);
10784 }
10785 
10786 /*
10787  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10788  * in one IRE walk.
10789  */
10790 static mblk_t *
10791 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10792     ip_stack_t *ipst)
10793 {
10794 	struct opthdr	*optp;
10795 	mblk_t		*mp2ctl;	/* Returned */
10796 	mblk_t		*mp3ctl;	/* nettomedia */
10797 	mblk_t		*mp4ctl;	/* routeattrs */
10798 	iproutedata_t	ird;
10799 	zoneid_t	zoneid;
10800 
10801 	/*
10802 	 * make copies of the original message
10803 	 *	- mp2ctl is returned unchanged to the caller for his use
10804 	 *	- mpctl is sent upstream as ipRouteEntryTable
10805 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10806 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10807 	 */
10808 	mp2ctl = copymsg(mpctl);
10809 	mp3ctl = copymsg(mpctl);
10810 	mp4ctl = copymsg(mpctl);
10811 	if (mp3ctl == NULL || mp4ctl == NULL) {
10812 		freemsg(mp4ctl);
10813 		freemsg(mp3ctl);
10814 		freemsg(mp2ctl);
10815 		freemsg(mpctl);
10816 		return (NULL);
10817 	}
10818 
10819 	bzero(&ird, sizeof (ird));
10820 
10821 	ird.ird_route.lp_head = mpctl->b_cont;
10822 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10823 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10824 	/*
10825 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10826 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10827 	 * intended a temporary solution until a proper MIB API is provided
10828 	 * that provides complete filtering/caller-opt-in.
10829 	 */
10830 	if (level == EXPER_IP_AND_ALL_IRES)
10831 		ird.ird_flags |= IRD_REPORT_ALL;
10832 
10833 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10834 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10835 
10836 	/* ipRouteEntryTable in mpctl */
10837 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10838 	optp->level = MIB2_IP;
10839 	optp->name = MIB2_IP_ROUTE;
10840 	optp->len = msgdsize(ird.ird_route.lp_head);
10841 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10842 	    (int)optp->level, (int)optp->name, (int)optp->len));
10843 	qreply(q, mpctl);
10844 
10845 	/* ipNetToMediaEntryTable in mp3ctl */
10846 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10847 
10848 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10849 	optp->level = MIB2_IP;
10850 	optp->name = MIB2_IP_MEDIA;
10851 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10852 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10853 	    (int)optp->level, (int)optp->name, (int)optp->len));
10854 	qreply(q, mp3ctl);
10855 
10856 	/* ipRouteAttributeTable in mp4ctl */
10857 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10858 	optp->level = MIB2_IP;
10859 	optp->name = EXPER_IP_RTATTR;
10860 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10861 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10862 	    (int)optp->level, (int)optp->name, (int)optp->len));
10863 	if (optp->len == 0)
10864 		freemsg(mp4ctl);
10865 	else
10866 		qreply(q, mp4ctl);
10867 
10868 	return (mp2ctl);
10869 }
10870 
10871 /*
10872  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10873  * ipv6NetToMediaEntryTable in an NDP walk.
10874  */
10875 static mblk_t *
10876 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10877     ip_stack_t *ipst)
10878 {
10879 	struct opthdr	*optp;
10880 	mblk_t		*mp2ctl;	/* Returned */
10881 	mblk_t		*mp3ctl;	/* nettomedia */
10882 	mblk_t		*mp4ctl;	/* routeattrs */
10883 	iproutedata_t	ird;
10884 	zoneid_t	zoneid;
10885 
10886 	/*
10887 	 * make copies of the original message
10888 	 *	- mp2ctl is returned unchanged to the caller for his use
10889 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10890 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10891 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10892 	 */
10893 	mp2ctl = copymsg(mpctl);
10894 	mp3ctl = copymsg(mpctl);
10895 	mp4ctl = copymsg(mpctl);
10896 	if (mp3ctl == NULL || mp4ctl == NULL) {
10897 		freemsg(mp4ctl);
10898 		freemsg(mp3ctl);
10899 		freemsg(mp2ctl);
10900 		freemsg(mpctl);
10901 		return (NULL);
10902 	}
10903 
10904 	bzero(&ird, sizeof (ird));
10905 
10906 	ird.ird_route.lp_head = mpctl->b_cont;
10907 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10908 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10909 	/*
10910 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10911 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10912 	 * intended a temporary solution until a proper MIB API is provided
10913 	 * that provides complete filtering/caller-opt-in.
10914 	 */
10915 	if (level == EXPER_IP_AND_ALL_IRES)
10916 		ird.ird_flags |= IRD_REPORT_ALL;
10917 
10918 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10919 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10920 
10921 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10922 	optp->level = MIB2_IP6;
10923 	optp->name = MIB2_IP6_ROUTE;
10924 	optp->len = msgdsize(ird.ird_route.lp_head);
10925 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10926 	    (int)optp->level, (int)optp->name, (int)optp->len));
10927 	qreply(q, mpctl);
10928 
10929 	/* ipv6NetToMediaEntryTable in mp3ctl */
10930 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10931 
10932 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10933 	optp->level = MIB2_IP6;
10934 	optp->name = MIB2_IP6_MEDIA;
10935 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10936 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10937 	    (int)optp->level, (int)optp->name, (int)optp->len));
10938 	qreply(q, mp3ctl);
10939 
10940 	/* ipv6RouteAttributeTable in mp4ctl */
10941 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10942 	optp->level = MIB2_IP6;
10943 	optp->name = EXPER_IP_RTATTR;
10944 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10945 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10946 	    (int)optp->level, (int)optp->name, (int)optp->len));
10947 	if (optp->len == 0)
10948 		freemsg(mp4ctl);
10949 	else
10950 		qreply(q, mp4ctl);
10951 
10952 	return (mp2ctl);
10953 }
10954 
10955 /*
10956  * IPv6 mib: One per ill
10957  */
10958 static mblk_t *
10959 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10960 {
10961 	struct opthdr		*optp;
10962 	mblk_t			*mp2ctl;
10963 	ill_t			*ill;
10964 	ill_walk_context_t	ctx;
10965 	mblk_t			*mp_tail = NULL;
10966 
10967 	/*
10968 	 * Make a copy of the original message
10969 	 */
10970 	mp2ctl = copymsg(mpctl);
10971 
10972 	/* fixed length IPv6 structure ... */
10973 
10974 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10975 	optp->level = MIB2_IP6;
10976 	optp->name = 0;
10977 	/* Include "unknown interface" ip6_mib */
10978 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10979 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10980 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10981 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10982 	    ipst->ips_ipv6_forward ? 1 : 2);
10983 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10984 	    ipst->ips_ipv6_def_hops);
10985 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10986 	    sizeof (mib2_ipIfStatsEntry_t));
10987 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10988 	    sizeof (mib2_ipv6AddrEntry_t));
10989 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10990 	    sizeof (mib2_ipv6RouteEntry_t));
10991 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10992 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10993 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10994 	    sizeof (ipv6_member_t));
10995 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10996 	    sizeof (ipv6_grpsrc_t));
10997 
10998 	/*
10999 	 * Synchronize 64- and 32-bit counters
11000 	 */
11001 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
11002 	    ipIfStatsHCInReceives);
11003 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
11004 	    ipIfStatsHCInDelivers);
11005 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
11006 	    ipIfStatsHCOutRequests);
11007 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
11008 	    ipIfStatsHCOutForwDatagrams);
11009 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
11010 	    ipIfStatsHCOutMcastPkts);
11011 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
11012 	    ipIfStatsHCInMcastPkts);
11013 
11014 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
11015 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
11016 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
11017 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
11018 	}
11019 
11020 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11021 	ill = ILL_START_WALK_V6(&ctx, ipst);
11022 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
11023 		ill->ill_ip_mib->ipIfStatsIfIndex =
11024 		    ill->ill_phyint->phyint_ifindex;
11025 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
11026 		    ipst->ips_ipv6_forward ? 1 : 2);
11027 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
11028 		    ill->ill_max_hops);
11029 
11030 		/*
11031 		 * Synchronize 64- and 32-bit counters
11032 		 */
11033 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
11034 		    ipIfStatsHCInReceives);
11035 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
11036 		    ipIfStatsHCInDelivers);
11037 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
11038 		    ipIfStatsHCOutRequests);
11039 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
11040 		    ipIfStatsHCOutForwDatagrams);
11041 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
11042 		    ipIfStatsHCOutMcastPkts);
11043 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
11044 		    ipIfStatsHCInMcastPkts);
11045 
11046 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
11047 		    (char *)ill->ill_ip_mib,
11048 		    (int)sizeof (*ill->ill_ip_mib))) {
11049 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
11050 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
11051 		}
11052 	}
11053 	rw_exit(&ipst->ips_ill_g_lock);
11054 
11055 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
11056 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
11057 	    (int)optp->level, (int)optp->name, (int)optp->len));
11058 	qreply(q, mpctl);
11059 	return (mp2ctl);
11060 }
11061 
11062 /*
11063  * ICMPv6 mib: One per ill
11064  */
11065 static mblk_t *
11066 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
11067 {
11068 	struct opthdr		*optp;
11069 	mblk_t			*mp2ctl;
11070 	ill_t			*ill;
11071 	ill_walk_context_t	ctx;
11072 	mblk_t			*mp_tail = NULL;
11073 	/*
11074 	 * Make a copy of the original message
11075 	 */
11076 	mp2ctl = copymsg(mpctl);
11077 
11078 	/* fixed length ICMPv6 structure ... */
11079 
11080 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
11081 	optp->level = MIB2_ICMP6;
11082 	optp->name = 0;
11083 	/* Include "unknown interface" icmp6_mib */
11084 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
11085 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
11086 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
11087 	    sizeof (mib2_ipv6IfIcmpEntry_t);
11088 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
11089 	    (char *)&ipst->ips_icmp6_mib,
11090 	    (int)sizeof (ipst->ips_icmp6_mib))) {
11091 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
11092 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
11093 	}
11094 
11095 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11096 	ill = ILL_START_WALK_V6(&ctx, ipst);
11097 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
11098 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
11099 		    ill->ill_phyint->phyint_ifindex;
11100 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
11101 		    (char *)ill->ill_icmp6_mib,
11102 		    (int)sizeof (*ill->ill_icmp6_mib))) {
11103 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
11104 			    "%u bytes\n",
11105 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
11106 		}
11107 	}
11108 	rw_exit(&ipst->ips_ill_g_lock);
11109 
11110 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
11111 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
11112 	    (int)optp->level, (int)optp->name, (int)optp->len));
11113 	qreply(q, mpctl);
11114 	return (mp2ctl);
11115 }
11116 
11117 /*
11118  * ire_walk routine to create both ipRouteEntryTable and
11119  * ipRouteAttributeTable in one IRE walk
11120  */
11121 static void
11122 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
11123 {
11124 	ill_t				*ill;
11125 	mib2_ipRouteEntry_t		*re;
11126 	mib2_ipAttributeEntry_t		iaes;
11127 	tsol_ire_gw_secattr_t		*attrp;
11128 	tsol_gc_t			*gc = NULL;
11129 	tsol_gcgrp_t			*gcgrp = NULL;
11130 	ip_stack_t			*ipst = ire->ire_ipst;
11131 
11132 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
11133 
11134 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11135 		if (ire->ire_testhidden)
11136 			return;
11137 		if (ire->ire_type & IRE_IF_CLONE)
11138 			return;
11139 	}
11140 
11141 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11142 		return;
11143 
11144 	if ((attrp = ire->ire_gw_secattr) != NULL) {
11145 		mutex_enter(&attrp->igsa_lock);
11146 		if ((gc = attrp->igsa_gc) != NULL) {
11147 			gcgrp = gc->gc_grp;
11148 			ASSERT(gcgrp != NULL);
11149 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11150 		}
11151 		mutex_exit(&attrp->igsa_lock);
11152 	}
11153 	/*
11154 	 * Return all IRE types for route table... let caller pick and choose
11155 	 */
11156 	re->ipRouteDest = ire->ire_addr;
11157 	ill = ire->ire_ill;
11158 	re->ipRouteIfIndex.o_length = 0;
11159 	if (ill != NULL) {
11160 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
11161 		re->ipRouteIfIndex.o_length =
11162 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
11163 	}
11164 	re->ipRouteMetric1 = -1;
11165 	re->ipRouteMetric2 = -1;
11166 	re->ipRouteMetric3 = -1;
11167 	re->ipRouteMetric4 = -1;
11168 
11169 	re->ipRouteNextHop = ire->ire_gateway_addr;
11170 	/* indirect(4), direct(3), or invalid(2) */
11171 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11172 		re->ipRouteType = 2;
11173 	else if (ire->ire_type & IRE_ONLINK)
11174 		re->ipRouteType = 3;
11175 	else
11176 		re->ipRouteType = 4;
11177 
11178 	re->ipRouteProto = -1;
11179 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
11180 	re->ipRouteMask = ire->ire_mask;
11181 	re->ipRouteMetric5 = -1;
11182 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11183 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
11184 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11185 
11186 	re->ipRouteInfo.re_frag_flag	= 0;
11187 	re->ipRouteInfo.re_rtt		= 0;
11188 	re->ipRouteInfo.re_src_addr	= 0;
11189 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
11190 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11191 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11192 	re->ipRouteInfo.re_flags	= ire->ire_flags;
11193 
11194 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11195 	if (ire->ire_type & IRE_INTERFACE) {
11196 		ire_t *child;
11197 
11198 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11199 		child = ire->ire_dep_children;
11200 		while (child != NULL) {
11201 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
11202 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11203 			child = child->ire_dep_sib_next;
11204 		}
11205 		rw_exit(&ipst->ips_ire_dep_lock);
11206 	}
11207 
11208 	if (ire->ire_flags & RTF_DYNAMIC) {
11209 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11210 	} else {
11211 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
11212 	}
11213 
11214 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11215 	    (char *)re, (int)sizeof (*re))) {
11216 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
11217 		    (uint_t)sizeof (*re)));
11218 	}
11219 
11220 	if (gc != NULL) {
11221 		iaes.iae_routeidx = ird->ird_idx;
11222 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11223 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11224 
11225 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11226 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11227 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
11228 			    "bytes\n", (uint_t)sizeof (iaes)));
11229 		}
11230 	}
11231 
11232 	/* bump route index for next pass */
11233 	ird->ird_idx++;
11234 
11235 	kmem_free(re, sizeof (*re));
11236 	if (gcgrp != NULL)
11237 		rw_exit(&gcgrp->gcgrp_rwlock);
11238 }
11239 
11240 /*
11241  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
11242  */
11243 static void
11244 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
11245 {
11246 	ill_t				*ill;
11247 	mib2_ipv6RouteEntry_t		*re;
11248 	mib2_ipAttributeEntry_t		iaes;
11249 	tsol_ire_gw_secattr_t		*attrp;
11250 	tsol_gc_t			*gc = NULL;
11251 	tsol_gcgrp_t			*gcgrp = NULL;
11252 	ip_stack_t			*ipst = ire->ire_ipst;
11253 
11254 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
11255 
11256 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11257 		if (ire->ire_testhidden)
11258 			return;
11259 		if (ire->ire_type & IRE_IF_CLONE)
11260 			return;
11261 	}
11262 
11263 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11264 		return;
11265 
11266 	if ((attrp = ire->ire_gw_secattr) != NULL) {
11267 		mutex_enter(&attrp->igsa_lock);
11268 		if ((gc = attrp->igsa_gc) != NULL) {
11269 			gcgrp = gc->gc_grp;
11270 			ASSERT(gcgrp != NULL);
11271 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11272 		}
11273 		mutex_exit(&attrp->igsa_lock);
11274 	}
11275 	/*
11276 	 * Return all IRE types for route table... let caller pick and choose
11277 	 */
11278 	re->ipv6RouteDest = ire->ire_addr_v6;
11279 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11280 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
11281 	re->ipv6RouteIfIndex.o_length = 0;
11282 	ill = ire->ire_ill;
11283 	if (ill != NULL) {
11284 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11285 		re->ipv6RouteIfIndex.o_length =
11286 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11287 	}
11288 
11289 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
11290 
11291 	mutex_enter(&ire->ire_lock);
11292 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11293 	mutex_exit(&ire->ire_lock);
11294 
11295 	/* remote(4), local(3), or discard(2) */
11296 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11297 		re->ipv6RouteType = 2;
11298 	else if (ire->ire_type & IRE_ONLINK)
11299 		re->ipv6RouteType = 3;
11300 	else
11301 		re->ipv6RouteType = 4;
11302 
11303 	re->ipv6RouteProtocol	= -1;
11304 	re->ipv6RoutePolicy	= 0;
11305 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
11306 	re->ipv6RouteNextHopRDI	= 0;
11307 	re->ipv6RouteWeight	= 0;
11308 	re->ipv6RouteMetric	= 0;
11309 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11310 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11311 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11312 
11313 	re->ipv6RouteInfo.re_frag_flag	= 0;
11314 	re->ipv6RouteInfo.re_rtt	= 0;
11315 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
11316 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11317 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11318 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
11319 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
11320 
11321 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11322 	if (ire->ire_type & IRE_INTERFACE) {
11323 		ire_t *child;
11324 
11325 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11326 		child = ire->ire_dep_children;
11327 		while (child != NULL) {
11328 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11329 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11330 			child = child->ire_dep_sib_next;
11331 		}
11332 		rw_exit(&ipst->ips_ire_dep_lock);
11333 	}
11334 	if (ire->ire_flags & RTF_DYNAMIC) {
11335 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11336 	} else {
11337 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
11338 	}
11339 
11340 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11341 	    (char *)re, (int)sizeof (*re))) {
11342 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11343 		    (uint_t)sizeof (*re)));
11344 	}
11345 
11346 	if (gc != NULL) {
11347 		iaes.iae_routeidx = ird->ird_idx;
11348 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11349 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11350 
11351 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11352 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11353 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11354 			    "bytes\n", (uint_t)sizeof (iaes)));
11355 		}
11356 	}
11357 
11358 	/* bump route index for next pass */
11359 	ird->ird_idx++;
11360 
11361 	kmem_free(re, sizeof (*re));
11362 	if (gcgrp != NULL)
11363 		rw_exit(&gcgrp->gcgrp_rwlock);
11364 }
11365 
11366 /*
11367  * ncec_walk routine to create ipv6NetToMediaEntryTable
11368  */
11369 static int
11370 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11371 {
11372 	ill_t				*ill;
11373 	mib2_ipv6NetToMediaEntry_t	ntme;
11374 
11375 	ill = ncec->ncec_ill;
11376 	/* skip arpce entries, and loopback ncec entries */
11377 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11378 		return (0);
11379 	/*
11380 	 * Neighbor cache entry attached to IRE with on-link
11381 	 * destination.
11382 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11383 	 */
11384 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11385 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11386 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11387 	if (ncec->ncec_lladdr != NULL) {
11388 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11389 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11390 	}
11391 	/*
11392 	 * Note: Returns ND_* states. Should be:
11393 	 * reachable(1), stale(2), delay(3), probe(4),
11394 	 * invalid(5), unknown(6)
11395 	 */
11396 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11397 	ntme.ipv6NetToMediaLastUpdated = 0;
11398 
11399 	/* other(1), dynamic(2), static(3), local(4) */
11400 	if (NCE_MYADDR(ncec)) {
11401 		ntme.ipv6NetToMediaType = 4;
11402 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11403 		ntme.ipv6NetToMediaType = 1; /* proxy */
11404 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11405 		ntme.ipv6NetToMediaType = 3;
11406 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11407 		ntme.ipv6NetToMediaType = 1;
11408 	} else {
11409 		ntme.ipv6NetToMediaType = 2;
11410 	}
11411 
11412 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11413 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11414 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11415 		    (uint_t)sizeof (ntme)));
11416 	}
11417 	return (0);
11418 }
11419 
11420 int
11421 nce2ace(ncec_t *ncec)
11422 {
11423 	int flags = 0;
11424 
11425 	if (NCE_ISREACHABLE(ncec))
11426 		flags |= ACE_F_RESOLVED;
11427 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11428 		flags |= ACE_F_AUTHORITY;
11429 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11430 		flags |= ACE_F_PUBLISH;
11431 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11432 		flags |= ACE_F_PERMANENT;
11433 	if (NCE_MYADDR(ncec))
11434 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11435 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11436 		flags |= ACE_F_UNVERIFIED;
11437 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11438 		flags |= ACE_F_AUTHORITY;
11439 	if (ncec->ncec_flags & NCE_F_DELAYED)
11440 		flags |= ACE_F_DELAYED;
11441 	return (flags);
11442 }
11443 
11444 /*
11445  * ncec_walk routine to create ipNetToMediaEntryTable
11446  */
11447 static int
11448 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11449 {
11450 	ill_t				*ill;
11451 	mib2_ipNetToMediaEntry_t	ntme;
11452 	const char			*name = "unknown";
11453 	ipaddr_t			ncec_addr;
11454 
11455 	ill = ncec->ncec_ill;
11456 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11457 	    ill->ill_net_type == IRE_LOOPBACK)
11458 		return (0);
11459 
11460 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11461 	name = ill->ill_name;
11462 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11463 	if (NCE_MYADDR(ncec)) {
11464 		ntme.ipNetToMediaType = 4;
11465 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11466 		ntme.ipNetToMediaType = 1;
11467 	} else {
11468 		ntme.ipNetToMediaType = 3;
11469 	}
11470 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11471 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11472 	    ntme.ipNetToMediaIfIndex.o_length);
11473 
11474 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11475 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11476 
11477 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11478 	ncec_addr = INADDR_BROADCAST;
11479 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11480 	    sizeof (ncec_addr));
11481 	/*
11482 	 * map all the flags to the ACE counterpart.
11483 	 */
11484 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11485 
11486 	ntme.ipNetToMediaPhysAddress.o_length =
11487 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11488 
11489 	if (!NCE_ISREACHABLE(ncec))
11490 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11491 	else {
11492 		if (ncec->ncec_lladdr != NULL) {
11493 			bcopy(ncec->ncec_lladdr,
11494 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11495 			    ntme.ipNetToMediaPhysAddress.o_length);
11496 		}
11497 	}
11498 
11499 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11500 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11501 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11502 		    (uint_t)sizeof (ntme)));
11503 	}
11504 	return (0);
11505 }
11506 
11507 /*
11508  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11509  */
11510 /* ARGSUSED */
11511 int
11512 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11513 {
11514 	switch (level) {
11515 	case MIB2_IP:
11516 	case MIB2_ICMP:
11517 		switch (name) {
11518 		default:
11519 			break;
11520 		}
11521 		return (1);
11522 	default:
11523 		return (1);
11524 	}
11525 }
11526 
11527 /*
11528  * When there exists both a 64- and 32-bit counter of a particular type
11529  * (i.e., InReceives), only the 64-bit counters are added.
11530  */
11531 void
11532 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11533 {
11534 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11535 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11536 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11537 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11538 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11539 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11540 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11541 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11542 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11543 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11544 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11545 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11546 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11547 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11548 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11549 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11550 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11551 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11552 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11553 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11554 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11555 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11556 	    o2->ipIfStatsInWrongIPVersion);
11557 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11558 	    o2->ipIfStatsInWrongIPVersion);
11559 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11560 	    o2->ipIfStatsOutSwitchIPVersion);
11561 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11562 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11563 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11564 	    o2->ipIfStatsHCInForwDatagrams);
11565 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11566 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11567 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11568 	    o2->ipIfStatsHCOutForwDatagrams);
11569 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11570 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11571 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11572 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11573 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11574 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11575 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11576 	    o2->ipIfStatsHCOutMcastOctets);
11577 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11578 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11579 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11580 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11581 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11582 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11583 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11584 }
11585 
11586 void
11587 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11588 {
11589 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11590 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11591 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11592 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11593 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11594 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11595 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11596 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11597 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11598 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11599 	    o2->ipv6IfIcmpInRouterSolicits);
11600 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11601 	    o2->ipv6IfIcmpInRouterAdvertisements);
11602 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11603 	    o2->ipv6IfIcmpInNeighborSolicits);
11604 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11605 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11606 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11607 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11608 	    o2->ipv6IfIcmpInGroupMembQueries);
11609 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11610 	    o2->ipv6IfIcmpInGroupMembResponses);
11611 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11612 	    o2->ipv6IfIcmpInGroupMembReductions);
11613 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11614 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11615 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11616 	    o2->ipv6IfIcmpOutDestUnreachs);
11617 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11618 	    o2->ipv6IfIcmpOutAdminProhibs);
11619 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11620 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11621 	    o2->ipv6IfIcmpOutParmProblems);
11622 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11623 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11624 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11625 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11626 	    o2->ipv6IfIcmpOutRouterSolicits);
11627 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11628 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11629 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11630 	    o2->ipv6IfIcmpOutNeighborSolicits);
11631 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11632 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11633 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11634 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11635 	    o2->ipv6IfIcmpOutGroupMembQueries);
11636 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11637 	    o2->ipv6IfIcmpOutGroupMembResponses);
11638 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11639 	    o2->ipv6IfIcmpOutGroupMembReductions);
11640 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11641 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11642 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11643 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11644 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11645 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11646 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11647 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11648 	    o2->ipv6IfIcmpInGroupMembTotal);
11649 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11650 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11651 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11652 	    o2->ipv6IfIcmpInGroupMembBadReports);
11653 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11654 	    o2->ipv6IfIcmpInGroupMembOurReports);
11655 }
11656 
11657 /*
11658  * Called before the options are updated to check if this packet will
11659  * be source routed from here.
11660  * This routine assumes that the options are well formed i.e. that they
11661  * have already been checked.
11662  */
11663 boolean_t
11664 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11665 {
11666 	ipoptp_t	opts;
11667 	uchar_t		*opt;
11668 	uint8_t		optval;
11669 	uint8_t		optlen;
11670 	ipaddr_t	dst;
11671 
11672 	if (IS_SIMPLE_IPH(ipha)) {
11673 		ip2dbg(("not source routed\n"));
11674 		return (B_FALSE);
11675 	}
11676 	dst = ipha->ipha_dst;
11677 	for (optval = ipoptp_first(&opts, ipha);
11678 	    optval != IPOPT_EOL;
11679 	    optval = ipoptp_next(&opts)) {
11680 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11681 		opt = opts.ipoptp_cur;
11682 		optlen = opts.ipoptp_len;
11683 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11684 		    optval, optlen));
11685 		switch (optval) {
11686 			uint32_t off;
11687 		case IPOPT_SSRR:
11688 		case IPOPT_LSRR:
11689 			/*
11690 			 * If dst is one of our addresses and there are some
11691 			 * entries left in the source route return (true).
11692 			 */
11693 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11694 				ip2dbg(("ip_source_routed: not next"
11695 				    " source route 0x%x\n",
11696 				    ntohl(dst)));
11697 				return (B_FALSE);
11698 			}
11699 			off = opt[IPOPT_OFFSET];
11700 			off--;
11701 			if (optlen < IP_ADDR_LEN ||
11702 			    off > optlen - IP_ADDR_LEN) {
11703 				/* End of source route */
11704 				ip1dbg(("ip_source_routed: end of SR\n"));
11705 				return (B_FALSE);
11706 			}
11707 			return (B_TRUE);
11708 		}
11709 	}
11710 	ip2dbg(("not source routed\n"));
11711 	return (B_FALSE);
11712 }
11713 
11714 /*
11715  * ip_unbind is called by the transports to remove a conn from
11716  * the fanout table.
11717  */
11718 void
11719 ip_unbind(conn_t *connp)
11720 {
11721 
11722 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11723 
11724 	if (is_system_labeled() && connp->conn_anon_port) {
11725 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11726 		    connp->conn_mlp_type, connp->conn_proto,
11727 		    ntohs(connp->conn_lport), B_FALSE);
11728 		connp->conn_anon_port = 0;
11729 	}
11730 	connp->conn_mlp_type = mlptSingle;
11731 
11732 	ipcl_hash_remove(connp);
11733 }
11734 
11735 /*
11736  * Used for deciding the MSS size for the upper layer. Thus
11737  * we need to check the outbound policy values in the conn.
11738  */
11739 int
11740 conn_ipsec_length(conn_t *connp)
11741 {
11742 	ipsec_latch_t *ipl;
11743 
11744 	ipl = connp->conn_latch;
11745 	if (ipl == NULL)
11746 		return (0);
11747 
11748 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11749 		return (0);
11750 
11751 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11752 }
11753 
11754 /*
11755  * Returns an estimate of the IPsec headers size. This is used if
11756  * we don't want to call into IPsec to get the exact size.
11757  */
11758 int
11759 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11760 {
11761 	ipsec_action_t *a;
11762 
11763 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11764 		return (0);
11765 
11766 	a = ixa->ixa_ipsec_action;
11767 	if (a == NULL) {
11768 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11769 		a = ixa->ixa_ipsec_policy->ipsp_act;
11770 	}
11771 	ASSERT(a != NULL);
11772 
11773 	return (a->ipa_ovhd);
11774 }
11775 
11776 /*
11777  * If there are any source route options, return the true final
11778  * destination. Otherwise, return the destination.
11779  */
11780 ipaddr_t
11781 ip_get_dst(ipha_t *ipha)
11782 {
11783 	ipoptp_t	opts;
11784 	uchar_t		*opt;
11785 	uint8_t		optval;
11786 	uint8_t		optlen;
11787 	ipaddr_t	dst;
11788 	uint32_t off;
11789 
11790 	dst = ipha->ipha_dst;
11791 
11792 	if (IS_SIMPLE_IPH(ipha))
11793 		return (dst);
11794 
11795 	for (optval = ipoptp_first(&opts, ipha);
11796 	    optval != IPOPT_EOL;
11797 	    optval = ipoptp_next(&opts)) {
11798 		opt = opts.ipoptp_cur;
11799 		optlen = opts.ipoptp_len;
11800 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11801 		switch (optval) {
11802 		case IPOPT_SSRR:
11803 		case IPOPT_LSRR:
11804 			off = opt[IPOPT_OFFSET];
11805 			/*
11806 			 * If one of the conditions is true, it means
11807 			 * end of options and dst already has the right
11808 			 * value.
11809 			 */
11810 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11811 				off = optlen - IP_ADDR_LEN;
11812 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11813 			}
11814 			return (dst);
11815 		default:
11816 			break;
11817 		}
11818 	}
11819 
11820 	return (dst);
11821 }
11822 
11823 /*
11824  * Outbound IP fragmentation routine.
11825  * Assumes the caller has checked whether or not fragmentation should
11826  * be allowed. Here we copy the DF bit from the header to all the generated
11827  * fragments.
11828  */
11829 int
11830 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11831     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11832     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11833 {
11834 	int		i1;
11835 	int		hdr_len;
11836 	mblk_t		*hdr_mp;
11837 	ipha_t		*ipha;
11838 	int		ip_data_end;
11839 	int		len;
11840 	mblk_t		*mp = mp_orig;
11841 	int		offset;
11842 	ill_t		*ill = nce->nce_ill;
11843 	ip_stack_t	*ipst = ill->ill_ipst;
11844 	mblk_t		*carve_mp;
11845 	uint32_t	frag_flag;
11846 	uint_t		priority = mp->b_band;
11847 	int		error = 0;
11848 
11849 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11850 
11851 	if (pkt_len != msgdsize(mp)) {
11852 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11853 		    pkt_len, msgdsize(mp)));
11854 		freemsg(mp);
11855 		return (EINVAL);
11856 	}
11857 
11858 	if (max_frag == 0) {
11859 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11860 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11861 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11862 		freemsg(mp);
11863 		return (EINVAL);
11864 	}
11865 
11866 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11867 	ipha = (ipha_t *)mp->b_rptr;
11868 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11869 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11870 
11871 	/*
11872 	 * Establish the starting offset.  May not be zero if we are fragging
11873 	 * a fragment that is being forwarded.
11874 	 */
11875 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11876 
11877 	/* TODO why is this test needed? */
11878 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11879 		/* TODO: notify ulp somehow */
11880 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11881 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11882 		freemsg(mp);
11883 		return (EINVAL);
11884 	}
11885 
11886 	hdr_len = IPH_HDR_LENGTH(ipha);
11887 	ipha->ipha_hdr_checksum = 0;
11888 
11889 	/*
11890 	 * Establish the number of bytes maximum per frag, after putting
11891 	 * in the header.
11892 	 */
11893 	len = (max_frag - hdr_len) & ~7;
11894 
11895 	/* Get a copy of the header for the trailing frags */
11896 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11897 	    mp);
11898 	if (hdr_mp == NULL) {
11899 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11900 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11901 		freemsg(mp);
11902 		return (ENOBUFS);
11903 	}
11904 
11905 	/* Store the starting offset, with the MoreFrags flag. */
11906 	i1 = offset | IPH_MF | frag_flag;
11907 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11908 
11909 	/* Establish the ending byte offset, based on the starting offset. */
11910 	offset <<= 3;
11911 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11912 
11913 	/* Store the length of the first fragment in the IP header. */
11914 	i1 = len + hdr_len;
11915 	ASSERT(i1 <= IP_MAXPACKET);
11916 	ipha->ipha_length = htons((uint16_t)i1);
11917 
11918 	/*
11919 	 * Compute the IP header checksum for the first frag.  We have to
11920 	 * watch out that we stop at the end of the header.
11921 	 */
11922 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11923 
11924 	/*
11925 	 * Now carve off the first frag.  Note that this will include the
11926 	 * original IP header.
11927 	 */
11928 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11929 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11930 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11931 		freeb(hdr_mp);
11932 		freemsg(mp_orig);
11933 		return (ENOBUFS);
11934 	}
11935 
11936 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11937 
11938 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11939 	    ixa_cookie);
11940 	if (error != 0 && error != EWOULDBLOCK) {
11941 		/* No point in sending the other fragments */
11942 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11943 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11944 		freeb(hdr_mp);
11945 		freemsg(mp_orig);
11946 		return (error);
11947 	}
11948 
11949 	/* No need to redo state machine in loop */
11950 	ixaflags &= ~IXAF_REACH_CONF;
11951 
11952 	/* Advance the offset to the second frag starting point. */
11953 	offset += len;
11954 	/*
11955 	 * Update hdr_len from the copied header - there might be less options
11956 	 * in the later fragments.
11957 	 */
11958 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11959 	/* Loop until done. */
11960 	for (;;) {
11961 		uint16_t	offset_and_flags;
11962 		uint16_t	ip_len;
11963 
11964 		if (ip_data_end - offset > len) {
11965 			/*
11966 			 * Carve off the appropriate amount from the original
11967 			 * datagram.
11968 			 */
11969 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11970 				mp = NULL;
11971 				break;
11972 			}
11973 			/*
11974 			 * More frags after this one.  Get another copy
11975 			 * of the header.
11976 			 */
11977 			if (carve_mp->b_datap->db_ref == 1 &&
11978 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11979 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11980 				/* Inline IP header */
11981 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11982 				    hdr_mp->b_rptr;
11983 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11984 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11985 				mp = carve_mp;
11986 			} else {
11987 				if (!(mp = copyb(hdr_mp))) {
11988 					freemsg(carve_mp);
11989 					break;
11990 				}
11991 				/* Get priority marking, if any. */
11992 				mp->b_band = priority;
11993 				mp->b_cont = carve_mp;
11994 			}
11995 			ipha = (ipha_t *)mp->b_rptr;
11996 			offset_and_flags = IPH_MF;
11997 		} else {
11998 			/*
11999 			 * Last frag.  Consume the header. Set len to
12000 			 * the length of this last piece.
12001 			 */
12002 			len = ip_data_end - offset;
12003 
12004 			/*
12005 			 * Carve off the appropriate amount from the original
12006 			 * datagram.
12007 			 */
12008 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
12009 				mp = NULL;
12010 				break;
12011 			}
12012 			if (carve_mp->b_datap->db_ref == 1 &&
12013 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
12014 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
12015 				/* Inline IP header */
12016 				carve_mp->b_rptr -= hdr_mp->b_wptr -
12017 				    hdr_mp->b_rptr;
12018 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
12019 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
12020 				mp = carve_mp;
12021 				freeb(hdr_mp);
12022 				hdr_mp = mp;
12023 			} else {
12024 				mp = hdr_mp;
12025 				/* Get priority marking, if any. */
12026 				mp->b_band = priority;
12027 				mp->b_cont = carve_mp;
12028 			}
12029 			ipha = (ipha_t *)mp->b_rptr;
12030 			/* A frag of a frag might have IPH_MF non-zero */
12031 			offset_and_flags =
12032 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
12033 			    IPH_MF;
12034 		}
12035 		offset_and_flags |= (uint16_t)(offset >> 3);
12036 		offset_and_flags |= (uint16_t)frag_flag;
12037 		/* Store the offset and flags in the IP header. */
12038 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
12039 
12040 		/* Store the length in the IP header. */
12041 		ip_len = (uint16_t)(len + hdr_len);
12042 		ipha->ipha_length = htons(ip_len);
12043 
12044 		/*
12045 		 * Set the IP header checksum.	Note that mp is just
12046 		 * the header, so this is easy to pass to ip_csum.
12047 		 */
12048 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
12049 
12050 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
12051 
12052 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
12053 		    nolzid, ixa_cookie);
12054 		/* All done if we just consumed the hdr_mp. */
12055 		if (mp == hdr_mp) {
12056 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
12057 			return (error);
12058 		}
12059 		if (error != 0 && error != EWOULDBLOCK) {
12060 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
12061 			    mblk_t *, hdr_mp);
12062 			/* No point in sending the other fragments */
12063 			break;
12064 		}
12065 
12066 		/* Otherwise, advance and loop. */
12067 		offset += len;
12068 	}
12069 	/* Clean up following allocation failure. */
12070 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
12071 	ip_drop_output("FragFails: loop ended", NULL, ill);
12072 	if (mp != hdr_mp)
12073 		freeb(hdr_mp);
12074 	if (mp != mp_orig)
12075 		freemsg(mp_orig);
12076 	return (error);
12077 }
12078 
12079 /*
12080  * Copy the header plus those options which have the copy bit set
12081  */
12082 static mblk_t *
12083 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
12084     mblk_t *src)
12085 {
12086 	mblk_t	*mp;
12087 	uchar_t	*up;
12088 
12089 	/*
12090 	 * Quick check if we need to look for options without the copy bit
12091 	 * set
12092 	 */
12093 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
12094 	if (!mp)
12095 		return (mp);
12096 	mp->b_rptr += ipst->ips_ip_wroff_extra;
12097 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
12098 		bcopy(rptr, mp->b_rptr, hdr_len);
12099 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
12100 		return (mp);
12101 	}
12102 	up  = mp->b_rptr;
12103 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
12104 	up += IP_SIMPLE_HDR_LENGTH;
12105 	rptr += IP_SIMPLE_HDR_LENGTH;
12106 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
12107 	while (hdr_len > 0) {
12108 		uint32_t optval;
12109 		uint32_t optlen;
12110 
12111 		optval = *rptr;
12112 		if (optval == IPOPT_EOL)
12113 			break;
12114 		if (optval == IPOPT_NOP)
12115 			optlen = 1;
12116 		else
12117 			optlen = rptr[1];
12118 		if (optval & IPOPT_COPY) {
12119 			bcopy(rptr, up, optlen);
12120 			up += optlen;
12121 		}
12122 		rptr += optlen;
12123 		hdr_len -= optlen;
12124 	}
12125 	/*
12126 	 * Make sure that we drop an even number of words by filling
12127 	 * with EOL to the next word boundary.
12128 	 */
12129 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
12130 	    hdr_len & 0x3; hdr_len++)
12131 		*up++ = IPOPT_EOL;
12132 	mp->b_wptr = up;
12133 	/* Update header length */
12134 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
12135 	return (mp);
12136 }
12137 
12138 /*
12139  * Update any source route, record route, or timestamp options when
12140  * sending a packet back to ourselves.
12141  * Check that we are at end of strict source route.
12142  * The options have been sanity checked by ip_output_options().
12143  */
12144 void
12145 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
12146 {
12147 	ipoptp_t	opts;
12148 	uchar_t		*opt;
12149 	uint8_t		optval;
12150 	uint8_t		optlen;
12151 	ipaddr_t	dst;
12152 	uint32_t	ts;
12153 	timestruc_t	now;
12154 
12155 	for (optval = ipoptp_first(&opts, ipha);
12156 	    optval != IPOPT_EOL;
12157 	    optval = ipoptp_next(&opts)) {
12158 		opt = opts.ipoptp_cur;
12159 		optlen = opts.ipoptp_len;
12160 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
12161 		switch (optval) {
12162 			uint32_t off;
12163 		case IPOPT_SSRR:
12164 		case IPOPT_LSRR:
12165 			off = opt[IPOPT_OFFSET];
12166 			off--;
12167 			if (optlen < IP_ADDR_LEN ||
12168 			    off > optlen - IP_ADDR_LEN) {
12169 				/* End of source route */
12170 				break;
12171 			}
12172 			/*
12173 			 * This will only happen if two consecutive entries
12174 			 * in the source route contains our address or if
12175 			 * it is a packet with a loose source route which
12176 			 * reaches us before consuming the whole source route
12177 			 */
12178 
12179 			if (optval == IPOPT_SSRR) {
12180 				return;
12181 			}
12182 			/*
12183 			 * Hack: instead of dropping the packet truncate the
12184 			 * source route to what has been used by filling the
12185 			 * rest with IPOPT_NOP.
12186 			 */
12187 			opt[IPOPT_OLEN] = (uint8_t)off;
12188 			while (off < optlen) {
12189 				opt[off++] = IPOPT_NOP;
12190 			}
12191 			break;
12192 		case IPOPT_RR:
12193 			off = opt[IPOPT_OFFSET];
12194 			off--;
12195 			if (optlen < IP_ADDR_LEN ||
12196 			    off > optlen - IP_ADDR_LEN) {
12197 				/* No more room - ignore */
12198 				ip1dbg((
12199 				    "ip_output_local_options: end of RR\n"));
12200 				break;
12201 			}
12202 			dst = htonl(INADDR_LOOPBACK);
12203 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12204 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12205 			break;
12206 		case IPOPT_TS:
12207 			/* Insert timestamp if there is romm */
12208 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12209 			case IPOPT_TS_TSONLY:
12210 				off = IPOPT_TS_TIMELEN;
12211 				break;
12212 			case IPOPT_TS_PRESPEC:
12213 			case IPOPT_TS_PRESPEC_RFC791:
12214 				/* Verify that the address matched */
12215 				off = opt[IPOPT_OFFSET] - 1;
12216 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
12217 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
12218 					/* Not for us */
12219 					break;
12220 				}
12221 				/* FALLTHRU */
12222 			case IPOPT_TS_TSANDADDR:
12223 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12224 				break;
12225 			default:
12226 				/*
12227 				 * ip_*put_options should have already
12228 				 * dropped this packet.
12229 				 */
12230 				cmn_err(CE_PANIC, "ip_output_local_options: "
12231 				    "unknown IT - bug in ip_output_options?\n");
12232 				return;	/* Keep "lint" happy */
12233 			}
12234 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
12235 				/* Increase overflow counter */
12236 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
12237 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
12238 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
12239 				    (off << 4);
12240 				break;
12241 			}
12242 			off = opt[IPOPT_OFFSET] - 1;
12243 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12244 			case IPOPT_TS_PRESPEC:
12245 			case IPOPT_TS_PRESPEC_RFC791:
12246 			case IPOPT_TS_TSANDADDR:
12247 				dst = htonl(INADDR_LOOPBACK);
12248 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12249 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12250 				/* FALLTHRU */
12251 			case IPOPT_TS_TSONLY:
12252 				off = opt[IPOPT_OFFSET] - 1;
12253 				/* Compute # of milliseconds since midnight */
12254 				gethrestime(&now);
12255 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
12256 				    now.tv_nsec / (NANOSEC / MILLISEC);
12257 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
12258 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
12259 				break;
12260 			}
12261 			break;
12262 		}
12263 	}
12264 }
12265 
12266 /*
12267  * Prepend an M_DATA fastpath header, and if none present prepend a
12268  * DL_UNITDATA_REQ. Frees the mblk on failure.
12269  *
12270  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12271  * If there is a change to them, the nce will be deleted (condemned) and
12272  * a new nce_t will be created when packets are sent. Thus we need no locks
12273  * to access those fields.
12274  *
12275  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12276  * we place b_band in dl_priority.dl_max.
12277  */
12278 static mblk_t *
12279 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12280 {
12281 	uint_t	hlen;
12282 	mblk_t *mp1;
12283 	uint_t	priority;
12284 	uchar_t *rptr;
12285 
12286 	rptr = mp->b_rptr;
12287 
12288 	ASSERT(DB_TYPE(mp) == M_DATA);
12289 	priority = mp->b_band;
12290 
12291 	ASSERT(nce != NULL);
12292 	if ((mp1 = nce->nce_fp_mp) != NULL) {
12293 		hlen = MBLKL(mp1);
12294 		/*
12295 		 * Check if we have enough room to prepend fastpath
12296 		 * header
12297 		 */
12298 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12299 			rptr -= hlen;
12300 			bcopy(mp1->b_rptr, rptr, hlen);
12301 			/*
12302 			 * Set the b_rptr to the start of the link layer
12303 			 * header
12304 			 */
12305 			mp->b_rptr = rptr;
12306 			return (mp);
12307 		}
12308 		mp1 = copyb(mp1);
12309 		if (mp1 == NULL) {
12310 			ill_t *ill = nce->nce_ill;
12311 
12312 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12313 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12314 			freemsg(mp);
12315 			return (NULL);
12316 		}
12317 		mp1->b_band = priority;
12318 		mp1->b_cont = mp;
12319 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12320 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12321 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12322 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12323 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12324 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12325 		/*
12326 		 * XXX disable ICK_VALID and compute checksum
12327 		 * here; can happen if nce_fp_mp changes and
12328 		 * it can't be copied now due to insufficient
12329 		 * space. (unlikely, fp mp can change, but it
12330 		 * does not increase in length)
12331 		 */
12332 		return (mp1);
12333 	}
12334 	mp1 = copyb(nce->nce_dlur_mp);
12335 
12336 	if (mp1 == NULL) {
12337 		ill_t *ill = nce->nce_ill;
12338 
12339 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12340 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12341 		freemsg(mp);
12342 		return (NULL);
12343 	}
12344 	mp1->b_cont = mp;
12345 	if (priority != 0) {
12346 		mp1->b_band = priority;
12347 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12348 		    priority;
12349 	}
12350 	return (mp1);
12351 #undef rptr
12352 }
12353 
12354 /*
12355  * Finish the outbound IPsec processing. This function is called from
12356  * ipsec_out_process() if the IPsec packet was processed
12357  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12358  * asynchronously.
12359  *
12360  * This is common to IPv4 and IPv6.
12361  */
12362 int
12363 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12364 {
12365 	iaflags_t	ixaflags = ixa->ixa_flags;
12366 	uint_t		pktlen;
12367 
12368 
12369 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12370 	if (ixaflags & IXAF_IS_IPV4) {
12371 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12372 
12373 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12374 		pktlen = ntohs(ipha->ipha_length);
12375 	} else {
12376 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12377 
12378 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12379 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12380 	}
12381 
12382 	/*
12383 	 * We release any hard reference on the SAs here to make
12384 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12385 	 * on the SAs.
12386 	 * If in the future we want the hard latching of the SAs in the
12387 	 * ip_xmit_attr_t then we should remove this.
12388 	 */
12389 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12390 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12391 		ixa->ixa_ipsec_esp_sa = NULL;
12392 	}
12393 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12394 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12395 		ixa->ixa_ipsec_ah_sa = NULL;
12396 	}
12397 
12398 	/* Do we need to fragment? */
12399 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12400 	    pktlen > ixa->ixa_fragsize) {
12401 		if (ixaflags & IXAF_IS_IPV4) {
12402 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12403 			/*
12404 			 * We check for the DF case in ipsec_out_process
12405 			 * hence this only handles the non-DF case.
12406 			 */
12407 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12408 			    pktlen, ixa->ixa_fragsize,
12409 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12410 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12411 			    &ixa->ixa_cookie));
12412 		} else {
12413 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12414 			if (mp == NULL) {
12415 				/* MIB and ip_drop_output already done */
12416 				return (ENOMEM);
12417 			}
12418 			pktlen += sizeof (ip6_frag_t);
12419 			if (pktlen > ixa->ixa_fragsize) {
12420 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12421 				    ixa->ixa_flags, pktlen,
12422 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12423 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12424 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12425 			}
12426 		}
12427 	}
12428 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12429 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12430 	    ixa->ixa_no_loop_zoneid, NULL));
12431 }
12432 
12433 /*
12434  * Finish the inbound IPsec processing. This function is called from
12435  * ipsec_out_process() if the IPsec packet was processed
12436  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12437  * asynchronously.
12438  *
12439  * This is common to IPv4 and IPv6.
12440  */
12441 void
12442 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12443 {
12444 	iaflags_t	iraflags = ira->ira_flags;
12445 
12446 	/* Length might have changed */
12447 	if (iraflags & IRAF_IS_IPV4) {
12448 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12449 
12450 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12451 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12452 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12453 		ira->ira_protocol = ipha->ipha_protocol;
12454 
12455 		ip_fanout_v4(mp, ipha, ira);
12456 	} else {
12457 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12458 		uint8_t		*nexthdrp;
12459 
12460 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12461 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12462 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12463 		    &nexthdrp)) {
12464 			/* Malformed packet */
12465 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12466 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12467 			freemsg(mp);
12468 			return;
12469 		}
12470 		ira->ira_protocol = *nexthdrp;
12471 		ip_fanout_v6(mp, ip6h, ira);
12472 	}
12473 }
12474 
12475 /*
12476  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12477  *
12478  * If this function returns B_TRUE, the requested SA's have been filled
12479  * into the ixa_ipsec_*_sa pointers.
12480  *
12481  * If the function returns B_FALSE, the packet has been "consumed", most
12482  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12483  *
12484  * The SA references created by the protocol-specific "select"
12485  * function will be released in ip_output_post_ipsec.
12486  */
12487 static boolean_t
12488 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12489 {
12490 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12491 	ipsec_policy_t *pp;
12492 	ipsec_action_t *ap;
12493 
12494 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12495 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12496 	    (ixa->ixa_ipsec_action != NULL));
12497 
12498 	ap = ixa->ixa_ipsec_action;
12499 	if (ap == NULL) {
12500 		pp = ixa->ixa_ipsec_policy;
12501 		ASSERT(pp != NULL);
12502 		ap = pp->ipsp_act;
12503 		ASSERT(ap != NULL);
12504 	}
12505 
12506 	/*
12507 	 * We have an action.  now, let's select SA's.
12508 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12509 	 * be cached in the conn_t.
12510 	 */
12511 	if (ap->ipa_want_esp) {
12512 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12513 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12514 			    IPPROTO_ESP);
12515 		}
12516 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12517 	}
12518 
12519 	if (ap->ipa_want_ah) {
12520 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12521 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12522 			    IPPROTO_AH);
12523 		}
12524 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12525 		/*
12526 		 * The ESP and AH processing order needs to be preserved
12527 		 * when both protocols are required (ESP should be applied
12528 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12529 		 * when both ESP and AH are required, and an AH ACQUIRE
12530 		 * is needed.
12531 		 */
12532 		if (ap->ipa_want_esp && need_ah_acquire)
12533 			need_esp_acquire = B_TRUE;
12534 	}
12535 
12536 	/*
12537 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12538 	 * Release SAs that got referenced, but will not be used until we
12539 	 * acquire _all_ of the SAs we need.
12540 	 */
12541 	if (need_ah_acquire || need_esp_acquire) {
12542 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12543 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12544 			ixa->ixa_ipsec_ah_sa = NULL;
12545 		}
12546 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12547 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12548 			ixa->ixa_ipsec_esp_sa = NULL;
12549 		}
12550 
12551 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12552 		return (B_FALSE);
12553 	}
12554 
12555 	return (B_TRUE);
12556 }
12557 
12558 /*
12559  * Handle IPsec output processing.
12560  * This function is only entered once for a given packet.
12561  * We try to do things synchronously, but if we need to have user-level
12562  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12563  * will be completed
12564  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12565  *  - when asynchronous ESP is done it will do AH
12566  *
12567  * In all cases we come back in ip_output_post_ipsec() to fragment and
12568  * send out the packet.
12569  */
12570 int
12571 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12572 {
12573 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12574 	ip_stack_t	*ipst = ixa->ixa_ipst;
12575 	ipsec_stack_t	*ipss;
12576 	ipsec_policy_t	*pp;
12577 	ipsec_action_t	*ap;
12578 
12579 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12580 
12581 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12582 	    (ixa->ixa_ipsec_action != NULL));
12583 
12584 	ipss = ipst->ips_netstack->netstack_ipsec;
12585 	if (!ipsec_loaded(ipss)) {
12586 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12587 		ip_drop_packet(mp, B_TRUE, ill,
12588 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12589 		    &ipss->ipsec_dropper);
12590 		return (ENOTSUP);
12591 	}
12592 
12593 	ap = ixa->ixa_ipsec_action;
12594 	if (ap == NULL) {
12595 		pp = ixa->ixa_ipsec_policy;
12596 		ASSERT(pp != NULL);
12597 		ap = pp->ipsp_act;
12598 		ASSERT(ap != NULL);
12599 	}
12600 
12601 	/* Handle explicit drop action and bypass. */
12602 	switch (ap->ipa_act.ipa_type) {
12603 	case IPSEC_ACT_DISCARD:
12604 	case IPSEC_ACT_REJECT:
12605 		ip_drop_packet(mp, B_FALSE, ill,
12606 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12607 		return (EHOSTUNREACH);	/* IPsec policy failure */
12608 	case IPSEC_ACT_BYPASS:
12609 		return (ip_output_post_ipsec(mp, ixa));
12610 	}
12611 
12612 	/*
12613 	 * The order of processing is first insert a IP header if needed.
12614 	 * Then insert the ESP header and then the AH header.
12615 	 */
12616 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12617 		/*
12618 		 * First get the outer IP header before sending
12619 		 * it to ESP.
12620 		 */
12621 		ipha_t *oipha, *iipha;
12622 		mblk_t *outer_mp, *inner_mp;
12623 
12624 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12625 			(void) mi_strlog(ill->ill_rq, 0,
12626 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12627 			    "ipsec_out_process: "
12628 			    "Self-Encapsulation failed: Out of memory\n");
12629 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12630 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12631 			freemsg(mp);
12632 			return (ENOBUFS);
12633 		}
12634 		inner_mp = mp;
12635 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12636 		oipha = (ipha_t *)outer_mp->b_rptr;
12637 		iipha = (ipha_t *)inner_mp->b_rptr;
12638 		*oipha = *iipha;
12639 		outer_mp->b_wptr += sizeof (ipha_t);
12640 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12641 		    sizeof (ipha_t));
12642 		oipha->ipha_protocol = IPPROTO_ENCAP;
12643 		oipha->ipha_version_and_hdr_length =
12644 		    IP_SIMPLE_HDR_VERSION;
12645 		oipha->ipha_hdr_checksum = 0;
12646 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12647 		outer_mp->b_cont = inner_mp;
12648 		mp = outer_mp;
12649 
12650 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12651 	}
12652 
12653 	/* If we need to wait for a SA then we can't return any errno */
12654 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12655 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12656 	    !ipsec_out_select_sa(mp, ixa))
12657 		return (0);
12658 
12659 	/*
12660 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12661 	 * to do the heavy lifting.
12662 	 */
12663 	if (ap->ipa_want_esp) {
12664 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12665 
12666 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12667 		if (mp == NULL) {
12668 			/*
12669 			 * Either it failed or is pending. In the former case
12670 			 * ipIfStatsInDiscards was increased.
12671 			 */
12672 			return (0);
12673 		}
12674 	}
12675 
12676 	if (ap->ipa_want_ah) {
12677 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12678 
12679 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12680 		if (mp == NULL) {
12681 			/*
12682 			 * Either it failed or is pending. In the former case
12683 			 * ipIfStatsInDiscards was increased.
12684 			 */
12685 			return (0);
12686 		}
12687 	}
12688 	/*
12689 	 * We are done with IPsec processing. Send it over
12690 	 * the wire.
12691 	 */
12692 	return (ip_output_post_ipsec(mp, ixa));
12693 }
12694 
12695 /*
12696  * ioctls that go through a down/up sequence may need to wait for the down
12697  * to complete. This involves waiting for the ire and ipif refcnts to go down
12698  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12699  */
12700 /* ARGSUSED */
12701 void
12702 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12703 {
12704 	struct iocblk *iocp;
12705 	mblk_t *mp1;
12706 	ip_ioctl_cmd_t *ipip;
12707 	int err;
12708 	sin_t	*sin;
12709 	struct lifreq *lifr;
12710 	struct ifreq *ifr;
12711 
12712 	iocp = (struct iocblk *)mp->b_rptr;
12713 	ASSERT(ipsq != NULL);
12714 	/* Existence of mp1 verified in ip_wput_nondata */
12715 	mp1 = mp->b_cont->b_cont;
12716 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12717 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12718 		/*
12719 		 * Special case where ipx_current_ipif is not set:
12720 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12721 		 * We are here as were not able to complete the operation in
12722 		 * ipif_set_values because we could not become exclusive on
12723 		 * the new ipsq.
12724 		 */
12725 		ill_t *ill = q->q_ptr;
12726 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12727 	}
12728 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12729 
12730 	if (ipip->ipi_cmd_type == IF_CMD) {
12731 		/* This a old style SIOC[GS]IF* command */
12732 		ifr = (struct ifreq *)mp1->b_rptr;
12733 		sin = (sin_t *)&ifr->ifr_addr;
12734 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12735 		/* This a new style SIOC[GS]LIF* command */
12736 		lifr = (struct lifreq *)mp1->b_rptr;
12737 		sin = (sin_t *)&lifr->lifr_addr;
12738 	} else {
12739 		sin = NULL;
12740 	}
12741 
12742 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12743 	    q, mp, ipip, mp1->b_rptr);
12744 
12745 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12746 	    int, ipip->ipi_cmd,
12747 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12748 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12749 
12750 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12751 }
12752 
12753 /*
12754  * ioctl processing
12755  *
12756  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12757  * the ioctl command in the ioctl tables, determines the copyin data size
12758  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12759  *
12760  * ioctl processing then continues when the M_IOCDATA makes its way down to
12761  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12762  * associated 'conn' is refheld till the end of the ioctl and the general
12763  * ioctl processing function ip_process_ioctl() is called to extract the
12764  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12765  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12766  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12767  * is used to extract the ioctl's arguments.
12768  *
12769  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12770  * so goes thru the serialization primitive ipsq_try_enter. Then the
12771  * appropriate function to handle the ioctl is called based on the entry in
12772  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12773  * which also refreleases the 'conn' that was refheld at the start of the
12774  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12775  *
12776  * Many exclusive ioctls go thru an internal down up sequence as part of
12777  * the operation. For example an attempt to change the IP address of an
12778  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12779  * does all the cleanup such as deleting all ires that use this address.
12780  * Then we need to wait till all references to the interface go away.
12781  */
12782 void
12783 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12784 {
12785 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12786 	ip_ioctl_cmd_t *ipip = arg;
12787 	ip_extract_func_t *extract_funcp;
12788 	cmd_info_t ci;
12789 	int err;
12790 	boolean_t entered_ipsq = B_FALSE;
12791 
12792 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12793 
12794 	if (ipip == NULL)
12795 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12796 
12797 	/*
12798 	 * SIOCLIFADDIF needs to go thru a special path since the
12799 	 * ill may not exist yet. This happens in the case of lo0
12800 	 * which is created using this ioctl.
12801 	 */
12802 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12803 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12804 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12805 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12806 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12807 		return;
12808 	}
12809 
12810 	ci.ci_ipif = NULL;
12811 	switch (ipip->ipi_cmd_type) {
12812 	case MISC_CMD:
12813 	case MSFILT_CMD:
12814 		/*
12815 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12816 		 */
12817 		if (ipip->ipi_cmd == IF_UNITSEL) {
12818 			/* ioctl comes down the ill */
12819 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12820 			ipif_refhold(ci.ci_ipif);
12821 		}
12822 		err = 0;
12823 		ci.ci_sin = NULL;
12824 		ci.ci_sin6 = NULL;
12825 		ci.ci_lifr = NULL;
12826 		extract_funcp = NULL;
12827 		break;
12828 
12829 	case IF_CMD:
12830 	case LIF_CMD:
12831 		extract_funcp = ip_extract_lifreq;
12832 		break;
12833 
12834 	case ARP_CMD:
12835 	case XARP_CMD:
12836 		extract_funcp = ip_extract_arpreq;
12837 		break;
12838 
12839 	default:
12840 		ASSERT(0);
12841 	}
12842 
12843 	if (extract_funcp != NULL) {
12844 		err = (*extract_funcp)(q, mp, ipip, &ci);
12845 		if (err != 0) {
12846 			DTRACE_PROBE4(ipif__ioctl,
12847 			    char *, "ip_process_ioctl finish err",
12848 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12849 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12850 			return;
12851 		}
12852 
12853 		/*
12854 		 * All of the extraction functions return a refheld ipif.
12855 		 */
12856 		ASSERT(ci.ci_ipif != NULL);
12857 	}
12858 
12859 	if (!(ipip->ipi_flags & IPI_WR)) {
12860 		/*
12861 		 * A return value of EINPROGRESS means the ioctl is
12862 		 * either queued and waiting for some reason or has
12863 		 * already completed.
12864 		 */
12865 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12866 		    ci.ci_lifr);
12867 		if (ci.ci_ipif != NULL) {
12868 			DTRACE_PROBE4(ipif__ioctl,
12869 			    char *, "ip_process_ioctl finish RD",
12870 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12871 			    ipif_t *, ci.ci_ipif);
12872 			ipif_refrele(ci.ci_ipif);
12873 		} else {
12874 			DTRACE_PROBE4(ipif__ioctl,
12875 			    char *, "ip_process_ioctl finish RD",
12876 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12877 		}
12878 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12879 		return;
12880 	}
12881 
12882 	ASSERT(ci.ci_ipif != NULL);
12883 
12884 	/*
12885 	 * If ipsq is non-NULL, we are already being called exclusively
12886 	 */
12887 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12888 	if (ipsq == NULL) {
12889 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12890 		    NEW_OP, B_TRUE);
12891 		if (ipsq == NULL) {
12892 			ipif_refrele(ci.ci_ipif);
12893 			return;
12894 		}
12895 		entered_ipsq = B_TRUE;
12896 	}
12897 	/*
12898 	 * Release the ipif so that ipif_down and friends that wait for
12899 	 * references to go away are not misled about the current ipif_refcnt
12900 	 * values. We are writer so we can access the ipif even after releasing
12901 	 * the ipif.
12902 	 */
12903 	ipif_refrele(ci.ci_ipif);
12904 
12905 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12906 
12907 	/*
12908 	 * A return value of EINPROGRESS means the ioctl is
12909 	 * either queued and waiting for some reason or has
12910 	 * already completed.
12911 	 */
12912 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12913 
12914 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12915 	    int, ipip->ipi_cmd,
12916 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12917 	    ipif_t *, ci.ci_ipif);
12918 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12919 
12920 	if (entered_ipsq)
12921 		ipsq_exit(ipsq);
12922 }
12923 
12924 /*
12925  * Complete the ioctl. Typically ioctls use the mi package and need to
12926  * do mi_copyout/mi_copy_done.
12927  */
12928 void
12929 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12930 {
12931 	conn_t	*connp = NULL;
12932 
12933 	if (err == EINPROGRESS)
12934 		return;
12935 
12936 	if (CONN_Q(q)) {
12937 		connp = Q_TO_CONN(q);
12938 		ASSERT(connp->conn_ref >= 2);
12939 	}
12940 
12941 	switch (mode) {
12942 	case COPYOUT:
12943 		if (err == 0)
12944 			mi_copyout(q, mp);
12945 		else
12946 			mi_copy_done(q, mp, err);
12947 		break;
12948 
12949 	case NO_COPYOUT:
12950 		mi_copy_done(q, mp, err);
12951 		break;
12952 
12953 	default:
12954 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12955 		break;
12956 	}
12957 
12958 	/*
12959 	 * The conn refhold and ioctlref placed on the conn at the start of the
12960 	 * ioctl are released here.
12961 	 */
12962 	if (connp != NULL) {
12963 		CONN_DEC_IOCTLREF(connp);
12964 		CONN_OPER_PENDING_DONE(connp);
12965 	}
12966 
12967 	if (ipsq != NULL)
12968 		ipsq_current_finish(ipsq);
12969 }
12970 
12971 /* Handles all non data messages */
12972 void
12973 ip_wput_nondata(queue_t *q, mblk_t *mp)
12974 {
12975 	mblk_t		*mp1;
12976 	struct iocblk	*iocp;
12977 	ip_ioctl_cmd_t	*ipip;
12978 	conn_t		*connp;
12979 	cred_t		*cr;
12980 	char		*proto_str;
12981 
12982 	if (CONN_Q(q))
12983 		connp = Q_TO_CONN(q);
12984 	else
12985 		connp = NULL;
12986 
12987 	switch (DB_TYPE(mp)) {
12988 	case M_IOCTL:
12989 		/*
12990 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12991 		 * will arrange to copy in associated control structures.
12992 		 */
12993 		ip_sioctl_copyin_setup(q, mp);
12994 		return;
12995 	case M_IOCDATA:
12996 		/*
12997 		 * Ensure that this is associated with one of our trans-
12998 		 * parent ioctls.  If it's not ours, discard it if we're
12999 		 * running as a driver, or pass it on if we're a module.
13000 		 */
13001 		iocp = (struct iocblk *)mp->b_rptr;
13002 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
13003 		if (ipip == NULL) {
13004 			if (q->q_next == NULL) {
13005 				goto nak;
13006 			} else {
13007 				putnext(q, mp);
13008 			}
13009 			return;
13010 		}
13011 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
13012 			/*
13013 			 * The ioctl is one we recognise, but is not consumed
13014 			 * by IP as a module and we are a module, so we drop
13015 			 */
13016 			goto nak;
13017 		}
13018 
13019 		/* IOCTL continuation following copyin or copyout. */
13020 		if (mi_copy_state(q, mp, NULL) == -1) {
13021 			/*
13022 			 * The copy operation failed.  mi_copy_state already
13023 			 * cleaned up, so we're out of here.
13024 			 */
13025 			return;
13026 		}
13027 		/*
13028 		 * If we just completed a copy in, we become writer and
13029 		 * continue processing in ip_sioctl_copyin_done.  If it
13030 		 * was a copy out, we call mi_copyout again.  If there is
13031 		 * nothing more to copy out, it will complete the IOCTL.
13032 		 */
13033 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
13034 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
13035 				mi_copy_done(q, mp, EPROTO);
13036 				return;
13037 			}
13038 			/*
13039 			 * Check for cases that need more copying.  A return
13040 			 * value of 0 means a second copyin has been started,
13041 			 * so we return; a return value of 1 means no more
13042 			 * copying is needed, so we continue.
13043 			 */
13044 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
13045 			    MI_COPY_COUNT(mp) == 1) {
13046 				if (ip_copyin_msfilter(q, mp) == 0)
13047 					return;
13048 			}
13049 			/*
13050 			 * Refhold the conn, till the ioctl completes. This is
13051 			 * needed in case the ioctl ends up in the pending mp
13052 			 * list. Every mp in the ipx_pending_mp list must have
13053 			 * a refhold on the conn to resume processing. The
13054 			 * refhold is released when the ioctl completes
13055 			 * (whether normally or abnormally). An ioctlref is also
13056 			 * placed on the conn to prevent TCP from removing the
13057 			 * queue needed to send the ioctl reply back.
13058 			 * In all cases ip_ioctl_finish is called to finish
13059 			 * the ioctl and release the refholds.
13060 			 */
13061 			if (connp != NULL) {
13062 				/* This is not a reentry */
13063 				CONN_INC_REF(connp);
13064 				CONN_INC_IOCTLREF(connp);
13065 			} else {
13066 				if (!(ipip->ipi_flags & IPI_MODOK)) {
13067 					mi_copy_done(q, mp, EINVAL);
13068 					return;
13069 				}
13070 			}
13071 
13072 			ip_process_ioctl(NULL, q, mp, ipip);
13073 
13074 		} else {
13075 			mi_copyout(q, mp);
13076 		}
13077 		return;
13078 
13079 	case M_IOCNAK:
13080 		/*
13081 		 * The only way we could get here is if a resolver didn't like
13082 		 * an IOCTL we sent it.	 This shouldn't happen.
13083 		 */
13084 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13085 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
13086 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
13087 		freemsg(mp);
13088 		return;
13089 	case M_IOCACK:
13090 		/* /dev/ip shouldn't see this */
13091 		goto nak;
13092 	case M_FLUSH:
13093 		if (*mp->b_rptr & FLUSHW)
13094 			flushq(q, FLUSHALL);
13095 		if (q->q_next) {
13096 			putnext(q, mp);
13097 			return;
13098 		}
13099 		if (*mp->b_rptr & FLUSHR) {
13100 			*mp->b_rptr &= ~FLUSHW;
13101 			qreply(q, mp);
13102 			return;
13103 		}
13104 		freemsg(mp);
13105 		return;
13106 	case M_CTL:
13107 		break;
13108 	case M_PROTO:
13109 	case M_PCPROTO:
13110 		/*
13111 		 * The only PROTO messages we expect are SNMP-related.
13112 		 */
13113 		switch (((union T_primitives *)mp->b_rptr)->type) {
13114 		case T_SVR4_OPTMGMT_REQ:
13115 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
13116 			    "flags %x\n",
13117 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
13118 
13119 			if (connp == NULL) {
13120 				proto_str = "T_SVR4_OPTMGMT_REQ";
13121 				goto protonak;
13122 			}
13123 
13124 			/*
13125 			 * All Solaris components should pass a db_credp
13126 			 * for this TPI message, hence we ASSERT.
13127 			 * But in case there is some other M_PROTO that looks
13128 			 * like a TPI message sent by some other kernel
13129 			 * component, we check and return an error.
13130 			 */
13131 			cr = msg_getcred(mp, NULL);
13132 			ASSERT(cr != NULL);
13133 			if (cr == NULL) {
13134 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
13135 				if (mp != NULL)
13136 					qreply(q, mp);
13137 				return;
13138 			}
13139 
13140 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
13141 				proto_str = "Bad SNMPCOM request?";
13142 				goto protonak;
13143 			}
13144 			return;
13145 		default:
13146 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
13147 			    (int)*(uint_t *)mp->b_rptr));
13148 			freemsg(mp);
13149 			return;
13150 		}
13151 	default:
13152 		break;
13153 	}
13154 	if (q->q_next) {
13155 		putnext(q, mp);
13156 	} else
13157 		freemsg(mp);
13158 	return;
13159 
13160 nak:
13161 	iocp->ioc_error = EINVAL;
13162 	mp->b_datap->db_type = M_IOCNAK;
13163 	iocp->ioc_count = 0;
13164 	qreply(q, mp);
13165 	return;
13166 
13167 protonak:
13168 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
13169 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
13170 		qreply(q, mp);
13171 }
13172 
13173 /*
13174  * Process IP options in an outbound packet.  Verify that the nexthop in a
13175  * strict source route is onlink.
13176  * Returns non-zero if something fails in which case an ICMP error has been
13177  * sent and mp freed.
13178  *
13179  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
13180  */
13181 int
13182 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
13183 {
13184 	ipoptp_t	opts;
13185 	uchar_t		*opt;
13186 	uint8_t		optval;
13187 	uint8_t		optlen;
13188 	ipaddr_t	dst;
13189 	intptr_t	code = 0;
13190 	ire_t		*ire;
13191 	ip_stack_t	*ipst = ixa->ixa_ipst;
13192 	ip_recv_attr_t	iras;
13193 
13194 	ip2dbg(("ip_output_options\n"));
13195 
13196 	dst = ipha->ipha_dst;
13197 	for (optval = ipoptp_first(&opts, ipha);
13198 	    optval != IPOPT_EOL;
13199 	    optval = ipoptp_next(&opts)) {
13200 		opt = opts.ipoptp_cur;
13201 		optlen = opts.ipoptp_len;
13202 		ip2dbg(("ip_output_options: opt %d, len %d\n",
13203 		    optval, optlen));
13204 		switch (optval) {
13205 			uint32_t off;
13206 		case IPOPT_SSRR:
13207 		case IPOPT_LSRR:
13208 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13209 				ip1dbg((
13210 				    "ip_output_options: bad option offset\n"));
13211 				code = (char *)&opt[IPOPT_OLEN] -
13212 				    (char *)ipha;
13213 				goto param_prob;
13214 			}
13215 			off = opt[IPOPT_OFFSET];
13216 			ip1dbg(("ip_output_options: next hop 0x%x\n",
13217 			    ntohl(dst)));
13218 			/*
13219 			 * For strict: verify that dst is directly
13220 			 * reachable.
13221 			 */
13222 			if (optval == IPOPT_SSRR) {
13223 				ire = ire_ftable_lookup_v4(dst, 0, 0,
13224 				    IRE_IF_ALL, NULL, ALL_ZONES, ixa->ixa_tsl,
13225 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
13226 				    NULL);
13227 				if (ire == NULL) {
13228 					ip1dbg(("ip_output_options: SSRR not"
13229 					    " directly reachable: 0x%x\n",
13230 					    ntohl(dst)));
13231 					goto bad_src_route;
13232 				}
13233 				ire_refrele(ire);
13234 			}
13235 			break;
13236 		case IPOPT_RR:
13237 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13238 				ip1dbg((
13239 				    "ip_output_options: bad option offset\n"));
13240 				code = (char *)&opt[IPOPT_OLEN] -
13241 				    (char *)ipha;
13242 				goto param_prob;
13243 			}
13244 			break;
13245 		case IPOPT_TS:
13246 			/*
13247 			 * Verify that length >=5 and that there is either
13248 			 * room for another timestamp or that the overflow
13249 			 * counter is not maxed out.
13250 			 */
13251 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
13252 			if (optlen < IPOPT_MINLEN_IT) {
13253 				goto param_prob;
13254 			}
13255 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13256 				ip1dbg((
13257 				    "ip_output_options: bad option offset\n"));
13258 				code = (char *)&opt[IPOPT_OFFSET] -
13259 				    (char *)ipha;
13260 				goto param_prob;
13261 			}
13262 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13263 			case IPOPT_TS_TSONLY:
13264 				off = IPOPT_TS_TIMELEN;
13265 				break;
13266 			case IPOPT_TS_TSANDADDR:
13267 			case IPOPT_TS_PRESPEC:
13268 			case IPOPT_TS_PRESPEC_RFC791:
13269 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13270 				break;
13271 			default:
13272 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
13273 				    (char *)ipha;
13274 				goto param_prob;
13275 			}
13276 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13277 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13278 				/*
13279 				 * No room and the overflow counter is 15
13280 				 * already.
13281 				 */
13282 				goto param_prob;
13283 			}
13284 			break;
13285 		}
13286 	}
13287 
13288 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13289 		return (0);
13290 
13291 	ip1dbg(("ip_output_options: error processing IP options."));
13292 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13293 
13294 param_prob:
13295 	bzero(&iras, sizeof (iras));
13296 	iras.ira_ill = iras.ira_rill = ill;
13297 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13298 	iras.ira_rifindex = iras.ira_ruifindex;
13299 	iras.ira_flags = IRAF_IS_IPV4;
13300 
13301 	ip_drop_output("ip_output_options", mp, ill);
13302 	icmp_param_problem(mp, (uint8_t)code, &iras);
13303 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13304 	return (-1);
13305 
13306 bad_src_route:
13307 	bzero(&iras, sizeof (iras));
13308 	iras.ira_ill = iras.ira_rill = ill;
13309 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13310 	iras.ira_rifindex = iras.ira_ruifindex;
13311 	iras.ira_flags = IRAF_IS_IPV4;
13312 
13313 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13314 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13315 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13316 	return (-1);
13317 }
13318 
13319 /*
13320  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13321  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13322  * thru /etc/system.
13323  */
13324 #define	CONN_MAXDRAINCNT	64
13325 
13326 static void
13327 conn_drain_init(ip_stack_t *ipst)
13328 {
13329 	int i, j;
13330 	idl_tx_list_t *itl_tx;
13331 
13332 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13333 
13334 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
13335 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13336 		/*
13337 		 * Default value of the number of drainers is the
13338 		 * number of cpus, subject to maximum of 8 drainers.
13339 		 */
13340 		if (boot_max_ncpus != -1)
13341 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13342 		else
13343 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13344 	}
13345 
13346 	ipst->ips_idl_tx_list =
13347 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13348 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13349 		itl_tx =  &ipst->ips_idl_tx_list[i];
13350 		itl_tx->txl_drain_list =
13351 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13352 		    sizeof (idl_t), KM_SLEEP);
13353 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13354 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13355 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13356 			    MUTEX_DEFAULT, NULL);
13357 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13358 		}
13359 	}
13360 }
13361 
13362 static void
13363 conn_drain_fini(ip_stack_t *ipst)
13364 {
13365 	int i;
13366 	idl_tx_list_t *itl_tx;
13367 
13368 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13369 		itl_tx =  &ipst->ips_idl_tx_list[i];
13370 		kmem_free(itl_tx->txl_drain_list,
13371 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13372 	}
13373 	kmem_free(ipst->ips_idl_tx_list,
13374 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13375 	ipst->ips_idl_tx_list = NULL;
13376 }
13377 
13378 /*
13379  * Note: For an overview of how flowcontrol is handled in IP please see the
13380  * IP Flowcontrol notes at the top of this file.
13381  *
13382  * Flow control has blocked us from proceeding. Insert the given conn in one
13383  * of the conn drain lists. These conn wq's will be qenabled later on when
13384  * STREAMS flow control does a backenable. conn_walk_drain will enable
13385  * the first conn in each of these drain lists. Each of these qenabled conns
13386  * in turn enables the next in the list, after it runs, or when it closes,
13387  * thus sustaining the drain process.
13388  */
13389 void
13390 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13391 {
13392 	idl_t	*idl = tx_list->txl_drain_list;
13393 	uint_t	index;
13394 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13395 
13396 	mutex_enter(&connp->conn_lock);
13397 	if (connp->conn_state_flags & CONN_CLOSING) {
13398 		/*
13399 		 * The conn is closing as a result of which CONN_CLOSING
13400 		 * is set. Return.
13401 		 */
13402 		mutex_exit(&connp->conn_lock);
13403 		return;
13404 	} else if (connp->conn_idl == NULL) {
13405 		/*
13406 		 * Assign the next drain list round robin. We dont' use
13407 		 * a lock, and thus it may not be strictly round robin.
13408 		 * Atomicity of load/stores is enough to make sure that
13409 		 * conn_drain_list_index is always within bounds.
13410 		 */
13411 		index = tx_list->txl_drain_index;
13412 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13413 		connp->conn_idl = &tx_list->txl_drain_list[index];
13414 		index++;
13415 		if (index == ipst->ips_conn_drain_list_cnt)
13416 			index = 0;
13417 		tx_list->txl_drain_index = index;
13418 	}
13419 	mutex_exit(&connp->conn_lock);
13420 
13421 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
13422 	if ((connp->conn_drain_prev != NULL) ||
13423 	    (connp->conn_state_flags & CONN_CLOSING)) {
13424 		/*
13425 		 * The conn is already in the drain list, OR
13426 		 * the conn is closing. We need to check again for
13427 		 * the closing case again since close can happen
13428 		 * after we drop the conn_lock, and before we
13429 		 * acquire the CONN_DRAIN_LIST_LOCK.
13430 		 */
13431 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
13432 		return;
13433 	} else {
13434 		idl = connp->conn_idl;
13435 	}
13436 
13437 	/*
13438 	 * The conn is not in the drain list. Insert it at the
13439 	 * tail of the drain list. The drain list is circular
13440 	 * and doubly linked. idl_conn points to the 1st element
13441 	 * in the list.
13442 	 */
13443 	if (idl->idl_conn == NULL) {
13444 		idl->idl_conn = connp;
13445 		connp->conn_drain_next = connp;
13446 		connp->conn_drain_prev = connp;
13447 	} else {
13448 		conn_t *head = idl->idl_conn;
13449 
13450 		connp->conn_drain_next = head;
13451 		connp->conn_drain_prev = head->conn_drain_prev;
13452 		head->conn_drain_prev->conn_drain_next = connp;
13453 		head->conn_drain_prev = connp;
13454 	}
13455 	/*
13456 	 * For non streams based sockets assert flow control.
13457 	 */
13458 	conn_setqfull(connp, NULL);
13459 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
13460 }
13461 
13462 static void
13463 conn_idl_remove(conn_t *connp)
13464 {
13465 	idl_t *idl = connp->conn_idl;
13466 
13467 	if (idl != NULL) {
13468 		/*
13469 		 * Remove ourself from the drain list, if we did not do
13470 		 * a putq, or if the conn is closing.
13471 		 * Note: It is possible that q->q_first is non-null. It means
13472 		 * that these messages landed after we did a enableok() in
13473 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
13474 		 * service them.
13475 		 */
13476 		if (connp->conn_drain_next == connp) {
13477 			/* Singleton in the list */
13478 			ASSERT(connp->conn_drain_prev == connp);
13479 			idl->idl_conn = NULL;
13480 		} else {
13481 			connp->conn_drain_prev->conn_drain_next =
13482 			    connp->conn_drain_next;
13483 			connp->conn_drain_next->conn_drain_prev =
13484 			    connp->conn_drain_prev;
13485 			if (idl->idl_conn == connp)
13486 				idl->idl_conn = connp->conn_drain_next;
13487 		}
13488 	}
13489 	connp->conn_drain_next = NULL;
13490 	connp->conn_drain_prev = NULL;
13491 
13492 	conn_clrqfull(connp, NULL);
13493 	/*
13494 	 * For streams based sockets open up flow control.
13495 	 */
13496 	if (!IPCL_IS_NONSTR(connp))
13497 		enableok(connp->conn_wq);
13498 }
13499 
13500 /*
13501  * This conn is closing, and we are called from ip_close. OR
13502  * this conn is draining because flow-control on the ill has been relieved.
13503  *
13504  * We must also need to remove conn's on this idl from the list, and also
13505  * inform the sockfs upcalls about the change in flow-control.
13506  */
13507 static void
13508 conn_drain_tail(conn_t *connp, boolean_t closing)
13509 {
13510 	idl_t *idl;
13511 	conn_t *next_connp;
13512 
13513 	/*
13514 	 * connp->conn_idl is stable at this point, and no lock is needed
13515 	 * to check it. If we are called from ip_close, close has already
13516 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13517 	 * called us only because conn_idl is non-null. If we are called thru
13518 	 * service, conn_idl could be null, but it cannot change because
13519 	 * service is single-threaded per queue, and there cannot be another
13520 	 * instance of service trying to call conn_drain_insert on this conn
13521 	 * now.
13522 	 */
13523 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13524 
13525 	/*
13526 	 * If connp->conn_idl is null, the conn has not been inserted into any
13527 	 * drain list even once since creation of the conn. Just return.
13528 	 */
13529 	if (connp == NULL || connp->conn_idl == NULL)
13530 		return;
13531 
13532 	if (connp->conn_drain_prev == NULL) {
13533 		/* This conn is currently not in the drain list.  */
13534 		return;
13535 	}
13536 	idl = connp->conn_idl;
13537 	if (!closing) {
13538 		/*
13539 		 * This conn is the current drainer. If this is the last conn
13540 		 * in the drain list, we need to do more checks, in the 'if'
13541 		 * below. Otherwwise we need to just qenable the next conn,
13542 		 * to sustain the draining, and is handled in the 'else'
13543 		 * below.
13544 		 */
13545 		next_connp = connp->conn_drain_next;
13546 		while (next_connp != connp) {
13547 			conn_t *delconnp = next_connp;
13548 
13549 			next_connp = next_connp->conn_drain_next;
13550 			conn_idl_remove(delconnp);
13551 		}
13552 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13553 	}
13554 	conn_idl_remove(connp);
13555 
13556 }
13557 
13558 /*
13559  * Write service routine. Shared perimeter entry point.
13560  * The device queue's messages has fallen below the low water mark and STREAMS
13561  * has backenabled the ill_wq. Send sockfs notification about flow-control onx
13562  * each waiting conn.
13563  */
13564 void
13565 ip_wsrv(queue_t *q)
13566 {
13567 	ill_t	*ill;
13568 
13569 	ill = (ill_t *)q->q_ptr;
13570 	if (ill->ill_state_flags == 0) {
13571 		ip_stack_t *ipst = ill->ill_ipst;
13572 
13573 		/*
13574 		 * The device flow control has opened up.
13575 		 * Walk through conn drain lists and qenable the
13576 		 * first conn in each list. This makes sense only
13577 		 * if the stream is fully plumbed and setup.
13578 		 * Hence the ill_state_flags check above.
13579 		 */
13580 		ip1dbg(("ip_wsrv: walking\n"));
13581 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13582 		enableok(ill->ill_wq);
13583 	}
13584 }
13585 
13586 /*
13587  * Callback to disable flow control in IP.
13588  *
13589  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13590  * is enabled.
13591  *
13592  * When MAC_TX() is not able to send any more packets, dld sets its queue
13593  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13594  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13595  * function and wakes up corresponding mac worker threads, which in turn
13596  * calls this callback function, and disables flow control.
13597  */
13598 void
13599 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13600 {
13601 	ill_t *ill = (ill_t *)arg;
13602 	ip_stack_t *ipst = ill->ill_ipst;
13603 	idl_tx_list_t *idl_txl;
13604 
13605 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13606 	mutex_enter(&idl_txl->txl_lock);
13607 	/* add code to to set a flag to indicate idl_txl is enabled */
13608 	conn_walk_drain(ipst, idl_txl);
13609 	mutex_exit(&idl_txl->txl_lock);
13610 }
13611 
13612 /*
13613  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
13614  * of conns that need to be drained, check if drain is already in progress.
13615  * If so set the idl_repeat bit, indicating that the last conn in the list
13616  * needs to reinitiate the drain once again, for the list. If drain is not
13617  * in progress for the list, initiate the draining, by qenabling the 1st
13618  * conn in the list. The drain is self-sustaining, each qenabled conn will
13619  * in turn qenable the next conn, when it is done/blocked/closing.
13620  */
13621 static void
13622 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13623 {
13624 	int i;
13625 	idl_t *idl;
13626 
13627 	IP_STAT(ipst, ip_conn_walk_drain);
13628 
13629 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13630 		idl = &tx_list->txl_drain_list[i];
13631 		mutex_enter(&idl->idl_lock);
13632 		conn_drain_tail(idl->idl_conn, B_FALSE);
13633 		mutex_exit(&idl->idl_lock);
13634 	}
13635 }
13636 
13637 /*
13638  * Determine if the ill and multicast aspects of that packets
13639  * "matches" the conn.
13640  */
13641 boolean_t
13642 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13643 {
13644 	ill_t		*ill = ira->ira_rill;
13645 	zoneid_t	zoneid = ira->ira_zoneid;
13646 	uint_t		in_ifindex;
13647 	ipaddr_t	dst, src;
13648 
13649 	dst = ipha->ipha_dst;
13650 	src = ipha->ipha_src;
13651 
13652 	/*
13653 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13654 	 * unicast, broadcast and multicast reception to
13655 	 * conn_incoming_ifindex.
13656 	 * conn_wantpacket is called for unicast, broadcast and
13657 	 * multicast packets.
13658 	 */
13659 	in_ifindex = connp->conn_incoming_ifindex;
13660 
13661 	/* mpathd can bind to the under IPMP interface, which we allow */
13662 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13663 		if (!IS_UNDER_IPMP(ill))
13664 			return (B_FALSE);
13665 
13666 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13667 			return (B_FALSE);
13668 	}
13669 
13670 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13671 		return (B_FALSE);
13672 
13673 	if (!(ira->ira_flags & IRAF_MULTICAST))
13674 		return (B_TRUE);
13675 
13676 	if (connp->conn_multi_router) {
13677 		/* multicast packet and multicast router socket: send up */
13678 		return (B_TRUE);
13679 	}
13680 
13681 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13682 	    ipha->ipha_protocol == IPPROTO_RSVP)
13683 		return (B_TRUE);
13684 
13685 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13686 }
13687 
13688 void
13689 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13690 {
13691 	if (IPCL_IS_NONSTR(connp)) {
13692 		(*connp->conn_upcalls->su_txq_full)
13693 		    (connp->conn_upper_handle, B_TRUE);
13694 		if (flow_stopped != NULL)
13695 			*flow_stopped = B_TRUE;
13696 	} else {
13697 		queue_t *q = connp->conn_wq;
13698 
13699 		ASSERT(q != NULL);
13700 		if (!(q->q_flag & QFULL)) {
13701 			mutex_enter(QLOCK(q));
13702 			if (!(q->q_flag & QFULL)) {
13703 				/* still need to set QFULL */
13704 				q->q_flag |= QFULL;
13705 				/* set flow_stopped to true under QLOCK */
13706 				if (flow_stopped != NULL)
13707 					*flow_stopped = B_TRUE;
13708 				mutex_exit(QLOCK(q));
13709 			} else {
13710 				/* flow_stopped is left unchanged */
13711 				mutex_exit(QLOCK(q));
13712 			}
13713 		}
13714 	}
13715 }
13716 
13717 void
13718 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13719 {
13720 	if (IPCL_IS_NONSTR(connp)) {
13721 		(*connp->conn_upcalls->su_txq_full)
13722 		    (connp->conn_upper_handle, B_FALSE);
13723 		if (flow_stopped != NULL)
13724 			*flow_stopped = B_FALSE;
13725 	} else {
13726 		queue_t *q = connp->conn_wq;
13727 
13728 		ASSERT(q != NULL);
13729 		if (q->q_flag & QFULL) {
13730 			mutex_enter(QLOCK(q));
13731 			if (q->q_flag & QFULL) {
13732 				q->q_flag &= ~QFULL;
13733 				/* set flow_stopped to false under QLOCK */
13734 				if (flow_stopped != NULL)
13735 					*flow_stopped = B_FALSE;
13736 				mutex_exit(QLOCK(q));
13737 				if (q->q_flag & QWANTW)
13738 					qbackenable(q, 0);
13739 			} else {
13740 				/* flow_stopped is left unchanged */
13741 				mutex_exit(QLOCK(q));
13742 			}
13743 		}
13744 	}
13745 	connp->conn_direct_blocked = B_FALSE;
13746 }
13747 
13748 /*
13749  * Return the length in bytes of the IPv4 headers (base header, label, and
13750  * other IP options) that will be needed based on the
13751  * ip_pkt_t structure passed by the caller.
13752  *
13753  * The returned length does not include the length of the upper level
13754  * protocol (ULP) header.
13755  * The caller needs to check that the length doesn't exceed the max for IPv4.
13756  */
13757 int
13758 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13759 {
13760 	int len;
13761 
13762 	len = IP_SIMPLE_HDR_LENGTH;
13763 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13764 		ASSERT(ipp->ipp_label_len_v4 != 0);
13765 		/* We need to round up here */
13766 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13767 	}
13768 
13769 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13770 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13771 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13772 		len += ipp->ipp_ipv4_options_len;
13773 	}
13774 	return (len);
13775 }
13776 
13777 /*
13778  * All-purpose routine to build an IPv4 header with options based
13779  * on the abstract ip_pkt_t.
13780  *
13781  * The caller has to set the source and destination address as well as
13782  * ipha_length. The caller has to massage any source route and compensate
13783  * for the ULP pseudo-header checksum due to the source route.
13784  */
13785 void
13786 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13787     uint8_t protocol)
13788 {
13789 	ipha_t	*ipha = (ipha_t *)buf;
13790 	uint8_t *cp;
13791 
13792 	/* Initialize IPv4 header */
13793 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13794 	ipha->ipha_length = 0;	/* Caller will set later */
13795 	ipha->ipha_ident = 0;
13796 	ipha->ipha_fragment_offset_and_flags = 0;
13797 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13798 	ipha->ipha_protocol = protocol;
13799 	ipha->ipha_hdr_checksum = 0;
13800 
13801 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13802 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13803 		ipha->ipha_src = ipp->ipp_addr_v4;
13804 
13805 	cp = (uint8_t *)&ipha[1];
13806 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13807 		ASSERT(ipp->ipp_label_len_v4 != 0);
13808 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13809 		cp += ipp->ipp_label_len_v4;
13810 		/* We need to round up here */
13811 		while ((uintptr_t)cp & 0x3) {
13812 			*cp++ = IPOPT_NOP;
13813 		}
13814 	}
13815 
13816 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13817 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13818 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13819 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13820 		cp += ipp->ipp_ipv4_options_len;
13821 	}
13822 	ipha->ipha_version_and_hdr_length =
13823 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13824 
13825 	ASSERT((int)(cp - buf) == buf_len);
13826 }
13827 
13828 /* Allocate the private structure */
13829 static int
13830 ip_priv_alloc(void **bufp)
13831 {
13832 	void	*buf;
13833 
13834 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13835 		return (ENOMEM);
13836 
13837 	*bufp = buf;
13838 	return (0);
13839 }
13840 
13841 /* Function to delete the private structure */
13842 void
13843 ip_priv_free(void *buf)
13844 {
13845 	ASSERT(buf != NULL);
13846 	kmem_free(buf, sizeof (ip_priv_t));
13847 }
13848 
13849 /*
13850  * The entry point for IPPF processing.
13851  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13852  * routine just returns.
13853  *
13854  * When called, ip_process generates an ipp_packet_t structure
13855  * which holds the state information for this packet and invokes the
13856  * the classifier (via ipp_packet_process). The classification, depending on
13857  * configured filters, results in a list of actions for this packet. Invoking
13858  * an action may cause the packet to be dropped, in which case we return NULL.
13859  * proc indicates the callout position for
13860  * this packet and ill is the interface this packet arrived on or will leave
13861  * on (inbound and outbound resp.).
13862  *
13863  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13864  * on the ill corrsponding to the destination IP address.
13865  */
13866 mblk_t *
13867 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13868 {
13869 	ip_priv_t	*priv;
13870 	ipp_action_id_t	aid;
13871 	int		rc = 0;
13872 	ipp_packet_t	*pp;
13873 
13874 	/* If the classifier is not loaded, return  */
13875 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13876 		return (mp);
13877 	}
13878 
13879 	ASSERT(mp != NULL);
13880 
13881 	/* Allocate the packet structure */
13882 	rc = ipp_packet_alloc(&pp, "ip", aid);
13883 	if (rc != 0)
13884 		goto drop;
13885 
13886 	/* Allocate the private structure */
13887 	rc = ip_priv_alloc((void **)&priv);
13888 	if (rc != 0) {
13889 		ipp_packet_free(pp);
13890 		goto drop;
13891 	}
13892 	priv->proc = proc;
13893 	priv->ill_index = ill_get_upper_ifindex(rill);
13894 
13895 	ipp_packet_set_private(pp, priv, ip_priv_free);
13896 	ipp_packet_set_data(pp, mp);
13897 
13898 	/* Invoke the classifier */
13899 	rc = ipp_packet_process(&pp);
13900 	if (pp != NULL) {
13901 		mp = ipp_packet_get_data(pp);
13902 		ipp_packet_free(pp);
13903 		if (rc != 0)
13904 			goto drop;
13905 		return (mp);
13906 	} else {
13907 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13908 		mp = NULL;
13909 	}
13910 drop:
13911 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13912 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13913 		ip_drop_input("ip_process", mp, ill);
13914 	} else {
13915 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13916 		ip_drop_output("ip_process", mp, ill);
13917 	}
13918 	freemsg(mp);
13919 	return (NULL);
13920 }
13921 
13922 /*
13923  * Propagate a multicast group membership operation (add/drop) on
13924  * all the interfaces crossed by the related multirt routes.
13925  * The call is considered successful if the operation succeeds
13926  * on at least one interface.
13927  *
13928  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13929  * multicast addresses with the ire argument being the first one.
13930  * We walk the bucket to find all the of those.
13931  *
13932  * Common to IPv4 and IPv6.
13933  */
13934 static int
13935 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13936     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13937     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13938     mcast_record_t fmode, const in6_addr_t *v6src)
13939 {
13940 	ire_t		*ire_gw;
13941 	irb_t		*irb;
13942 	int		ifindex;
13943 	int		error = 0;
13944 	int		result;
13945 	ip_stack_t	*ipst = ire->ire_ipst;
13946 	ipaddr_t	group;
13947 	boolean_t	isv6;
13948 	int		match_flags;
13949 
13950 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13951 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13952 		isv6 = B_FALSE;
13953 	} else {
13954 		isv6 = B_TRUE;
13955 	}
13956 
13957 	irb = ire->ire_bucket;
13958 	ASSERT(irb != NULL);
13959 
13960 	result = 0;
13961 	irb_refhold(irb);
13962 	for (; ire != NULL; ire = ire->ire_next) {
13963 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13964 			continue;
13965 
13966 		/* We handle -ifp routes by matching on the ill if set */
13967 		match_flags = MATCH_IRE_TYPE;
13968 		if (ire->ire_ill != NULL)
13969 			match_flags |= MATCH_IRE_ILL;
13970 
13971 		if (isv6) {
13972 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13973 				continue;
13974 
13975 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13976 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13977 			    match_flags, 0, ipst, NULL);
13978 		} else {
13979 			if (ire->ire_addr != group)
13980 				continue;
13981 
13982 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13983 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13984 			    match_flags, 0, ipst, NULL);
13985 		}
13986 		/* No interface route exists for the gateway; skip this ire. */
13987 		if (ire_gw == NULL)
13988 			continue;
13989 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13990 			ire_refrele(ire_gw);
13991 			continue;
13992 		}
13993 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13994 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13995 
13996 		/*
13997 		 * The operation is considered a success if
13998 		 * it succeeds at least once on any one interface.
13999 		 */
14000 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
14001 		    fmode, v6src);
14002 		if (error == 0)
14003 			result = CGTP_MCAST_SUCCESS;
14004 
14005 		ire_refrele(ire_gw);
14006 	}
14007 	irb_refrele(irb);
14008 	/*
14009 	 * Consider the call as successful if we succeeded on at least
14010 	 * one interface. Otherwise, return the last encountered error.
14011 	 */
14012 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
14013 }
14014 
14015 /*
14016  * Get the CGTP (multirouting) filtering status.
14017  * If 0, the CGTP hooks are transparent.
14018  */
14019 /* ARGSUSED */
14020 static int
14021 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
14022 {
14023 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
14024 
14025 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
14026 	return (0);
14027 }
14028 
14029 /*
14030  * Set the CGTP (multirouting) filtering status.
14031  * If the status is changed from active to transparent
14032  * or from transparent to active, forward the new status
14033  * to the filtering module (if loaded).
14034  */
14035 /* ARGSUSED */
14036 static int
14037 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
14038     cred_t *ioc_cr)
14039 {
14040 	long		new_value;
14041 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
14042 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
14043 
14044 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
14045 		return (EPERM);
14046 
14047 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
14048 	    new_value < 0 || new_value > 1) {
14049 		return (EINVAL);
14050 	}
14051 
14052 	if ((!*ip_cgtp_filter_value) && new_value) {
14053 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
14054 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
14055 		    " (module not loaded)" : "");
14056 	}
14057 	if (*ip_cgtp_filter_value && (!new_value)) {
14058 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
14059 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
14060 		    " (module not loaded)" : "");
14061 	}
14062 
14063 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
14064 		int	res;
14065 		netstackid_t stackid;
14066 
14067 		stackid = ipst->ips_netstack->netstack_stackid;
14068 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
14069 		    new_value);
14070 		if (res)
14071 			return (res);
14072 	}
14073 
14074 	*ip_cgtp_filter_value = (boolean_t)new_value;
14075 
14076 	ill_set_inputfn_all(ipst);
14077 	return (0);
14078 }
14079 
14080 /*
14081  * Return the expected CGTP hooks version number.
14082  */
14083 int
14084 ip_cgtp_filter_supported(void)
14085 {
14086 	return (ip_cgtp_filter_rev);
14087 }
14088 
14089 /*
14090  * CGTP hooks can be registered by invoking this function.
14091  * Checks that the version number matches.
14092  */
14093 int
14094 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
14095 {
14096 	netstack_t *ns;
14097 	ip_stack_t *ipst;
14098 
14099 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
14100 		return (ENOTSUP);
14101 
14102 	ns = netstack_find_by_stackid(stackid);
14103 	if (ns == NULL)
14104 		return (EINVAL);
14105 	ipst = ns->netstack_ip;
14106 	ASSERT(ipst != NULL);
14107 
14108 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
14109 		netstack_rele(ns);
14110 		return (EALREADY);
14111 	}
14112 
14113 	ipst->ips_ip_cgtp_filter_ops = ops;
14114 
14115 	ill_set_inputfn_all(ipst);
14116 
14117 	netstack_rele(ns);
14118 	return (0);
14119 }
14120 
14121 /*
14122  * CGTP hooks can be unregistered by invoking this function.
14123  * Returns ENXIO if there was no registration.
14124  * Returns EBUSY if the ndd variable has not been turned off.
14125  */
14126 int
14127 ip_cgtp_filter_unregister(netstackid_t stackid)
14128 {
14129 	netstack_t *ns;
14130 	ip_stack_t *ipst;
14131 
14132 	ns = netstack_find_by_stackid(stackid);
14133 	if (ns == NULL)
14134 		return (EINVAL);
14135 	ipst = ns->netstack_ip;
14136 	ASSERT(ipst != NULL);
14137 
14138 	if (ipst->ips_ip_cgtp_filter) {
14139 		netstack_rele(ns);
14140 		return (EBUSY);
14141 	}
14142 
14143 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
14144 		netstack_rele(ns);
14145 		return (ENXIO);
14146 	}
14147 	ipst->ips_ip_cgtp_filter_ops = NULL;
14148 
14149 	ill_set_inputfn_all(ipst);
14150 
14151 	netstack_rele(ns);
14152 	return (0);
14153 }
14154 
14155 /*
14156  * Check whether there is a CGTP filter registration.
14157  * Returns non-zero if there is a registration, otherwise returns zero.
14158  * Note: returns zero if bad stackid.
14159  */
14160 int
14161 ip_cgtp_filter_is_registered(netstackid_t stackid)
14162 {
14163 	netstack_t *ns;
14164 	ip_stack_t *ipst;
14165 	int ret;
14166 
14167 	ns = netstack_find_by_stackid(stackid);
14168 	if (ns == NULL)
14169 		return (0);
14170 	ipst = ns->netstack_ip;
14171 	ASSERT(ipst != NULL);
14172 
14173 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
14174 		ret = 1;
14175 	else
14176 		ret = 0;
14177 
14178 	netstack_rele(ns);
14179 	return (ret);
14180 }
14181 
14182 static int
14183 ip_squeue_switch(int val)
14184 {
14185 	int rval;
14186 
14187 	switch (val) {
14188 	case IP_SQUEUE_ENTER_NODRAIN:
14189 		rval = SQ_NODRAIN;
14190 		break;
14191 	case IP_SQUEUE_ENTER:
14192 		rval = SQ_PROCESS;
14193 		break;
14194 	case IP_SQUEUE_FILL:
14195 	default:
14196 		rval = SQ_FILL;
14197 		break;
14198 	}
14199 	return (rval);
14200 }
14201 
14202 /* ARGSUSED */
14203 static int
14204 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
14205     caddr_t addr, cred_t *cr)
14206 {
14207 	int *v = (int *)addr;
14208 	long new_value;
14209 
14210 	if (secpolicy_net_config(cr, B_FALSE) != 0)
14211 		return (EPERM);
14212 
14213 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
14214 		return (EINVAL);
14215 
14216 	ip_squeue_flag = ip_squeue_switch(new_value);
14217 	*v = new_value;
14218 	return (0);
14219 }
14220 
14221 /*
14222  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
14223  * ip_debug.
14224  */
14225 /* ARGSUSED */
14226 static int
14227 ip_int_set(queue_t *q, mblk_t *mp, char *value,
14228     caddr_t addr, cred_t *cr)
14229 {
14230 	int *v = (int *)addr;
14231 	long new_value;
14232 
14233 	if (secpolicy_net_config(cr, B_FALSE) != 0)
14234 		return (EPERM);
14235 
14236 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
14237 		return (EINVAL);
14238 
14239 	*v = new_value;
14240 	return (0);
14241 }
14242 
14243 static void *
14244 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
14245 {
14246 	kstat_t *ksp;
14247 
14248 	ip_stat_t template = {
14249 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
14250 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
14251 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
14252 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
14253 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
14254 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
14255 		{ "ip_opt",			KSTAT_DATA_UINT64 },
14256 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
14257 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
14258 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
14259 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
14260 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
14261 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
14262 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
14263 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
14264 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
14265 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
14266 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
14267 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
14268 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
14269 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
14270 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
14271 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
14272 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
14273 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
14274 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
14275 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
14276 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
14277 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
14278 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
14279 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
14280 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
14281 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
14282 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
14283 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
14284 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
14285 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
14286 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
14287 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
14288 	};
14289 
14290 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
14291 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
14292 	    KSTAT_FLAG_VIRTUAL, stackid);
14293 
14294 	if (ksp == NULL)
14295 		return (NULL);
14296 
14297 	bcopy(&template, ip_statisticsp, sizeof (template));
14298 	ksp->ks_data = (void *)ip_statisticsp;
14299 	ksp->ks_private = (void *)(uintptr_t)stackid;
14300 
14301 	kstat_install(ksp);
14302 	return (ksp);
14303 }
14304 
14305 static void
14306 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
14307 {
14308 	if (ksp != NULL) {
14309 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14310 		kstat_delete_netstack(ksp, stackid);
14311 	}
14312 }
14313 
14314 static void *
14315 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
14316 {
14317 	kstat_t	*ksp;
14318 
14319 	ip_named_kstat_t template = {
14320 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
14321 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
14322 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
14323 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
14324 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
14325 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
14326 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
14327 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
14328 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
14329 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
14330 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
14331 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
14332 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
14333 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
14334 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
14335 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
14336 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
14337 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
14338 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
14339 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
14340 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
14341 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
14342 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
14343 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
14344 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
14345 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
14346 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
14347 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
14348 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
14349 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
14350 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
14351 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
14352 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
14353 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
14354 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
14355 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
14356 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
14357 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
14358 	};
14359 
14360 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
14361 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
14362 	if (ksp == NULL || ksp->ks_data == NULL)
14363 		return (NULL);
14364 
14365 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
14366 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
14367 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
14368 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
14369 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14370 
14371 	template.netToMediaEntrySize.value.i32 =
14372 	    sizeof (mib2_ipNetToMediaEntry_t);
14373 
14374 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14375 
14376 	bcopy(&template, ksp->ks_data, sizeof (template));
14377 	ksp->ks_update = ip_kstat_update;
14378 	ksp->ks_private = (void *)(uintptr_t)stackid;
14379 
14380 	kstat_install(ksp);
14381 	return (ksp);
14382 }
14383 
14384 static void
14385 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14386 {
14387 	if (ksp != NULL) {
14388 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14389 		kstat_delete_netstack(ksp, stackid);
14390 	}
14391 }
14392 
14393 static int
14394 ip_kstat_update(kstat_t *kp, int rw)
14395 {
14396 	ip_named_kstat_t *ipkp;
14397 	mib2_ipIfStatsEntry_t ipmib;
14398 	ill_walk_context_t ctx;
14399 	ill_t *ill;
14400 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14401 	netstack_t	*ns;
14402 	ip_stack_t	*ipst;
14403 
14404 	if (kp == NULL || kp->ks_data == NULL)
14405 		return (EIO);
14406 
14407 	if (rw == KSTAT_WRITE)
14408 		return (EACCES);
14409 
14410 	ns = netstack_find_by_stackid(stackid);
14411 	if (ns == NULL)
14412 		return (-1);
14413 	ipst = ns->netstack_ip;
14414 	if (ipst == NULL) {
14415 		netstack_rele(ns);
14416 		return (-1);
14417 	}
14418 	ipkp = (ip_named_kstat_t *)kp->ks_data;
14419 
14420 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14421 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14422 	ill = ILL_START_WALK_V4(&ctx, ipst);
14423 	for (; ill != NULL; ill = ill_next(&ctx, ill))
14424 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14425 	rw_exit(&ipst->ips_ill_g_lock);
14426 
14427 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
14428 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
14429 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
14430 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
14431 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
14432 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14433 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
14434 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
14435 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
14436 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
14437 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
14438 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
14439 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
14440 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
14441 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
14442 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
14443 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
14444 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
14445 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
14446 
14447 	ipkp->routingDiscards.value.ui32 =	0;
14448 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
14449 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
14450 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
14451 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
14452 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
14453 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
14454 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
14455 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
14456 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
14457 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
14458 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
14459 
14460 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
14461 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
14462 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14463 
14464 	netstack_rele(ns);
14465 
14466 	return (0);
14467 }
14468 
14469 static void *
14470 icmp_kstat_init(netstackid_t stackid)
14471 {
14472 	kstat_t	*ksp;
14473 
14474 	icmp_named_kstat_t template = {
14475 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14476 		{ "inErrors",		KSTAT_DATA_UINT32 },
14477 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14478 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14479 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14480 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14481 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14482 		{ "inEchos",		KSTAT_DATA_UINT32 },
14483 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14484 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14485 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14486 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14487 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14488 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14489 		{ "outErrors",		KSTAT_DATA_UINT32 },
14490 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14491 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14492 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14493 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14494 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14495 		{ "outEchos",		KSTAT_DATA_UINT32 },
14496 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14497 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14498 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14499 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14500 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14501 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14502 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14503 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14504 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14505 		{ "outDrops",		KSTAT_DATA_UINT32 },
14506 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14507 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14508 	};
14509 
14510 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14511 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14512 	if (ksp == NULL || ksp->ks_data == NULL)
14513 		return (NULL);
14514 
14515 	bcopy(&template, ksp->ks_data, sizeof (template));
14516 
14517 	ksp->ks_update = icmp_kstat_update;
14518 	ksp->ks_private = (void *)(uintptr_t)stackid;
14519 
14520 	kstat_install(ksp);
14521 	return (ksp);
14522 }
14523 
14524 static void
14525 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14526 {
14527 	if (ksp != NULL) {
14528 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14529 		kstat_delete_netstack(ksp, stackid);
14530 	}
14531 }
14532 
14533 static int
14534 icmp_kstat_update(kstat_t *kp, int rw)
14535 {
14536 	icmp_named_kstat_t *icmpkp;
14537 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14538 	netstack_t	*ns;
14539 	ip_stack_t	*ipst;
14540 
14541 	if ((kp == NULL) || (kp->ks_data == NULL))
14542 		return (EIO);
14543 
14544 	if (rw == KSTAT_WRITE)
14545 		return (EACCES);
14546 
14547 	ns = netstack_find_by_stackid(stackid);
14548 	if (ns == NULL)
14549 		return (-1);
14550 	ipst = ns->netstack_ip;
14551 	if (ipst == NULL) {
14552 		netstack_rele(ns);
14553 		return (-1);
14554 	}
14555 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14556 
14557 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14558 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14559 	icmpkp->inDestUnreachs.value.ui32 =
14560 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14561 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14562 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14563 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14564 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14565 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14566 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14567 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14568 	icmpkp->inTimestampReps.value.ui32 =
14569 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14570 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14571 	icmpkp->inAddrMaskReps.value.ui32 =
14572 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14573 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14574 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14575 	icmpkp->outDestUnreachs.value.ui32 =
14576 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14577 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14578 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14579 	icmpkp->outSrcQuenchs.value.ui32 =
14580 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14581 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14582 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14583 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14584 	icmpkp->outTimestamps.value.ui32 =
14585 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14586 	icmpkp->outTimestampReps.value.ui32 =
14587 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14588 	icmpkp->outAddrMasks.value.ui32 =
14589 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14590 	icmpkp->outAddrMaskReps.value.ui32 =
14591 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14592 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14593 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14594 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14595 	icmpkp->outFragNeeded.value.ui32 =
14596 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14597 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14598 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14599 	icmpkp->inBadRedirects.value.ui32 =
14600 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14601 
14602 	netstack_rele(ns);
14603 	return (0);
14604 }
14605 
14606 /*
14607  * This is the fanout function for raw socket opened for SCTP.  Note
14608  * that it is called after SCTP checks that there is no socket which
14609  * wants a packet.  Then before SCTP handles this out of the blue packet,
14610  * this function is called to see if there is any raw socket for SCTP.
14611  * If there is and it is bound to the correct address, the packet will
14612  * be sent to that socket.  Note that only one raw socket can be bound to
14613  * a port.  This is assured in ipcl_sctp_hash_insert();
14614  */
14615 void
14616 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14617     ip_recv_attr_t *ira)
14618 {
14619 	conn_t		*connp;
14620 	queue_t		*rq;
14621 	boolean_t	secure;
14622 	ill_t		*ill = ira->ira_ill;
14623 	ip_stack_t	*ipst = ill->ill_ipst;
14624 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14625 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14626 	iaflags_t	iraflags = ira->ira_flags;
14627 	ill_t		*rill = ira->ira_rill;
14628 
14629 	secure = iraflags & IRAF_IPSEC_SECURE;
14630 
14631 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14632 	    ira, ipst);
14633 	if (connp == NULL) {
14634 		/*
14635 		 * Although raw sctp is not summed, OOB chunks must be.
14636 		 * Drop the packet here if the sctp checksum failed.
14637 		 */
14638 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14639 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
14640 			freemsg(mp);
14641 			return;
14642 		}
14643 		ira->ira_ill = ira->ira_rill = NULL;
14644 		sctp_ootb_input(mp, ira, ipst);
14645 		ira->ira_ill = ill;
14646 		ira->ira_rill = rill;
14647 		return;
14648 	}
14649 	rq = connp->conn_rq;
14650 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14651 		CONN_DEC_REF(connp);
14652 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14653 		freemsg(mp);
14654 		return;
14655 	}
14656 	if (((iraflags & IRAF_IS_IPV4) ?
14657 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14658 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14659 	    secure) {
14660 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14661 		    ip6h, ira);
14662 		if (mp == NULL) {
14663 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14664 			/* Note that mp is NULL */
14665 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14666 			CONN_DEC_REF(connp);
14667 			return;
14668 		}
14669 	}
14670 
14671 	if (iraflags & IRAF_ICMP_ERROR) {
14672 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14673 	} else {
14674 		ill_t *rill = ira->ira_rill;
14675 
14676 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14677 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14678 		ira->ira_ill = ira->ira_rill = NULL;
14679 		(connp->conn_recv)(connp, mp, NULL, ira);
14680 		ira->ira_ill = ill;
14681 		ira->ira_rill = rill;
14682 	}
14683 	CONN_DEC_REF(connp);
14684 }
14685 
14686 /*
14687  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14688  * header before the ip payload.
14689  */
14690 static void
14691 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14692 {
14693 	int len = (mp->b_wptr - mp->b_rptr);
14694 	mblk_t *ip_mp;
14695 
14696 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14697 	if (is_fp_mp || len != fp_mp_len) {
14698 		if (len > fp_mp_len) {
14699 			/*
14700 			 * fastpath header and ip header in the first mblk
14701 			 */
14702 			mp->b_rptr += fp_mp_len;
14703 		} else {
14704 			/*
14705 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14706 			 * attach the fastpath header before ip header.
14707 			 */
14708 			ip_mp = mp->b_cont;
14709 			freeb(mp);
14710 			mp = ip_mp;
14711 			mp->b_rptr += (fp_mp_len - len);
14712 		}
14713 	} else {
14714 		ip_mp = mp->b_cont;
14715 		freeb(mp);
14716 		mp = ip_mp;
14717 	}
14718 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14719 	freemsg(mp);
14720 }
14721 
14722 /*
14723  * Normal post fragmentation function.
14724  *
14725  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14726  * using the same state machine.
14727  *
14728  * We return an error on failure. In particular we return EWOULDBLOCK
14729  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14730  * (currently by canputnext failure resulting in backenabling from GLD.)
14731  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14732  * indication that they can flow control until ip_wsrv() tells then to restart.
14733  *
14734  * If the nce passed by caller is incomplete, this function
14735  * queues the packet and if necessary, sends ARP request and bails.
14736  * If the Neighbor Cache passed is fully resolved, we simply prepend
14737  * the link-layer header to the packet, do ipsec hw acceleration
14738  * work if necessary, and send the packet out on the wire.
14739  */
14740 /* ARGSUSED6 */
14741 int
14742 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14743     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14744 {
14745 	queue_t		*wq;
14746 	ill_t		*ill = nce->nce_ill;
14747 	ip_stack_t	*ipst = ill->ill_ipst;
14748 	uint64_t	delta;
14749 	boolean_t	isv6 = ill->ill_isv6;
14750 	boolean_t	fp_mp;
14751 	ncec_t		*ncec = nce->nce_common;
14752 	int64_t		now = LBOLT_FASTPATH64;
14753 	boolean_t	is_probe;
14754 
14755 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14756 
14757 	ASSERT(mp != NULL);
14758 	ASSERT(mp->b_datap->db_type == M_DATA);
14759 	ASSERT(pkt_len == msgdsize(mp));
14760 
14761 	/*
14762 	 * If we have already been here and are coming back after ARP/ND.
14763 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14764 	 * in that case since they have seen the packet when it came here
14765 	 * the first time.
14766 	 */
14767 	if (ixaflags & IXAF_NO_TRACE)
14768 		goto sendit;
14769 
14770 	if (ixaflags & IXAF_IS_IPV4) {
14771 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14772 
14773 		ASSERT(!isv6);
14774 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14775 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14776 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14777 			int	error;
14778 
14779 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14780 			    ipst->ips_ipv4firewall_physical_out,
14781 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14782 			DTRACE_PROBE1(ip4__physical__out__end,
14783 			    mblk_t *, mp);
14784 			if (mp == NULL)
14785 				return (error);
14786 
14787 			/* The length could have changed */
14788 			pkt_len = msgdsize(mp);
14789 		}
14790 		if (ipst->ips_ip4_observe.he_interested) {
14791 			/*
14792 			 * Note that for TX the zoneid is the sending
14793 			 * zone, whether or not MLP is in play.
14794 			 * Since the szone argument is the IP zoneid (i.e.,
14795 			 * zero for exclusive-IP zones) and ipobs wants
14796 			 * the system zoneid, we map it here.
14797 			 */
14798 			szone = IP_REAL_ZONEID(szone, ipst);
14799 
14800 			/*
14801 			 * On the outbound path the destination zone will be
14802 			 * unknown as we're sending this packet out on the
14803 			 * wire.
14804 			 */
14805 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14806 			    ill, ipst);
14807 		}
14808 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14809 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14810 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14811 	} else {
14812 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14813 
14814 		ASSERT(isv6);
14815 		ASSERT(pkt_len ==
14816 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14817 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14818 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14819 			int	error;
14820 
14821 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14822 			    ipst->ips_ipv6firewall_physical_out,
14823 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14824 			DTRACE_PROBE1(ip6__physical__out__end,
14825 			    mblk_t *, mp);
14826 			if (mp == NULL)
14827 				return (error);
14828 
14829 			/* The length could have changed */
14830 			pkt_len = msgdsize(mp);
14831 		}
14832 		if (ipst->ips_ip6_observe.he_interested) {
14833 			/* See above */
14834 			szone = IP_REAL_ZONEID(szone, ipst);
14835 
14836 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14837 			    ill, ipst);
14838 		}
14839 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14840 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14841 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14842 	}
14843 
14844 sendit:
14845 	/*
14846 	 * We check the state without a lock because the state can never
14847 	 * move "backwards" to initial or incomplete.
14848 	 */
14849 	switch (ncec->ncec_state) {
14850 	case ND_REACHABLE:
14851 	case ND_STALE:
14852 	case ND_DELAY:
14853 	case ND_PROBE:
14854 		mp = ip_xmit_attach_llhdr(mp, nce);
14855 		if (mp == NULL) {
14856 			/*
14857 			 * ip_xmit_attach_llhdr has increased
14858 			 * ipIfStatsOutDiscards and called ip_drop_output()
14859 			 */
14860 			return (ENOBUFS);
14861 		}
14862 		/*
14863 		 * check if nce_fastpath completed and we tagged on a
14864 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14865 		 */
14866 		fp_mp = (mp->b_datap->db_type == M_DATA);
14867 
14868 		if (fp_mp &&
14869 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14870 			ill_dld_direct_t *idd;
14871 
14872 			idd = &ill->ill_dld_capab->idc_direct;
14873 			/*
14874 			 * Send the packet directly to DLD, where it
14875 			 * may be queued depending on the availability
14876 			 * of transmit resources at the media layer.
14877 			 * Return value should be taken into
14878 			 * account and flow control the TCP.
14879 			 */
14880 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14881 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14882 			    pkt_len);
14883 
14884 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14885 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14886 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14887 			} else {
14888 				uintptr_t cookie;
14889 
14890 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14891 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14892 					if (ixacookie != NULL)
14893 						*ixacookie = cookie;
14894 					return (EWOULDBLOCK);
14895 				}
14896 			}
14897 		} else {
14898 			wq = ill->ill_wq;
14899 
14900 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14901 			    !canputnext(wq)) {
14902 				if (ixacookie != NULL)
14903 					*ixacookie = 0;
14904 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14905 				    nce->nce_fp_mp != NULL ?
14906 				    MBLKL(nce->nce_fp_mp) : 0);
14907 				return (EWOULDBLOCK);
14908 			}
14909 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14910 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14911 			    pkt_len);
14912 			putnext(wq, mp);
14913 		}
14914 
14915 		/*
14916 		 * The rest of this function implements Neighbor Unreachability
14917 		 * detection. Determine if the ncec is eligible for NUD.
14918 		 */
14919 		if (ncec->ncec_flags & NCE_F_NONUD)
14920 			return (0);
14921 
14922 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14923 
14924 		/*
14925 		 * Check for upper layer advice
14926 		 */
14927 		if (ixaflags & IXAF_REACH_CONF) {
14928 			timeout_id_t tid;
14929 
14930 			/*
14931 			 * It should be o.k. to check the state without
14932 			 * a lock here, at most we lose an advice.
14933 			 */
14934 			ncec->ncec_last = TICK_TO_MSEC(now);
14935 			if (ncec->ncec_state != ND_REACHABLE) {
14936 				mutex_enter(&ncec->ncec_lock);
14937 				ncec->ncec_state = ND_REACHABLE;
14938 				tid = ncec->ncec_timeout_id;
14939 				ncec->ncec_timeout_id = 0;
14940 				mutex_exit(&ncec->ncec_lock);
14941 				(void) untimeout(tid);
14942 				if (ip_debug > 2) {
14943 					/* ip1dbg */
14944 					pr_addr_dbg("ip_xmit: state"
14945 					    " for %s changed to"
14946 					    " REACHABLE\n", AF_INET6,
14947 					    &ncec->ncec_addr);
14948 				}
14949 			}
14950 			return (0);
14951 		}
14952 
14953 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14954 		ip1dbg(("ip_xmit: delta = %" PRId64
14955 		    " ill_reachable_time = %d \n", delta,
14956 		    ill->ill_reachable_time));
14957 		if (delta > (uint64_t)ill->ill_reachable_time) {
14958 			mutex_enter(&ncec->ncec_lock);
14959 			switch (ncec->ncec_state) {
14960 			case ND_REACHABLE:
14961 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14962 				/* FALLTHROUGH */
14963 			case ND_STALE:
14964 				/*
14965 				 * ND_REACHABLE is identical to
14966 				 * ND_STALE in this specific case. If
14967 				 * reachable time has expired for this
14968 				 * neighbor (delta is greater than
14969 				 * reachable time), conceptually, the
14970 				 * neighbor cache is no longer in
14971 				 * REACHABLE state, but already in
14972 				 * STALE state.  So the correct
14973 				 * transition here is to ND_DELAY.
14974 				 */
14975 				ncec->ncec_state = ND_DELAY;
14976 				mutex_exit(&ncec->ncec_lock);
14977 				nce_restart_timer(ncec,
14978 				    ipst->ips_delay_first_probe_time);
14979 				if (ip_debug > 3) {
14980 					/* ip2dbg */
14981 					pr_addr_dbg("ip_xmit: state"
14982 					    " for %s changed to"
14983 					    " DELAY\n", AF_INET6,
14984 					    &ncec->ncec_addr);
14985 				}
14986 				break;
14987 			case ND_DELAY:
14988 			case ND_PROBE:
14989 				mutex_exit(&ncec->ncec_lock);
14990 				/* Timers have already started */
14991 				break;
14992 			case ND_UNREACHABLE:
14993 				/*
14994 				 * nce_timer has detected that this ncec
14995 				 * is unreachable and initiated deleting
14996 				 * this ncec.
14997 				 * This is a harmless race where we found the
14998 				 * ncec before it was deleted and have
14999 				 * just sent out a packet using this
15000 				 * unreachable ncec.
15001 				 */
15002 				mutex_exit(&ncec->ncec_lock);
15003 				break;
15004 			default:
15005 				ASSERT(0);
15006 				mutex_exit(&ncec->ncec_lock);
15007 			}
15008 		}
15009 		return (0);
15010 
15011 	case ND_INCOMPLETE:
15012 		/*
15013 		 * the state could have changed since we didn't hold the lock.
15014 		 * Re-verify state under lock.
15015 		 */
15016 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
15017 		mutex_enter(&ncec->ncec_lock);
15018 		if (NCE_ISREACHABLE(ncec)) {
15019 			mutex_exit(&ncec->ncec_lock);
15020 			goto sendit;
15021 		}
15022 		/* queue the packet */
15023 		nce_queue_mp(ncec, mp, is_probe);
15024 		mutex_exit(&ncec->ncec_lock);
15025 		DTRACE_PROBE2(ip__xmit__incomplete,
15026 		    (ncec_t *), ncec, (mblk_t *), mp);
15027 		return (0);
15028 
15029 	case ND_INITIAL:
15030 		/*
15031 		 * State could have changed since we didn't hold the lock, so
15032 		 * re-verify state.
15033 		 */
15034 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
15035 		mutex_enter(&ncec->ncec_lock);
15036 		if (NCE_ISREACHABLE(ncec))  {
15037 			mutex_exit(&ncec->ncec_lock);
15038 			goto sendit;
15039 		}
15040 		nce_queue_mp(ncec, mp, is_probe);
15041 		if (ncec->ncec_state == ND_INITIAL) {
15042 			ncec->ncec_state = ND_INCOMPLETE;
15043 			mutex_exit(&ncec->ncec_lock);
15044 			/*
15045 			 * figure out the source we want to use
15046 			 * and resolve it.
15047 			 */
15048 			ip_ndp_resolve(ncec);
15049 		} else  {
15050 			mutex_exit(&ncec->ncec_lock);
15051 		}
15052 		return (0);
15053 
15054 	case ND_UNREACHABLE:
15055 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
15056 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
15057 		    mp, ill);
15058 		freemsg(mp);
15059 		return (0);
15060 
15061 	default:
15062 		ASSERT(0);
15063 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
15064 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
15065 		    mp, ill);
15066 		freemsg(mp);
15067 		return (ENETUNREACH);
15068 	}
15069 }
15070 
15071 /*
15072  * Return B_TRUE if the buffers differ in length or content.
15073  * This is used for comparing extension header buffers.
15074  * Note that an extension header would be declared different
15075  * even if all that changed was the next header value in that header i.e.
15076  * what really changed is the next extension header.
15077  */
15078 boolean_t
15079 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
15080     uint_t blen)
15081 {
15082 	if (!b_valid)
15083 		blen = 0;
15084 
15085 	if (alen != blen)
15086 		return (B_TRUE);
15087 	if (alen == 0)
15088 		return (B_FALSE);	/* Both zero length */
15089 	return (bcmp(abuf, bbuf, alen));
15090 }
15091 
15092 /*
15093  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
15094  * Return B_FALSE if memory allocation fails - don't change any state!
15095  */
15096 boolean_t
15097 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
15098     const void *src, uint_t srclen)
15099 {
15100 	void *dst;
15101 
15102 	if (!src_valid)
15103 		srclen = 0;
15104 
15105 	ASSERT(*dstlenp == 0);
15106 	if (src != NULL && srclen != 0) {
15107 		dst = mi_alloc(srclen, BPRI_MED);
15108 		if (dst == NULL)
15109 			return (B_FALSE);
15110 	} else {
15111 		dst = NULL;
15112 	}
15113 	if (*dstp != NULL)
15114 		mi_free(*dstp);
15115 	*dstp = dst;
15116 	*dstlenp = dst == NULL ? 0 : srclen;
15117 	return (B_TRUE);
15118 }
15119 
15120 /*
15121  * Replace what is in *dst, *dstlen with the source.
15122  * Assumes ip_allocbuf has already been called.
15123  */
15124 void
15125 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
15126     const void *src, uint_t srclen)
15127 {
15128 	if (!src_valid)
15129 		srclen = 0;
15130 
15131 	ASSERT(*dstlenp == srclen);
15132 	if (src != NULL && srclen != 0)
15133 		bcopy(src, *dstp, srclen);
15134 }
15135 
15136 /*
15137  * Free the storage pointed to by the members of an ip_pkt_t.
15138  */
15139 void
15140 ip_pkt_free(ip_pkt_t *ipp)
15141 {
15142 	uint_t	fields = ipp->ipp_fields;
15143 
15144 	if (fields & IPPF_HOPOPTS) {
15145 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15146 		ipp->ipp_hopopts = NULL;
15147 		ipp->ipp_hopoptslen = 0;
15148 	}
15149 	if (fields & IPPF_RTHDRDSTOPTS) {
15150 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
15151 		ipp->ipp_rthdrdstopts = NULL;
15152 		ipp->ipp_rthdrdstoptslen = 0;
15153 	}
15154 	if (fields & IPPF_DSTOPTS) {
15155 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15156 		ipp->ipp_dstopts = NULL;
15157 		ipp->ipp_dstoptslen = 0;
15158 	}
15159 	if (fields & IPPF_RTHDR) {
15160 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15161 		ipp->ipp_rthdr = NULL;
15162 		ipp->ipp_rthdrlen = 0;
15163 	}
15164 	if (fields & IPPF_IPV4_OPTIONS) {
15165 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
15166 		ipp->ipp_ipv4_options = NULL;
15167 		ipp->ipp_ipv4_options_len = 0;
15168 	}
15169 	if (fields & IPPF_LABEL_V4) {
15170 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
15171 		ipp->ipp_label_v4 = NULL;
15172 		ipp->ipp_label_len_v4 = 0;
15173 	}
15174 	if (fields & IPPF_LABEL_V6) {
15175 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
15176 		ipp->ipp_label_v6 = NULL;
15177 		ipp->ipp_label_len_v6 = 0;
15178 	}
15179 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15180 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
15181 }
15182 
15183 /*
15184  * Copy from src to dst and allocate as needed.
15185  * Returns zero or ENOMEM.
15186  *
15187  * The caller must initialize dst to zero.
15188  */
15189 int
15190 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
15191 {
15192 	uint_t	fields = src->ipp_fields;
15193 
15194 	/* Start with fields that don't require memory allocation */
15195 	dst->ipp_fields = fields &
15196 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15197 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
15198 
15199 	dst->ipp_addr = src->ipp_addr;
15200 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
15201 	dst->ipp_hoplimit = src->ipp_hoplimit;
15202 	dst->ipp_tclass = src->ipp_tclass;
15203 	dst->ipp_type_of_service = src->ipp_type_of_service;
15204 
15205 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15206 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
15207 		return (0);
15208 
15209 	if (fields & IPPF_HOPOPTS) {
15210 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
15211 		if (dst->ipp_hopopts == NULL) {
15212 			ip_pkt_free(dst);
15213 			return (ENOMEM);
15214 		}
15215 		dst->ipp_fields |= IPPF_HOPOPTS;
15216 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
15217 		    src->ipp_hopoptslen);
15218 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
15219 	}
15220 	if (fields & IPPF_RTHDRDSTOPTS) {
15221 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
15222 		    kmflag);
15223 		if (dst->ipp_rthdrdstopts == NULL) {
15224 			ip_pkt_free(dst);
15225 			return (ENOMEM);
15226 		}
15227 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
15228 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
15229 		    src->ipp_rthdrdstoptslen);
15230 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
15231 	}
15232 	if (fields & IPPF_DSTOPTS) {
15233 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
15234 		if (dst->ipp_dstopts == NULL) {
15235 			ip_pkt_free(dst);
15236 			return (ENOMEM);
15237 		}
15238 		dst->ipp_fields |= IPPF_DSTOPTS;
15239 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
15240 		    src->ipp_dstoptslen);
15241 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
15242 	}
15243 	if (fields & IPPF_RTHDR) {
15244 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
15245 		if (dst->ipp_rthdr == NULL) {
15246 			ip_pkt_free(dst);
15247 			return (ENOMEM);
15248 		}
15249 		dst->ipp_fields |= IPPF_RTHDR;
15250 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
15251 		    src->ipp_rthdrlen);
15252 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
15253 	}
15254 	if (fields & IPPF_IPV4_OPTIONS) {
15255 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
15256 		    kmflag);
15257 		if (dst->ipp_ipv4_options == NULL) {
15258 			ip_pkt_free(dst);
15259 			return (ENOMEM);
15260 		}
15261 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
15262 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
15263 		    src->ipp_ipv4_options_len);
15264 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
15265 	}
15266 	if (fields & IPPF_LABEL_V4) {
15267 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
15268 		if (dst->ipp_label_v4 == NULL) {
15269 			ip_pkt_free(dst);
15270 			return (ENOMEM);
15271 		}
15272 		dst->ipp_fields |= IPPF_LABEL_V4;
15273 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
15274 		    src->ipp_label_len_v4);
15275 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
15276 	}
15277 	if (fields & IPPF_LABEL_V6) {
15278 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
15279 		if (dst->ipp_label_v6 == NULL) {
15280 			ip_pkt_free(dst);
15281 			return (ENOMEM);
15282 		}
15283 		dst->ipp_fields |= IPPF_LABEL_V6;
15284 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
15285 		    src->ipp_label_len_v6);
15286 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
15287 	}
15288 	if (fields & IPPF_FRAGHDR) {
15289 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
15290 		if (dst->ipp_fraghdr == NULL) {
15291 			ip_pkt_free(dst);
15292 			return (ENOMEM);
15293 		}
15294 		dst->ipp_fields |= IPPF_FRAGHDR;
15295 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
15296 		    src->ipp_fraghdrlen);
15297 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
15298 	}
15299 	return (0);
15300 }
15301 
15302 /*
15303  * Returns INADDR_ANY if no source route
15304  */
15305 ipaddr_t
15306 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
15307 {
15308 	ipaddr_t	nexthop = INADDR_ANY;
15309 	ipoptp_t	opts;
15310 	uchar_t		*opt;
15311 	uint8_t		optval;
15312 	uint8_t		optlen;
15313 	uint32_t	totallen;
15314 
15315 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15316 		return (INADDR_ANY);
15317 
15318 	totallen = ipp->ipp_ipv4_options_len;
15319 	if (totallen & 0x3)
15320 		return (INADDR_ANY);
15321 
15322 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15323 	    optval != IPOPT_EOL;
15324 	    optval = ipoptp_next(&opts)) {
15325 		opt = opts.ipoptp_cur;
15326 		switch (optval) {
15327 			uint8_t off;
15328 		case IPOPT_SSRR:
15329 		case IPOPT_LSRR:
15330 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15331 				break;
15332 			}
15333 			optlen = opts.ipoptp_len;
15334 			off = opt[IPOPT_OFFSET];
15335 			off--;
15336 			if (optlen < IP_ADDR_LEN ||
15337 			    off > optlen - IP_ADDR_LEN) {
15338 				/* End of source route */
15339 				break;
15340 			}
15341 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
15342 			if (nexthop == htonl(INADDR_LOOPBACK)) {
15343 				/* Ignore */
15344 				nexthop = INADDR_ANY;
15345 				break;
15346 			}
15347 			break;
15348 		}
15349 	}
15350 	return (nexthop);
15351 }
15352 
15353 /*
15354  * Reverse a source route.
15355  */
15356 void
15357 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
15358 {
15359 	ipaddr_t	tmp;
15360 	ipoptp_t	opts;
15361 	uchar_t		*opt;
15362 	uint8_t		optval;
15363 	uint32_t	totallen;
15364 
15365 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15366 		return;
15367 
15368 	totallen = ipp->ipp_ipv4_options_len;
15369 	if (totallen & 0x3)
15370 		return;
15371 
15372 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15373 	    optval != IPOPT_EOL;
15374 	    optval = ipoptp_next(&opts)) {
15375 		uint8_t off1, off2;
15376 
15377 		opt = opts.ipoptp_cur;
15378 		switch (optval) {
15379 		case IPOPT_SSRR:
15380 		case IPOPT_LSRR:
15381 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15382 				break;
15383 			}
15384 			off1 = IPOPT_MINOFF_SR - 1;
15385 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15386 			while (off2 > off1) {
15387 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15388 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15389 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15390 				off2 -= IP_ADDR_LEN;
15391 				off1 += IP_ADDR_LEN;
15392 			}
15393 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15394 			break;
15395 		}
15396 	}
15397 }
15398 
15399 /*
15400  * Returns NULL if no routing header
15401  */
15402 in6_addr_t *
15403 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15404 {
15405 	in6_addr_t	*nexthop = NULL;
15406 	ip6_rthdr0_t	*rthdr;
15407 
15408 	if (!(ipp->ipp_fields & IPPF_RTHDR))
15409 		return (NULL);
15410 
15411 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15412 	if (rthdr->ip6r0_segleft == 0)
15413 		return (NULL);
15414 
15415 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15416 	return (nexthop);
15417 }
15418 
15419 zoneid_t
15420 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15421     zoneid_t lookup_zoneid)
15422 {
15423 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15424 	ire_t		*ire;
15425 	int		ire_flags = MATCH_IRE_TYPE;
15426 	zoneid_t	zoneid = ALL_ZONES;
15427 
15428 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15429 		return (ALL_ZONES);
15430 
15431 	if (lookup_zoneid != ALL_ZONES)
15432 		ire_flags |= MATCH_IRE_ZONEONLY;
15433 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15434 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15435 	if (ire != NULL) {
15436 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15437 		ire_refrele(ire);
15438 	}
15439 	return (zoneid);
15440 }
15441 
15442 zoneid_t
15443 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15444     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15445 {
15446 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15447 	ire_t		*ire;
15448 	int		ire_flags = MATCH_IRE_TYPE;
15449 	zoneid_t	zoneid = ALL_ZONES;
15450 
15451 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15452 		return (ALL_ZONES);
15453 
15454 	if (IN6_IS_ADDR_LINKLOCAL(addr))
15455 		ire_flags |= MATCH_IRE_ILL;
15456 
15457 	if (lookup_zoneid != ALL_ZONES)
15458 		ire_flags |= MATCH_IRE_ZONEONLY;
15459 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15460 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15461 	if (ire != NULL) {
15462 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15463 		ire_refrele(ire);
15464 	}
15465 	return (zoneid);
15466 }
15467 
15468 /*
15469  * IP obserability hook support functions.
15470  */
15471 static void
15472 ipobs_init(ip_stack_t *ipst)
15473 {
15474 	netid_t id;
15475 
15476 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15477 
15478 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15479 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15480 
15481 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15482 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15483 }
15484 
15485 static void
15486 ipobs_fini(ip_stack_t *ipst)
15487 {
15488 
15489 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15490 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15491 }
15492 
15493 /*
15494  * hook_pkt_observe_t is composed in network byte order so that the
15495  * entire mblk_t chain handed into hook_run can be used as-is.
15496  * The caveat is that use of the fields, such as the zone fields,
15497  * requires conversion into host byte order first.
15498  */
15499 void
15500 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15501     const ill_t *ill, ip_stack_t *ipst)
15502 {
15503 	hook_pkt_observe_t *hdr;
15504 	uint64_t grifindex;
15505 	mblk_t *imp;
15506 
15507 	imp = allocb(sizeof (*hdr), BPRI_HI);
15508 	if (imp == NULL)
15509 		return;
15510 
15511 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15512 	/*
15513 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15514 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15515 	 */
15516 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15517 	imp->b_cont = mp;
15518 
15519 	ASSERT(DB_TYPE(mp) == M_DATA);
15520 
15521 	if (IS_UNDER_IPMP(ill))
15522 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15523 	else
15524 		grifindex = 0;
15525 
15526 	hdr->hpo_version = 1;
15527 	hdr->hpo_htype = htons(htype);
15528 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15529 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15530 	hdr->hpo_grifindex = htonl(grifindex);
15531 	hdr->hpo_zsrc = htonl(zsrc);
15532 	hdr->hpo_zdst = htonl(zdst);
15533 	hdr->hpo_pkt = imp;
15534 	hdr->hpo_ctx = ipst->ips_netstack;
15535 
15536 	if (ill->ill_isv6) {
15537 		hdr->hpo_family = AF_INET6;
15538 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15539 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15540 	} else {
15541 		hdr->hpo_family = AF_INET;
15542 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15543 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15544 	}
15545 
15546 	imp->b_cont = NULL;
15547 	freemsg(imp);
15548 }
15549 
15550 /*
15551  * Utility routine that checks if `v4srcp' is a valid address on underlying
15552  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15553  * associated with `v4srcp' on success.  NOTE: if this is not called from
15554  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15555  * group during or after this lookup.
15556  */
15557 boolean_t
15558 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15559 {
15560 	ipif_t *ipif;
15561 
15562 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15563 	if (ipif != NULL) {
15564 		if (ipifp != NULL)
15565 			*ipifp = ipif;
15566 		else
15567 			ipif_refrele(ipif);
15568 		return (B_TRUE);
15569 	}
15570 
15571 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15572 	    *v4srcp));
15573 	return (B_FALSE);
15574 }
15575