xref: /titanic_44/usr/src/uts/common/inet/ip/ip.c (revision 49959095a0317f217df367aaa3073887685b919a)
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 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
830 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
831 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
832 	{  0,	1,	1,	"icmp_accept_clear_messages" },
833 	{  0,	1,	1,	"igmp_accept_clear_messages" },
834 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
835 				"ip_ndp_delay_first_probe_time"},
836 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
837 				"ip_ndp_max_unicast_solicit"},
838 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
839 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
840 	{  0,	1,	0,	"ip6_forward_src_routed"},
841 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
842 	{  0,	1,	1,	"ip6_send_redirects"},
843 	{  0,	1,	0,	"ip6_ignore_redirect" },
844 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
845 
846 	{  0,	2,	2,	"ip_src_check" },
847 
848 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
849 
850 	{  0,	1,	1,	"pim_accept_clear_messages" },
851 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
852 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
853 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
854 	{  0,	15,	0,	"ip_policy_mask" },
855 	{  0,	2,	2,	"ip_ecmp_behavior" },
856 	{  0,	255,	1,	"ip_multirt_ttl" },
857 	{  0,	3600,	60,	"ip_ire_badcnt_lifetime" },	/* In seconds */
858 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
859 	{  0,	1000,	1,	"ip_max_temp_defend" },
860 	/*
861 	 * when a conflict of an active address is detected,
862 	 * defend up to ip_max_defend times, within any
863 	 * ip_defend_interval span.
864 	 */
865 	{  0,	1000,	3,	"ip_max_defend" },
866 	{  0,	999999,	30,	"ip_defend_interval" },
867 	{  0,	3600000, 300000, "ip_dup_recovery" },
868 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
869 	{  0,	1,	1,	"ip_lso_outbound" },
870 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
871 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
872 #ifdef DEBUG
873 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
874 #else
875 	{  0,	0,	0,	"" },
876 #endif
877 	/* delay before sending first probe: */
878 	{  0,	20000,	1000,	"arp_probe_delay" },
879 	{  0,	20000,	100,	"arp_fastprobe_delay" },
880 	/* interval at which DAD probes are sent: */
881 	{ 10,	20000,	1500,	"arp_probe_interval" },
882 	{ 10,	20000,	150,	"arp_fastprobe_interval" },
883 	/* setting probe count to 0 will disable ARP probing for DAD. */
884 	{  0,	20,	3,	"arp_probe_count" },
885 	{  0,	20,	3,	"arp_fastprobe_count" },
886 
887 	{  0,	3600000, 15000,	"ipv4_dad_announce_interval"},
888 	{  0,	3600000, 15000,	"ipv6_dad_announce_interval"},
889 	/*
890 	 * Rate limiting parameters for DAD defense used in
891 	 * ill_defend_rate_limit():
892 	 * defend_rate : pkts/hour permitted
893 	 * defend_interval : time that can elapse before we send out a
894 	 *			DAD defense.
895 	 * defend_period: denominator for defend_rate (in seconds).
896 	 */
897 	{  0,	3600000, 300000,	"arp_defend_interval"},
898 	{  0,	20000, 100,		"arp_defend_rate"},
899 	{  0,	3600000, 300000,	"ndp_defend_interval"},
900 	{  0,	20000, 100,		"ndp_defend_rate"},
901 	{  5,	86400,	3600,		"arp_defend_period"},
902 	{  5,	86400,	3600,		"ndp_defend_period"},
903 	{  0,	1,	1,		"ipv4_icmp_return_pmtu" },
904 	{  0,	1,	1,		"ipv6_icmp_return_pmtu" },
905 	/*
906 	 * publish count/interval values used to announce local addresses
907 	 * for IPv4, IPv6.
908 	 */
909 	{  1,	20,	5,	"ip_arp_publish_count" },
910 	{  1000, 20000,	2000,	"ip_arp_publish_interval" },
911 };
912 
913 /*
914  * Extended NDP table
915  * The addresses for the first two are filled in to be ips_ip_g_forward
916  * and ips_ipv6_forward at init time.
917  */
918 static ipndp_t	lcl_ndp_arr[] = {
919 	/* getf			setf		data			name */
920 #define	IPNDP_IP_FORWARDING_OFFSET	0
921 	{  ip_param_generic_get,	ip_forward_set,	NULL,
922 	    "ip_forwarding" },
923 #define	IPNDP_IP6_FORWARDING_OFFSET	1
924 	{  ip_param_generic_get,	ip_forward_set,	NULL,
925 	    "ip6_forwarding" },
926 	{ ip_param_generic_get, ip_input_proc_set,
927 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
928 	{ ip_param_generic_get, ip_int_set,
929 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
930 #define	IPNDP_CGTP_FILTER_OFFSET	4
931 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
932 	    "ip_cgtp_filter" },
933 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
934 	    "ip_debug" },
935 };
936 
937 /*
938  * Table of IP ioctls encoding the various properties of the ioctl and
939  * indexed based on the last byte of the ioctl command. Occasionally there
940  * is a clash, and there is more than 1 ioctl with the same last byte.
941  * In such a case 1 ioctl is encoded in the ndx table and the remaining
942  * ioctls are encoded in the misc table. An entry in the ndx table is
943  * retrieved by indexing on the last byte of the ioctl command and comparing
944  * the ioctl command with the value in the ndx table. In the event of a
945  * mismatch the misc table is then searched sequentially for the desired
946  * ioctl command.
947  *
948  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
949  */
950 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
951 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
961 
962 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
963 			MISC_CMD, ip_siocaddrt, NULL },
964 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
965 			MISC_CMD, ip_siocdelrt, NULL },
966 
967 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
968 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
969 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
970 			IF_CMD, ip_sioctl_get_addr, NULL },
971 
972 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
973 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
974 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
975 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
976 
977 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
978 			IPI_PRIV | IPI_WR,
979 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
980 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
981 			IPI_MODOK | IPI_GET_CMD,
982 			IF_CMD, ip_sioctl_get_flags, NULL },
983 
984 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
985 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
986 
987 	/* copyin size cannot be coded for SIOCGIFCONF */
988 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
989 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
990 
991 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
992 			IF_CMD, ip_sioctl_mtu, NULL },
993 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
994 			IF_CMD, ip_sioctl_get_mtu, NULL },
995 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
996 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
997 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
998 			IF_CMD, ip_sioctl_brdaddr, NULL },
999 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1000 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1001 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1002 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1003 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1004 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1005 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1006 			IF_CMD, ip_sioctl_metric, NULL },
1007 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1008 
1009 	/* See 166-168 below for extended SIOC*XARP ioctls */
1010 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1011 			ARP_CMD, ip_sioctl_arp, NULL },
1012 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1013 			ARP_CMD, ip_sioctl_arp, NULL },
1014 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1015 			ARP_CMD, ip_sioctl_arp, NULL },
1016 
1017 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 
1039 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1040 			MISC_CMD, if_unitsel, if_unitsel_restart },
1041 
1042 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1062 			IPI_PRIV | IPI_WR | IPI_MODOK,
1063 			IF_CMD, ip_sioctl_sifname, NULL },
1064 
1065 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 
1079 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1080 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1081 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1082 			IF_CMD, ip_sioctl_get_muxid, NULL },
1083 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1084 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1085 
1086 	/* Both if and lif variants share same func */
1087 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1088 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1089 	/* Both if and lif variants share same func */
1090 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1091 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1092 
1093 	/* copyin size cannot be coded for SIOCGIFCONF */
1094 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1095 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1096 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 
1114 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1115 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1116 			ip_sioctl_removeif_restart },
1117 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1118 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1119 			LIF_CMD, ip_sioctl_addif, NULL },
1120 #define	SIOCLIFADDR_NDX 112
1121 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1122 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1123 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1124 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1125 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1126 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1127 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1128 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1129 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1130 			IPI_PRIV | IPI_WR,
1131 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1132 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1133 			IPI_GET_CMD | IPI_MODOK,
1134 			LIF_CMD, ip_sioctl_get_flags, NULL },
1135 
1136 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 
1139 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1140 			ip_sioctl_get_lifconf, NULL },
1141 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1142 			LIF_CMD, ip_sioctl_mtu, NULL },
1143 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1144 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1145 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1146 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1147 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1148 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1149 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1150 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1151 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1152 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1153 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1154 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1155 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1156 			LIF_CMD, ip_sioctl_metric, NULL },
1157 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1158 			IPI_PRIV | IPI_WR | IPI_MODOK,
1159 			LIF_CMD, ip_sioctl_slifname,
1160 			ip_sioctl_slifname_restart },
1161 
1162 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1163 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1164 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1165 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1166 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1167 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1168 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1169 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1170 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1171 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1172 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1173 			LIF_CMD, ip_sioctl_token, NULL },
1174 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1175 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1176 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1177 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1178 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1179 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1180 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1181 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1182 
1183 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1184 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1185 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1186 			LIF_CMD, ip_siocdelndp_v6, NULL },
1187 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1188 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1189 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1190 			LIF_CMD, ip_siocsetndp_v6, NULL },
1191 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1192 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1193 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1194 			MISC_CMD, ip_sioctl_tonlink, NULL },
1195 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1196 			MISC_CMD, ip_sioctl_tmysite, NULL },
1197 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1200 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1201 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1202 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1203 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1204 
1205 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1206 
1207 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1208 			LIF_CMD, ip_sioctl_get_binding, NULL },
1209 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1210 			IPI_PRIV | IPI_WR,
1211 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1212 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1213 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1214 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1215 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1216 
1217 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1218 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1219 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 
1222 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 
1224 	/* These are handled in ip_sioctl_copyin_setup itself */
1225 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1226 			MISC_CMD, NULL, NULL },
1227 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1228 			MISC_CMD, NULL, NULL },
1229 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1230 
1231 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1232 			ip_sioctl_get_lifconf, NULL },
1233 
1234 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1235 			XARP_CMD, ip_sioctl_arp, NULL },
1236 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1237 			XARP_CMD, ip_sioctl_arp, NULL },
1238 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1239 			XARP_CMD, ip_sioctl_arp, NULL },
1240 
1241 	/* SIOCPOPSOCKFS is not handled by IP */
1242 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1243 
1244 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1245 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1246 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1247 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1248 			ip_sioctl_slifzone_restart },
1249 	/* 172-174 are SCTP ioctls and not handled by IP */
1250 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1251 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1252 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1253 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1254 			IPI_GET_CMD, LIF_CMD,
1255 			ip_sioctl_get_lifusesrc, 0 },
1256 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1257 			IPI_PRIV | IPI_WR,
1258 			LIF_CMD, ip_sioctl_slifusesrc,
1259 			NULL },
1260 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1261 			ip_sioctl_get_lifsrcof, NULL },
1262 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1263 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1264 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1265 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1266 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1267 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1268 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1269 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1270 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1271 	/* SIOCSENABLESDP is handled by SDP */
1272 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1273 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1274 	/* 185 */ { IPI_DONTCARE /* SIOCGIFHWADDR */, 0, 0, 0, NULL, NULL },
1275 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1276 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1277 			ip_sioctl_ilb_cmd, NULL },
1278 };
1279 
1280 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1281 
1282 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1283 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1284 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1285 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1286 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1287 	{ ND_GET,	0, 0, 0, NULL, NULL },
1288 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1289 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1290 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1291 		MISC_CMD, mrt_ioctl},
1292 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1293 		MISC_CMD, mrt_ioctl},
1294 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1295 		MISC_CMD, mrt_ioctl}
1296 };
1297 
1298 int ip_misc_ioctl_count =
1299     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1300 
1301 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1302 					/* Settable in /etc/system */
1303 /* Defined in ip_ire.c */
1304 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1305 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1306 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1307 
1308 static nv_t	ire_nv_arr[] = {
1309 	{ IRE_BROADCAST, "BROADCAST" },
1310 	{ IRE_LOCAL, "LOCAL" },
1311 	{ IRE_LOOPBACK, "LOOPBACK" },
1312 	{ IRE_DEFAULT, "DEFAULT" },
1313 	{ IRE_PREFIX, "PREFIX" },
1314 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1315 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1316 	{ IRE_IF_CLONE, "IF_CLONE" },
1317 	{ IRE_HOST, "HOST" },
1318 	{ IRE_MULTICAST, "MULTICAST" },
1319 	{ IRE_NOROUTE, "NOROUTE" },
1320 	{ 0 }
1321 };
1322 
1323 nv_t	*ire_nv_tbl = ire_nv_arr;
1324 
1325 /* Simple ICMP IP Header Template */
1326 static ipha_t icmp_ipha = {
1327 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1328 };
1329 
1330 struct module_info ip_mod_info = {
1331 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1332 	IP_MOD_LOWAT
1333 };
1334 
1335 /*
1336  * Duplicate static symbols within a module confuses mdb; so we avoid the
1337  * problem by making the symbols here distinct from those in udp.c.
1338  */
1339 
1340 /*
1341  * Entry points for IP as a device and as a module.
1342  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1343  */
1344 static struct qinit iprinitv4 = {
1345 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1346 	&ip_mod_info
1347 };
1348 
1349 struct qinit iprinitv6 = {
1350 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1351 	&ip_mod_info
1352 };
1353 
1354 static struct qinit ipwinit = {
1355 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1356 	&ip_mod_info
1357 };
1358 
1359 static struct qinit iplrinit = {
1360 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1361 	&ip_mod_info
1362 };
1363 
1364 static struct qinit iplwinit = {
1365 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1366 	&ip_mod_info
1367 };
1368 
1369 /* For AF_INET aka /dev/ip */
1370 struct streamtab ipinfov4 = {
1371 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1372 };
1373 
1374 /* For AF_INET6 aka /dev/ip6 */
1375 struct streamtab ipinfov6 = {
1376 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1377 };
1378 
1379 #ifdef	DEBUG
1380 boolean_t skip_sctp_cksum = B_FALSE;
1381 #endif
1382 
1383 /*
1384  * Generate an ICMP fragmentation needed message.
1385  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1386  * constructed by the caller.
1387  */
1388 void
1389 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1390 {
1391 	icmph_t	icmph;
1392 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1393 
1394 	mp = icmp_pkt_err_ok(mp, ira);
1395 	if (mp == NULL)
1396 		return;
1397 
1398 	bzero(&icmph, sizeof (icmph_t));
1399 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1400 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1401 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1402 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1403 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1404 
1405 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1406 }
1407 
1408 /*
1409  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1410  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1411  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1412  * Likewise, if the ICMP error is misformed (too short, etc), then it
1413  * returns NULL. The caller uses this to determine whether or not to send
1414  * to raw sockets.
1415  *
1416  * All error messages are passed to the matching transport stream.
1417  *
1418  * The following cases are handled by icmp_inbound:
1419  * 1) It needs to send a reply back and possibly delivering it
1420  *    to the "interested" upper clients.
1421  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1422  * 3) It needs to change some values in IP only.
1423  * 4) It needs to change some values in IP and upper layers e.g TCP
1424  *    by delivering an error to the upper layers.
1425  *
1426  * We handle the above three cases in the context of IPsec in the
1427  * following way :
1428  *
1429  * 1) Send the reply back in the same way as the request came in.
1430  *    If it came in encrypted, it goes out encrypted. If it came in
1431  *    clear, it goes out in clear. Thus, this will prevent chosen
1432  *    plain text attack.
1433  * 2) The client may or may not expect things to come in secure.
1434  *    If it comes in secure, the policy constraints are checked
1435  *    before delivering it to the upper layers. If it comes in
1436  *    clear, ipsec_inbound_accept_clear will decide whether to
1437  *    accept this in clear or not. In both the cases, if the returned
1438  *    message (IP header + 8 bytes) that caused the icmp message has
1439  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1440  *    sending up. If there are only 8 bytes of returned message, then
1441  *    upper client will not be notified.
1442  * 3) Check with global policy to see whether it matches the constaints.
1443  *    But this will be done only if icmp_accept_messages_in_clear is
1444  *    zero.
1445  * 4) If we need to change both in IP and ULP, then the decision taken
1446  *    while affecting the values in IP and while delivering up to TCP
1447  *    should be the same.
1448  *
1449  * 	There are two cases.
1450  *
1451  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1452  *	   failed), we will not deliver it to the ULP, even though they
1453  *	   are *willing* to accept in *clear*. This is fine as our global
1454  *	   disposition to icmp messages asks us reject the datagram.
1455  *
1456  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1457  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1458  *	   to deliver it to ULP (policy failed), it can lead to
1459  *	   consistency problems. The cases known at this time are
1460  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1461  *	   values :
1462  *
1463  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1464  *	     and Upper layer rejects. Then the communication will
1465  *	     come to a stop. This is solved by making similar decisions
1466  *	     at both levels. Currently, when we are unable to deliver
1467  *	     to the Upper Layer (due to policy failures) while IP has
1468  *	     adjusted dce_pmtu, the next outbound datagram would
1469  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1470  *	     will be with the right level of protection. Thus the right
1471  *	     value will be communicated even if we are not able to
1472  *	     communicate when we get from the wire initially. But this
1473  *	     assumes there would be at least one outbound datagram after
1474  *	     IP has adjusted its dce_pmtu value. To make things
1475  *	     simpler, we accept in clear after the validation of
1476  *	     AH/ESP headers.
1477  *
1478  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1479  *	     upper layer depending on the level of protection the upper
1480  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1481  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1482  *	     should be accepted in clear when the Upper layer expects secure.
1483  *	     Thus the communication may get aborted by some bad ICMP
1484  *	     packets.
1485  */
1486 mblk_t *
1487 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1488 {
1489 	icmph_t		*icmph;
1490 	ipha_t		*ipha;		/* Outer header */
1491 	int		ip_hdr_length;	/* Outer header length */
1492 	boolean_t	interested;
1493 	ipif_t		*ipif;
1494 	uint32_t	ts;
1495 	uint32_t	*tsp;
1496 	timestruc_t	now;
1497 	ill_t		*ill = ira->ira_ill;
1498 	ip_stack_t	*ipst = ill->ill_ipst;
1499 	zoneid_t	zoneid = ira->ira_zoneid;
1500 	int		len_needed;
1501 	mblk_t		*mp_ret = NULL;
1502 
1503 	ipha = (ipha_t *)mp->b_rptr;
1504 
1505 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1506 
1507 	ip_hdr_length = ira->ira_ip_hdr_length;
1508 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1509 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1510 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1511 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1512 			freemsg(mp);
1513 			return (NULL);
1514 		}
1515 		/* Last chance to get real. */
1516 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1517 		if (ipha == NULL) {
1518 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1519 			freemsg(mp);
1520 			return (NULL);
1521 		}
1522 	}
1523 
1524 	/* The IP header will always be a multiple of four bytes */
1525 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1526 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1527 	    icmph->icmph_code));
1528 
1529 	/*
1530 	 * We will set "interested" to "true" if we should pass a copy to
1531 	 * the transport or if we handle the packet locally.
1532 	 */
1533 	interested = B_FALSE;
1534 	switch (icmph->icmph_type) {
1535 	case ICMP_ECHO_REPLY:
1536 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1537 		break;
1538 	case ICMP_DEST_UNREACHABLE:
1539 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1540 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1541 		interested = B_TRUE;	/* Pass up to transport */
1542 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1543 		break;
1544 	case ICMP_SOURCE_QUENCH:
1545 		interested = B_TRUE;	/* Pass up to transport */
1546 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1547 		break;
1548 	case ICMP_REDIRECT:
1549 		if (!ipst->ips_ip_ignore_redirect)
1550 			interested = B_TRUE;
1551 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1552 		break;
1553 	case ICMP_ECHO_REQUEST:
1554 		/*
1555 		 * Whether to respond to echo requests that come in as IP
1556 		 * broadcasts or as IP multicast is subject to debate
1557 		 * (what isn't?).  We aim to please, you pick it.
1558 		 * Default is do it.
1559 		 */
1560 		if (ira->ira_flags & IRAF_MULTICAST) {
1561 			/* multicast: respond based on tunable */
1562 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1563 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1564 			/* broadcast: respond based on tunable */
1565 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1566 		} else {
1567 			/* unicast: always respond */
1568 			interested = B_TRUE;
1569 		}
1570 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1571 		if (!interested) {
1572 			/* We never pass these to RAW sockets */
1573 			freemsg(mp);
1574 			return (NULL);
1575 		}
1576 
1577 		/* Check db_ref to make sure we can modify the packet. */
1578 		if (mp->b_datap->db_ref > 1) {
1579 			mblk_t	*mp1;
1580 
1581 			mp1 = copymsg(mp);
1582 			freemsg(mp);
1583 			if (!mp1) {
1584 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1585 				return (NULL);
1586 			}
1587 			mp = mp1;
1588 			ipha = (ipha_t *)mp->b_rptr;
1589 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1590 		}
1591 		icmph->icmph_type = ICMP_ECHO_REPLY;
1592 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1593 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1594 		return (NULL);
1595 
1596 	case ICMP_ROUTER_ADVERTISEMENT:
1597 	case ICMP_ROUTER_SOLICITATION:
1598 		break;
1599 	case ICMP_TIME_EXCEEDED:
1600 		interested = B_TRUE;	/* Pass up to transport */
1601 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1602 		break;
1603 	case ICMP_PARAM_PROBLEM:
1604 		interested = B_TRUE;	/* Pass up to transport */
1605 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1606 		break;
1607 	case ICMP_TIME_STAMP_REQUEST:
1608 		/* Response to Time Stamp Requests is local policy. */
1609 		if (ipst->ips_ip_g_resp_to_timestamp) {
1610 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1611 				interested =
1612 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1613 			else
1614 				interested = B_TRUE;
1615 		}
1616 		if (!interested) {
1617 			/* We never pass these to RAW sockets */
1618 			freemsg(mp);
1619 			return (NULL);
1620 		}
1621 
1622 		/* Make sure we have enough of the packet */
1623 		len_needed = ip_hdr_length + ICMPH_SIZE +
1624 		    3 * sizeof (uint32_t);
1625 
1626 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1627 			ipha = ip_pullup(mp, len_needed, ira);
1628 			if (ipha == NULL) {
1629 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1630 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1631 				    mp, ill);
1632 				freemsg(mp);
1633 				return (NULL);
1634 			}
1635 			/* Refresh following the pullup. */
1636 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1637 		}
1638 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1639 		/* Check db_ref to make sure we can modify the packet. */
1640 		if (mp->b_datap->db_ref > 1) {
1641 			mblk_t	*mp1;
1642 
1643 			mp1 = copymsg(mp);
1644 			freemsg(mp);
1645 			if (!mp1) {
1646 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1647 				return (NULL);
1648 			}
1649 			mp = mp1;
1650 			ipha = (ipha_t *)mp->b_rptr;
1651 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1652 		}
1653 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1654 		tsp = (uint32_t *)&icmph[1];
1655 		tsp++;		/* Skip past 'originate time' */
1656 		/* Compute # of milliseconds since midnight */
1657 		gethrestime(&now);
1658 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1659 		    now.tv_nsec / (NANOSEC / MILLISEC);
1660 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1661 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1662 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1663 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1664 		return (NULL);
1665 
1666 	case ICMP_TIME_STAMP_REPLY:
1667 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1668 		break;
1669 	case ICMP_INFO_REQUEST:
1670 		/* Per RFC 1122 3.2.2.7, ignore this. */
1671 	case ICMP_INFO_REPLY:
1672 		break;
1673 	case ICMP_ADDRESS_MASK_REQUEST:
1674 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1675 			interested =
1676 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1677 		} else {
1678 			interested = B_TRUE;
1679 		}
1680 		if (!interested) {
1681 			/* We never pass these to RAW sockets */
1682 			freemsg(mp);
1683 			return (NULL);
1684 		}
1685 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1686 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1687 			ipha = ip_pullup(mp, len_needed, ira);
1688 			if (ipha == NULL) {
1689 				BUMP_MIB(ill->ill_ip_mib,
1690 				    ipIfStatsInTruncatedPkts);
1691 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1692 				    ill);
1693 				freemsg(mp);
1694 				return (NULL);
1695 			}
1696 			/* Refresh following the pullup. */
1697 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1698 		}
1699 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1700 		/* Check db_ref to make sure we can modify the packet. */
1701 		if (mp->b_datap->db_ref > 1) {
1702 			mblk_t	*mp1;
1703 
1704 			mp1 = copymsg(mp);
1705 			freemsg(mp);
1706 			if (!mp1) {
1707 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1708 				return (NULL);
1709 			}
1710 			mp = mp1;
1711 			ipha = (ipha_t *)mp->b_rptr;
1712 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1713 		}
1714 		/*
1715 		 * Need the ipif with the mask be the same as the source
1716 		 * address of the mask reply. For unicast we have a specific
1717 		 * ipif. For multicast/broadcast we only handle onlink
1718 		 * senders, and use the source address to pick an ipif.
1719 		 */
1720 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1721 		if (ipif == NULL) {
1722 			/* Broadcast or multicast */
1723 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1724 			if (ipif == NULL) {
1725 				freemsg(mp);
1726 				return (NULL);
1727 			}
1728 		}
1729 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1730 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1731 		ipif_refrele(ipif);
1732 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1733 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1734 		return (NULL);
1735 
1736 	case ICMP_ADDRESS_MASK_REPLY:
1737 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1738 		break;
1739 	default:
1740 		interested = B_TRUE;	/* Pass up to transport */
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1742 		break;
1743 	}
1744 	/*
1745 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1746 	 * if there isn't one.
1747 	 */
1748 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1749 		/* If there is an ICMP client and we want one too, copy it. */
1750 
1751 		if (!interested) {
1752 			/* Caller will deliver to RAW sockets */
1753 			return (mp);
1754 		}
1755 		mp_ret = copymsg(mp);
1756 		if (mp_ret == NULL) {
1757 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1758 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1759 		}
1760 	} else if (!interested) {
1761 		/* Neither we nor raw sockets are interested. Drop packet now */
1762 		freemsg(mp);
1763 		return (NULL);
1764 	}
1765 
1766 	/*
1767 	 * ICMP error or redirect packet. Make sure we have enough of
1768 	 * the header and that db_ref == 1 since we might end up modifying
1769 	 * the packet.
1770 	 */
1771 	if (mp->b_cont != NULL) {
1772 		if (ip_pullup(mp, -1, ira) == NULL) {
1773 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1774 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1775 			    mp, ill);
1776 			freemsg(mp);
1777 			return (mp_ret);
1778 		}
1779 	}
1780 
1781 	if (mp->b_datap->db_ref > 1) {
1782 		mblk_t	*mp1;
1783 
1784 		mp1 = copymsg(mp);
1785 		if (mp1 == NULL) {
1786 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1787 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1788 			freemsg(mp);
1789 			return (mp_ret);
1790 		}
1791 		freemsg(mp);
1792 		mp = mp1;
1793 	}
1794 
1795 	/*
1796 	 * In case mp has changed, verify the message before any further
1797 	 * processes.
1798 	 */
1799 	ipha = (ipha_t *)mp->b_rptr;
1800 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1801 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1802 		freemsg(mp);
1803 		return (mp_ret);
1804 	}
1805 
1806 	switch (icmph->icmph_type) {
1807 	case ICMP_REDIRECT:
1808 		icmp_redirect_v4(mp, ipha, icmph, ira);
1809 		break;
1810 	case ICMP_DEST_UNREACHABLE:
1811 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1812 			/* Update DCE and adjust MTU is icmp header if needed */
1813 			icmp_inbound_too_big_v4(icmph, ira);
1814 		}
1815 		/* FALLTHRU */
1816 	default:
1817 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1818 		break;
1819 	}
1820 	return (mp_ret);
1821 }
1822 
1823 /*
1824  * Send an ICMP echo, timestamp or address mask reply.
1825  * The caller has already updated the payload part of the packet.
1826  * We handle the ICMP checksum, IP source address selection and feed
1827  * the packet into ip_output_simple.
1828  */
1829 static void
1830 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1831     ip_recv_attr_t *ira)
1832 {
1833 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1834 	ill_t		*ill = ira->ira_ill;
1835 	ip_stack_t	*ipst = ill->ill_ipst;
1836 	ip_xmit_attr_t	ixas;
1837 
1838 	/* Send out an ICMP packet */
1839 	icmph->icmph_checksum = 0;
1840 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1841 	/* Reset time to live. */
1842 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1843 	{
1844 		/* Swap source and destination addresses */
1845 		ipaddr_t tmp;
1846 
1847 		tmp = ipha->ipha_src;
1848 		ipha->ipha_src = ipha->ipha_dst;
1849 		ipha->ipha_dst = tmp;
1850 	}
1851 	ipha->ipha_ident = 0;
1852 	if (!IS_SIMPLE_IPH(ipha))
1853 		icmp_options_update(ipha);
1854 
1855 	bzero(&ixas, sizeof (ixas));
1856 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1857 	ixas.ixa_zoneid = ira->ira_zoneid;
1858 	ixas.ixa_cred = kcred;
1859 	ixas.ixa_cpid = NOPID;
1860 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1861 	ixas.ixa_ifindex = 0;
1862 	ixas.ixa_ipst = ipst;
1863 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1864 
1865 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1866 		/*
1867 		 * This packet should go out the same way as it
1868 		 * came in i.e in clear, independent of the IPsec policy
1869 		 * for transmitting packets.
1870 		 */
1871 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1872 	} else {
1873 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1874 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1875 			/* Note: mp already consumed and ip_drop_packet done */
1876 			return;
1877 		}
1878 	}
1879 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1880 		/*
1881 		 * Not one or our addresses (IRE_LOCALs), thus we let
1882 		 * ip_output_simple pick the source.
1883 		 */
1884 		ipha->ipha_src = INADDR_ANY;
1885 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1886 	}
1887 	/* Should we send with DF and use dce_pmtu? */
1888 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1889 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1890 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1891 	}
1892 
1893 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1894 
1895 	(void) ip_output_simple(mp, &ixas);
1896 	ixa_cleanup(&ixas);
1897 }
1898 
1899 /*
1900  * Verify the ICMP messages for either for ICMP error or redirect packet.
1901  * The caller should have fully pulled up the message. If it's a redirect
1902  * packet, only basic checks on IP header will be done; otherwise, verify
1903  * the packet by looking at the included ULP header.
1904  *
1905  * Called before icmp_inbound_error_fanout_v4 is called.
1906  */
1907 static boolean_t
1908 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1909 {
1910 	ill_t		*ill = ira->ira_ill;
1911 	int		hdr_length;
1912 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1913 	conn_t		*connp;
1914 	ipha_t		*ipha;	/* Inner IP header */
1915 
1916 	ipha = (ipha_t *)&icmph[1];
1917 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1918 		goto truncated;
1919 
1920 	hdr_length = IPH_HDR_LENGTH(ipha);
1921 
1922 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1923 		goto discard_pkt;
1924 
1925 	if (hdr_length < sizeof (ipha_t))
1926 		goto truncated;
1927 
1928 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1929 		goto truncated;
1930 
1931 	/*
1932 	 * Stop here for ICMP_REDIRECT.
1933 	 */
1934 	if (icmph->icmph_type == ICMP_REDIRECT)
1935 		return (B_TRUE);
1936 
1937 	/*
1938 	 * ICMP errors only.
1939 	 */
1940 	switch (ipha->ipha_protocol) {
1941 	case IPPROTO_UDP:
1942 		/*
1943 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1944 		 * transport header.
1945 		 */
1946 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1947 		    mp->b_wptr)
1948 			goto truncated;
1949 		break;
1950 	case IPPROTO_TCP: {
1951 		tcpha_t		*tcpha;
1952 
1953 		/*
1954 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1955 		 * transport header.
1956 		 */
1957 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1958 		    mp->b_wptr)
1959 			goto truncated;
1960 
1961 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1962 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1963 		    ipst);
1964 		if (connp == NULL)
1965 			goto discard_pkt;
1966 
1967 		if ((connp->conn_verifyicmp != NULL) &&
1968 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1969 			CONN_DEC_REF(connp);
1970 			goto discard_pkt;
1971 		}
1972 		CONN_DEC_REF(connp);
1973 		break;
1974 	}
1975 	case IPPROTO_SCTP:
1976 		/*
1977 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1978 		 * transport header.
1979 		 */
1980 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1981 		    mp->b_wptr)
1982 			goto truncated;
1983 		break;
1984 	case IPPROTO_ESP:
1985 	case IPPROTO_AH:
1986 		break;
1987 	case IPPROTO_ENCAP:
1988 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1989 		    mp->b_wptr)
1990 			goto truncated;
1991 		break;
1992 	default:
1993 		break;
1994 	}
1995 
1996 	return (B_TRUE);
1997 
1998 discard_pkt:
1999 	/* Bogus ICMP error. */
2000 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2001 	return (B_FALSE);
2002 
2003 truncated:
2004 	/* We pulled up everthing already. Must be truncated */
2005 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2006 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2007 	return (B_FALSE);
2008 }
2009 
2010 /* Table from RFC 1191 */
2011 static int icmp_frag_size_table[] =
2012 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2013 
2014 /*
2015  * Process received ICMP Packet too big.
2016  * Just handles the DCE create/update, including using the above table of
2017  * PMTU guesses. The caller is responsible for validating the packet before
2018  * passing it in and also to fanout the ICMP error to any matching transport
2019  * conns. Assumes the message has been fully pulled up and verified.
2020  *
2021  * Before getting here, the caller has called icmp_inbound_verify_v4()
2022  * that should have verified with ULP to prevent undoing the changes we're
2023  * going to make to DCE. For example, TCP might have verified that the packet
2024  * which generated error is in the send window.
2025  *
2026  * In some cases modified this MTU in the ICMP header packet; the caller
2027  * should pass to the matching ULP after this returns.
2028  */
2029 static void
2030 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
2031 {
2032 	dce_t		*dce;
2033 	int		old_mtu;
2034 	int		mtu, orig_mtu;
2035 	ipaddr_t	dst;
2036 	boolean_t	disable_pmtud;
2037 	ill_t		*ill = ira->ira_ill;
2038 	ip_stack_t	*ipst = ill->ill_ipst;
2039 	uint_t		hdr_length;
2040 	ipha_t		*ipha;
2041 
2042 	/* Caller already pulled up everything. */
2043 	ipha = (ipha_t *)&icmph[1];
2044 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2045 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2046 	ASSERT(ill != NULL);
2047 
2048 	hdr_length = IPH_HDR_LENGTH(ipha);
2049 
2050 	/*
2051 	 * We handle path MTU for source routed packets since the DCE
2052 	 * is looked up using the final destination.
2053 	 */
2054 	dst = ip_get_dst(ipha);
2055 
2056 	dce = dce_lookup_and_add_v4(dst, ipst);
2057 	if (dce == NULL) {
2058 		/* Couldn't add a unique one - ENOMEM */
2059 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
2060 		    ntohl(dst)));
2061 		return;
2062 	}
2063 
2064 	/* Check for MTU discovery advice as described in RFC 1191 */
2065 	mtu = ntohs(icmph->icmph_du_mtu);
2066 	orig_mtu = mtu;
2067 	disable_pmtud = B_FALSE;
2068 
2069 	mutex_enter(&dce->dce_lock);
2070 	if (dce->dce_flags & DCEF_PMTU)
2071 		old_mtu = dce->dce_pmtu;
2072 	else
2073 		old_mtu = ill->ill_mtu;
2074 
2075 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2076 		uint32_t length;
2077 		int	i;
2078 
2079 		/*
2080 		 * Use the table from RFC 1191 to figure out
2081 		 * the next "plateau" based on the length in
2082 		 * the original IP packet.
2083 		 */
2084 		length = ntohs(ipha->ipha_length);
2085 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
2086 		    uint32_t, length);
2087 		if (old_mtu <= length &&
2088 		    old_mtu >= length - hdr_length) {
2089 			/*
2090 			 * Handle broken BSD 4.2 systems that
2091 			 * return the wrong ipha_length in ICMP
2092 			 * errors.
2093 			 */
2094 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
2095 			    length, old_mtu));
2096 			length -= hdr_length;
2097 		}
2098 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2099 			if (length > icmp_frag_size_table[i])
2100 				break;
2101 		}
2102 		if (i == A_CNT(icmp_frag_size_table)) {
2103 			/* Smaller than IP_MIN_MTU! */
2104 			ip1dbg(("Too big for packet size %d\n",
2105 			    length));
2106 			disable_pmtud = B_TRUE;
2107 			mtu = ipst->ips_ip_pmtu_min;
2108 		} else {
2109 			mtu = icmp_frag_size_table[i];
2110 			ip1dbg(("Calculated mtu %d, packet size %d, "
2111 			    "before %d\n", mtu, length, old_mtu));
2112 			if (mtu < ipst->ips_ip_pmtu_min) {
2113 				mtu = ipst->ips_ip_pmtu_min;
2114 				disable_pmtud = B_TRUE;
2115 			}
2116 		}
2117 	}
2118 	if (disable_pmtud)
2119 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
2120 	else
2121 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
2122 
2123 	dce->dce_pmtu = MIN(old_mtu, mtu);
2124 	/* Prepare to send the new max frag size for the ULP. */
2125 	icmph->icmph_du_zero = 0;
2126 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
2127 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
2128 	    dce, int, orig_mtu, int, mtu);
2129 
2130 	/* We now have a PMTU for sure */
2131 	dce->dce_flags |= DCEF_PMTU;
2132 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
2133 	mutex_exit(&dce->dce_lock);
2134 	/*
2135 	 * After dropping the lock the new value is visible to everyone.
2136 	 * Then we bump the generation number so any cached values reinspect
2137 	 * the dce_t.
2138 	 */
2139 	dce_increment_generation(dce);
2140 	dce_refrele(dce);
2141 }
2142 
2143 /*
2144  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
2145  * calls this function.
2146  */
2147 static mblk_t *
2148 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
2149 {
2150 	int length;
2151 
2152 	ASSERT(mp->b_datap->db_type == M_DATA);
2153 
2154 	/* icmp_inbound_v4 has already pulled up the whole error packet */
2155 	ASSERT(mp->b_cont == NULL);
2156 
2157 	/*
2158 	 * The length that we want to overlay is the inner header
2159 	 * and what follows it.
2160 	 */
2161 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
2162 
2163 	/*
2164 	 * Overlay the inner header and whatever follows it over the
2165 	 * outer header.
2166 	 */
2167 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2168 
2169 	/* Adjust for what we removed */
2170 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2171 	return (mp);
2172 }
2173 
2174 /*
2175  * Try to pass the ICMP message upstream in case the ULP cares.
2176  *
2177  * If the packet that caused the ICMP error is secure, we send
2178  * it to AH/ESP to make sure that the attached packet has a
2179  * valid association. ipha in the code below points to the
2180  * IP header of the packet that caused the error.
2181  *
2182  * For IPsec cases, we let the next-layer-up (which has access to
2183  * cached policy on the conn_t, or can query the SPD directly)
2184  * subtract out any IPsec overhead if they must.  We therefore make no
2185  * adjustments here for IPsec overhead.
2186  *
2187  * IFN could have been generated locally or by some router.
2188  *
2189  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2190  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2191  *	    This happens because IP adjusted its value of MTU on an
2192  *	    earlier IFN message and could not tell the upper layer,
2193  *	    the new adjusted value of MTU e.g. Packet was encrypted
2194  *	    or there was not enough information to fanout to upper
2195  *	    layers. Thus on the next outbound datagram, ire_send_wire
2196  *	    generates the IFN, where IPsec processing has *not* been
2197  *	    done.
2198  *
2199  *	    Note that we retain ixa_fragsize across IPsec thus once
2200  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2201  *	    no change the fragsize even if the path MTU changes before
2202  *	    we reach ip_output_post_ipsec.
2203  *
2204  *	    In the local case, IRAF_LOOPBACK will be set indicating
2205  *	    that IFN was generated locally.
2206  *
2207  * ROUTER : IFN could be secure or non-secure.
2208  *
2209  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2210  *	      packet in error has AH/ESP headers to validate the AH/ESP
2211  *	      headers. AH/ESP will verify whether there is a valid SA or
2212  *	      not and send it back. We will fanout again if we have more
2213  *	      data in the packet.
2214  *
2215  *	      If the packet in error does not have AH/ESP, we handle it
2216  *	      like any other case.
2217  *
2218  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2219  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2220  *	      valid SA or not and send it back. We will fanout again if
2221  *	      we have more data in the packet.
2222  *
2223  *	      If the packet in error does not have AH/ESP, we handle it
2224  *	      like any other case.
2225  *
2226  * The caller must have called icmp_inbound_verify_v4.
2227  */
2228 static void
2229 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2230 {
2231 	uint16_t	*up;	/* Pointer to ports in ULP header */
2232 	uint32_t	ports;	/* reversed ports for fanout */
2233 	ipha_t		ripha;	/* With reversed addresses */
2234 	ipha_t		*ipha;  /* Inner IP header */
2235 	uint_t		hdr_length; /* Inner IP header length */
2236 	tcpha_t		*tcpha;
2237 	conn_t		*connp;
2238 	ill_t		*ill = ira->ira_ill;
2239 	ip_stack_t	*ipst = ill->ill_ipst;
2240 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2241 	ill_t		*rill = ira->ira_rill;
2242 
2243 	/* Caller already pulled up everything. */
2244 	ipha = (ipha_t *)&icmph[1];
2245 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2246 	ASSERT(mp->b_cont == NULL);
2247 
2248 	hdr_length = IPH_HDR_LENGTH(ipha);
2249 	ira->ira_protocol = ipha->ipha_protocol;
2250 
2251 	/*
2252 	 * We need a separate IP header with the source and destination
2253 	 * addresses reversed to do fanout/classification because the ipha in
2254 	 * the ICMP error is in the form we sent it out.
2255 	 */
2256 	ripha.ipha_src = ipha->ipha_dst;
2257 	ripha.ipha_dst = ipha->ipha_src;
2258 	ripha.ipha_protocol = ipha->ipha_protocol;
2259 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2260 
2261 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2262 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2263 	    ntohl(ipha->ipha_dst),
2264 	    icmph->icmph_type, icmph->icmph_code));
2265 
2266 	switch (ipha->ipha_protocol) {
2267 	case IPPROTO_UDP:
2268 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2269 
2270 		/* Attempt to find a client stream based on port. */
2271 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2272 		    ntohs(up[0]), ntohs(up[1])));
2273 
2274 		/* Note that we send error to all matches. */
2275 		ira->ira_flags |= IRAF_ICMP_ERROR;
2276 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2277 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2278 		return;
2279 
2280 	case IPPROTO_TCP:
2281 		/*
2282 		 * Find a TCP client stream for this packet.
2283 		 * Note that we do a reverse lookup since the header is
2284 		 * in the form we sent it out.
2285 		 */
2286 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2287 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2288 		    ipst);
2289 		if (connp == NULL)
2290 			goto discard_pkt;
2291 
2292 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2293 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2294 			mp = ipsec_check_inbound_policy(mp, connp,
2295 			    ipha, NULL, ira);
2296 			if (mp == NULL) {
2297 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2298 				/* Note that mp is NULL */
2299 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2300 				CONN_DEC_REF(connp);
2301 				return;
2302 			}
2303 		}
2304 
2305 		ira->ira_flags |= IRAF_ICMP_ERROR;
2306 		ira->ira_ill = ira->ira_rill = NULL;
2307 		if (IPCL_IS_TCP(connp)) {
2308 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2309 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2310 			    SQTAG_TCP_INPUT_ICMP_ERR);
2311 		} else {
2312 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2313 			(connp->conn_recv)(connp, mp, NULL, ira);
2314 			CONN_DEC_REF(connp);
2315 		}
2316 		ira->ira_ill = ill;
2317 		ira->ira_rill = rill;
2318 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2319 		return;
2320 
2321 	case IPPROTO_SCTP:
2322 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2323 		/* Find a SCTP client stream for this packet. */
2324 		((uint16_t *)&ports)[0] = up[1];
2325 		((uint16_t *)&ports)[1] = up[0];
2326 
2327 		ira->ira_flags |= IRAF_ICMP_ERROR;
2328 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2329 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2330 		return;
2331 
2332 	case IPPROTO_ESP:
2333 	case IPPROTO_AH:
2334 		if (!ipsec_loaded(ipss)) {
2335 			ip_proto_not_sup(mp, ira);
2336 			return;
2337 		}
2338 
2339 		if (ipha->ipha_protocol == IPPROTO_ESP)
2340 			mp = ipsecesp_icmp_error(mp, ira);
2341 		else
2342 			mp = ipsecah_icmp_error(mp, ira);
2343 		if (mp == NULL)
2344 			return;
2345 
2346 		/* Just in case ipsec didn't preserve the NULL b_cont */
2347 		if (mp->b_cont != NULL) {
2348 			if (!pullupmsg(mp, -1))
2349 				goto discard_pkt;
2350 		}
2351 
2352 		/*
2353 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2354 		 * correct, but we don't use them any more here.
2355 		 *
2356 		 * If succesful, the mp has been modified to not include
2357 		 * the ESP/AH header so we can fanout to the ULP's icmp
2358 		 * error handler.
2359 		 */
2360 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2361 			goto truncated;
2362 
2363 		/* Verify the modified message before any further processes. */
2364 		ipha = (ipha_t *)mp->b_rptr;
2365 		hdr_length = IPH_HDR_LENGTH(ipha);
2366 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2367 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2368 			freemsg(mp);
2369 			return;
2370 		}
2371 
2372 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2373 		return;
2374 
2375 	case IPPROTO_ENCAP: {
2376 		/* Look for self-encapsulated packets that caused an error */
2377 		ipha_t *in_ipha;
2378 
2379 		/*
2380 		 * Caller has verified that length has to be
2381 		 * at least the size of IP header.
2382 		 */
2383 		ASSERT(hdr_length >= sizeof (ipha_t));
2384 		/*
2385 		 * Check the sanity of the inner IP header like
2386 		 * we did for the outer header.
2387 		 */
2388 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2389 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2390 			goto discard_pkt;
2391 		}
2392 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2393 			goto discard_pkt;
2394 		}
2395 		/* Check for Self-encapsulated tunnels */
2396 		if (in_ipha->ipha_src == ipha->ipha_src &&
2397 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2398 
2399 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2400 			    in_ipha);
2401 			if (mp == NULL)
2402 				goto discard_pkt;
2403 
2404 			/*
2405 			 * Just in case self_encap didn't preserve the NULL
2406 			 * b_cont
2407 			 */
2408 			if (mp->b_cont != NULL) {
2409 				if (!pullupmsg(mp, -1))
2410 					goto discard_pkt;
2411 			}
2412 			/*
2413 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2414 			 * longer correct, but we don't use them any more here.
2415 			 */
2416 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2417 				goto truncated;
2418 
2419 			/*
2420 			 * Verify the modified message before any further
2421 			 * processes.
2422 			 */
2423 			ipha = (ipha_t *)mp->b_rptr;
2424 			hdr_length = IPH_HDR_LENGTH(ipha);
2425 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2426 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2427 				freemsg(mp);
2428 				return;
2429 			}
2430 
2431 			/*
2432 			 * The packet in error is self-encapsualted.
2433 			 * And we are finding it further encapsulated
2434 			 * which we could not have possibly generated.
2435 			 */
2436 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2437 				goto discard_pkt;
2438 			}
2439 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2440 			return;
2441 		}
2442 		/* No self-encapsulated */
2443 		/* FALLTHRU */
2444 	}
2445 	case IPPROTO_IPV6:
2446 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2447 		    &ripha.ipha_dst, ipst)) != NULL) {
2448 			ira->ira_flags |= IRAF_ICMP_ERROR;
2449 			connp->conn_recvicmp(connp, mp, NULL, ira);
2450 			CONN_DEC_REF(connp);
2451 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2452 			return;
2453 		}
2454 		/*
2455 		 * No IP tunnel is interested, fallthrough and see
2456 		 * if a raw socket will want it.
2457 		 */
2458 		/* FALLTHRU */
2459 	default:
2460 		ira->ira_flags |= IRAF_ICMP_ERROR;
2461 		ip_fanout_proto_v4(mp, &ripha, ira);
2462 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2463 		return;
2464 	}
2465 	/* NOTREACHED */
2466 discard_pkt:
2467 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2468 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2469 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2470 	freemsg(mp);
2471 	return;
2472 
2473 truncated:
2474 	/* We pulled up everthing already. Must be truncated */
2475 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2476 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2477 	freemsg(mp);
2478 }
2479 
2480 /*
2481  * Common IP options parser.
2482  *
2483  * Setup routine: fill in *optp with options-parsing state, then
2484  * tail-call ipoptp_next to return the first option.
2485  */
2486 uint8_t
2487 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2488 {
2489 	uint32_t totallen; /* total length of all options */
2490 
2491 	totallen = ipha->ipha_version_and_hdr_length -
2492 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2493 	totallen <<= 2;
2494 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2495 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2496 	optp->ipoptp_flags = 0;
2497 	return (ipoptp_next(optp));
2498 }
2499 
2500 /* Like above but without an ipha_t */
2501 uint8_t
2502 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2503 {
2504 	optp->ipoptp_next = opt;
2505 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2506 	optp->ipoptp_flags = 0;
2507 	return (ipoptp_next(optp));
2508 }
2509 
2510 /*
2511  * Common IP options parser: extract next option.
2512  */
2513 uint8_t
2514 ipoptp_next(ipoptp_t *optp)
2515 {
2516 	uint8_t *end = optp->ipoptp_end;
2517 	uint8_t *cur = optp->ipoptp_next;
2518 	uint8_t opt, len, pointer;
2519 
2520 	/*
2521 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2522 	 * has been corrupted.
2523 	 */
2524 	ASSERT(cur <= end);
2525 
2526 	if (cur == end)
2527 		return (IPOPT_EOL);
2528 
2529 	opt = cur[IPOPT_OPTVAL];
2530 
2531 	/*
2532 	 * Skip any NOP options.
2533 	 */
2534 	while (opt == IPOPT_NOP) {
2535 		cur++;
2536 		if (cur == end)
2537 			return (IPOPT_EOL);
2538 		opt = cur[IPOPT_OPTVAL];
2539 	}
2540 
2541 	if (opt == IPOPT_EOL)
2542 		return (IPOPT_EOL);
2543 
2544 	/*
2545 	 * Option requiring a length.
2546 	 */
2547 	if ((cur + 1) >= end) {
2548 		optp->ipoptp_flags |= IPOPTP_ERROR;
2549 		return (IPOPT_EOL);
2550 	}
2551 	len = cur[IPOPT_OLEN];
2552 	if (len < 2) {
2553 		optp->ipoptp_flags |= IPOPTP_ERROR;
2554 		return (IPOPT_EOL);
2555 	}
2556 	optp->ipoptp_cur = cur;
2557 	optp->ipoptp_len = len;
2558 	optp->ipoptp_next = cur + len;
2559 	if (cur + len > end) {
2560 		optp->ipoptp_flags |= IPOPTP_ERROR;
2561 		return (IPOPT_EOL);
2562 	}
2563 
2564 	/*
2565 	 * For the options which require a pointer field, make sure
2566 	 * its there, and make sure it points to either something
2567 	 * inside this option, or the end of the option.
2568 	 */
2569 	switch (opt) {
2570 	case IPOPT_RR:
2571 	case IPOPT_TS:
2572 	case IPOPT_LSRR:
2573 	case IPOPT_SSRR:
2574 		if (len <= IPOPT_OFFSET) {
2575 			optp->ipoptp_flags |= IPOPTP_ERROR;
2576 			return (opt);
2577 		}
2578 		pointer = cur[IPOPT_OFFSET];
2579 		if (pointer - 1 > len) {
2580 			optp->ipoptp_flags |= IPOPTP_ERROR;
2581 			return (opt);
2582 		}
2583 		break;
2584 	}
2585 
2586 	/*
2587 	 * Sanity check the pointer field based on the type of the
2588 	 * option.
2589 	 */
2590 	switch (opt) {
2591 	case IPOPT_RR:
2592 	case IPOPT_SSRR:
2593 	case IPOPT_LSRR:
2594 		if (pointer < IPOPT_MINOFF_SR)
2595 			optp->ipoptp_flags |= IPOPTP_ERROR;
2596 		break;
2597 	case IPOPT_TS:
2598 		if (pointer < IPOPT_MINOFF_IT)
2599 			optp->ipoptp_flags |= IPOPTP_ERROR;
2600 		/*
2601 		 * Note that the Internet Timestamp option also
2602 		 * contains two four bit fields (the Overflow field,
2603 		 * and the Flag field), which follow the pointer
2604 		 * field.  We don't need to check that these fields
2605 		 * fall within the length of the option because this
2606 		 * was implicitely done above.  We've checked that the
2607 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2608 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2609 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2610 		 */
2611 		ASSERT(len > IPOPT_POS_OV_FLG);
2612 		break;
2613 	}
2614 
2615 	return (opt);
2616 }
2617 
2618 /*
2619  * Use the outgoing IP header to create an IP_OPTIONS option the way
2620  * it was passed down from the application.
2621  *
2622  * This is compatible with BSD in that it returns
2623  * the reverse source route with the final destination
2624  * as the last entry. The first 4 bytes of the option
2625  * will contain the final destination.
2626  */
2627 int
2628 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2629 {
2630 	ipoptp_t	opts;
2631 	uchar_t		*opt;
2632 	uint8_t		optval;
2633 	uint8_t		optlen;
2634 	uint32_t	len = 0;
2635 	uchar_t		*buf1 = buf;
2636 	uint32_t	totallen;
2637 	ipaddr_t	dst;
2638 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2639 
2640 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2641 		return (0);
2642 
2643 	totallen = ipp->ipp_ipv4_options_len;
2644 	if (totallen & 0x3)
2645 		return (0);
2646 
2647 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2648 	len += IP_ADDR_LEN;
2649 	bzero(buf1, IP_ADDR_LEN);
2650 
2651 	dst = connp->conn_faddr_v4;
2652 
2653 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2654 	    optval != IPOPT_EOL;
2655 	    optval = ipoptp_next(&opts)) {
2656 		int	off;
2657 
2658 		opt = opts.ipoptp_cur;
2659 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2660 			break;
2661 		}
2662 		optlen = opts.ipoptp_len;
2663 
2664 		switch (optval) {
2665 		case IPOPT_SSRR:
2666 		case IPOPT_LSRR:
2667 
2668 			/*
2669 			 * Insert destination as the first entry in the source
2670 			 * route and move down the entries on step.
2671 			 * The last entry gets placed at buf1.
2672 			 */
2673 			buf[IPOPT_OPTVAL] = optval;
2674 			buf[IPOPT_OLEN] = optlen;
2675 			buf[IPOPT_OFFSET] = optlen;
2676 
2677 			off = optlen - IP_ADDR_LEN;
2678 			if (off < 0) {
2679 				/* No entries in source route */
2680 				break;
2681 			}
2682 			/* Last entry in source route if not already set */
2683 			if (dst == INADDR_ANY)
2684 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2685 			off -= IP_ADDR_LEN;
2686 
2687 			while (off > 0) {
2688 				bcopy(opt + off,
2689 				    buf + off + IP_ADDR_LEN,
2690 				    IP_ADDR_LEN);
2691 				off -= IP_ADDR_LEN;
2692 			}
2693 			/* ipha_dst into first slot */
2694 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2695 			    IP_ADDR_LEN);
2696 			buf += optlen;
2697 			len += optlen;
2698 			break;
2699 
2700 		default:
2701 			bcopy(opt, buf, optlen);
2702 			buf += optlen;
2703 			len += optlen;
2704 			break;
2705 		}
2706 	}
2707 done:
2708 	/* Pad the resulting options */
2709 	while (len & 0x3) {
2710 		*buf++ = IPOPT_EOL;
2711 		len++;
2712 	}
2713 	return (len);
2714 }
2715 
2716 /*
2717  * Update any record route or timestamp options to include this host.
2718  * Reverse any source route option.
2719  * This routine assumes that the options are well formed i.e. that they
2720  * have already been checked.
2721  */
2722 static void
2723 icmp_options_update(ipha_t *ipha)
2724 {
2725 	ipoptp_t	opts;
2726 	uchar_t		*opt;
2727 	uint8_t		optval;
2728 	ipaddr_t	src;		/* Our local address */
2729 	ipaddr_t	dst;
2730 
2731 	ip2dbg(("icmp_options_update\n"));
2732 	src = ipha->ipha_src;
2733 	dst = ipha->ipha_dst;
2734 
2735 	for (optval = ipoptp_first(&opts, ipha);
2736 	    optval != IPOPT_EOL;
2737 	    optval = ipoptp_next(&opts)) {
2738 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2739 		opt = opts.ipoptp_cur;
2740 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2741 		    optval, opts.ipoptp_len));
2742 		switch (optval) {
2743 			int off1, off2;
2744 		case IPOPT_SSRR:
2745 		case IPOPT_LSRR:
2746 			/*
2747 			 * Reverse the source route.  The first entry
2748 			 * should be the next to last one in the current
2749 			 * source route (the last entry is our address).
2750 			 * The last entry should be the final destination.
2751 			 */
2752 			off1 = IPOPT_MINOFF_SR - 1;
2753 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2754 			if (off2 < 0) {
2755 				/* No entries in source route */
2756 				ip1dbg((
2757 				    "icmp_options_update: bad src route\n"));
2758 				break;
2759 			}
2760 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2761 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2762 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2763 			off2 -= IP_ADDR_LEN;
2764 
2765 			while (off1 < off2) {
2766 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2767 				bcopy((char *)opt + off2, (char *)opt + off1,
2768 				    IP_ADDR_LEN);
2769 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2770 				off1 += IP_ADDR_LEN;
2771 				off2 -= IP_ADDR_LEN;
2772 			}
2773 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2774 			break;
2775 		}
2776 	}
2777 }
2778 
2779 /*
2780  * Process received ICMP Redirect messages.
2781  * Assumes the caller has verified that the headers are in the pulled up mblk.
2782  * Consumes mp.
2783  */
2784 static void
2785 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2786 {
2787 	ire_t		*ire, *nire;
2788 	ire_t		*prev_ire;
2789 	ipaddr_t  	src, dst, gateway;
2790 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2791 	ipha_t		*inner_ipha;	/* Inner IP header */
2792 
2793 	/* Caller already pulled up everything. */
2794 	inner_ipha = (ipha_t *)&icmph[1];
2795 	src = ipha->ipha_src;
2796 	dst = inner_ipha->ipha_dst;
2797 	gateway = icmph->icmph_rd_gateway;
2798 	/* Make sure the new gateway is reachable somehow. */
2799 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2800 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2801 	/*
2802 	 * Make sure we had a route for the dest in question and that
2803 	 * that route was pointing to the old gateway (the source of the
2804 	 * redirect packet.)
2805 	 * We do longest match and then compare ire_gateway_addr below.
2806 	 */
2807 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2808 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2809 	/*
2810 	 * Check that
2811 	 *	the redirect was not from ourselves
2812 	 *	the new gateway and the old gateway are directly reachable
2813 	 */
2814 	if (prev_ire == NULL || ire == NULL ||
2815 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2816 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2817 	    !(ire->ire_type & IRE_IF_ALL) ||
2818 	    prev_ire->ire_gateway_addr != src) {
2819 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2820 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2821 		freemsg(mp);
2822 		if (ire != NULL)
2823 			ire_refrele(ire);
2824 		if (prev_ire != NULL)
2825 			ire_refrele(prev_ire);
2826 		return;
2827 	}
2828 
2829 	ire_refrele(prev_ire);
2830 	ire_refrele(ire);
2831 
2832 	/*
2833 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2834 	 * require TOS routing
2835 	 */
2836 	switch (icmph->icmph_code) {
2837 	case 0:
2838 	case 1:
2839 		/* TODO: TOS specificity for cases 2 and 3 */
2840 	case 2:
2841 	case 3:
2842 		break;
2843 	default:
2844 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2845 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2846 		freemsg(mp);
2847 		return;
2848 	}
2849 	/*
2850 	 * Create a Route Association.  This will allow us to remember that
2851 	 * someone we believe told us to use the particular gateway.
2852 	 */
2853 	ire = ire_create(
2854 	    (uchar_t *)&dst,			/* dest addr */
2855 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2856 	    (uchar_t *)&gateway,		/* gateway addr */
2857 	    IRE_HOST,
2858 	    NULL,				/* ill */
2859 	    ALL_ZONES,
2860 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2861 	    NULL,				/* tsol_gc_t */
2862 	    ipst);
2863 
2864 	if (ire == NULL) {
2865 		freemsg(mp);
2866 		return;
2867 	}
2868 	nire = ire_add(ire);
2869 	/* Check if it was a duplicate entry */
2870 	if (nire != NULL && nire != ire) {
2871 		ASSERT(nire->ire_identical_ref > 1);
2872 		ire_delete(nire);
2873 		ire_refrele(nire);
2874 		nire = NULL;
2875 	}
2876 	ire = nire;
2877 	if (ire != NULL) {
2878 		ire_refrele(ire);		/* Held in ire_add */
2879 
2880 		/* tell routing sockets that we received a redirect */
2881 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2882 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2883 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2884 	}
2885 
2886 	/*
2887 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2888 	 * This together with the added IRE has the effect of
2889 	 * modifying an existing redirect.
2890 	 */
2891 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2892 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2893 	if (prev_ire != NULL) {
2894 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2895 			ire_delete(prev_ire);
2896 		ire_refrele(prev_ire);
2897 	}
2898 
2899 	freemsg(mp);
2900 }
2901 
2902 /*
2903  * Generate an ICMP parameter problem message.
2904  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2905  * constructed by the caller.
2906  */
2907 static void
2908 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2909 {
2910 	icmph_t	icmph;
2911 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2912 
2913 	mp = icmp_pkt_err_ok(mp, ira);
2914 	if (mp == NULL)
2915 		return;
2916 
2917 	bzero(&icmph, sizeof (icmph_t));
2918 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2919 	icmph.icmph_pp_ptr = ptr;
2920 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2921 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2922 }
2923 
2924 /*
2925  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2926  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2927  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2928  * an icmp error packet can be sent.
2929  * Assigns an appropriate source address to the packet. If ipha_dst is
2930  * one of our addresses use it for source. Otherwise let ip_output_simple
2931  * pick the source address.
2932  */
2933 static void
2934 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2935 {
2936 	ipaddr_t dst;
2937 	icmph_t	*icmph;
2938 	ipha_t	*ipha;
2939 	uint_t	len_needed;
2940 	size_t	msg_len;
2941 	mblk_t	*mp1;
2942 	ipaddr_t src;
2943 	ire_t	*ire;
2944 	ip_xmit_attr_t ixas;
2945 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2946 
2947 	ipha = (ipha_t *)mp->b_rptr;
2948 
2949 	bzero(&ixas, sizeof (ixas));
2950 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2951 	ixas.ixa_zoneid = ira->ira_zoneid;
2952 	ixas.ixa_ifindex = 0;
2953 	ixas.ixa_ipst = ipst;
2954 	ixas.ixa_cred = kcred;
2955 	ixas.ixa_cpid = NOPID;
2956 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2957 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2958 
2959 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2960 		/*
2961 		 * Apply IPsec based on how IPsec was applied to
2962 		 * the packet that had the error.
2963 		 *
2964 		 * If it was an outbound packet that caused the ICMP
2965 		 * error, then the caller will have setup the IRA
2966 		 * appropriately.
2967 		 */
2968 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2969 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2970 			/* Note: mp already consumed and ip_drop_packet done */
2971 			return;
2972 		}
2973 	} else {
2974 		/*
2975 		 * This is in clear. The icmp message we are building
2976 		 * here should go out in clear, independent of our policy.
2977 		 */
2978 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2979 	}
2980 
2981 	/* Remember our eventual destination */
2982 	dst = ipha->ipha_src;
2983 
2984 	/*
2985 	 * If the packet was for one of our unicast addresses, make
2986 	 * sure we respond with that as the source. Otherwise
2987 	 * have ip_output_simple pick the source address.
2988 	 */
2989 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2990 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2991 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2992 	if (ire != NULL) {
2993 		ire_refrele(ire);
2994 		src = ipha->ipha_dst;
2995 	} else {
2996 		src = INADDR_ANY;
2997 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2998 	}
2999 
3000 	/*
3001 	 * Check if we can send back more then 8 bytes in addition to
3002 	 * the IP header.  We try to send 64 bytes of data and the internal
3003 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3004 	 */
3005 	len_needed = IPH_HDR_LENGTH(ipha);
3006 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3007 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3008 		if (!pullupmsg(mp, -1)) {
3009 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3010 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
3011 			freemsg(mp);
3012 			return;
3013 		}
3014 		ipha = (ipha_t *)mp->b_rptr;
3015 
3016 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3017 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3018 			    len_needed));
3019 		} else {
3020 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3021 
3022 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3023 			len_needed += ip_hdr_length_v6(mp, ip6h);
3024 		}
3025 	}
3026 	len_needed += ipst->ips_ip_icmp_return;
3027 	msg_len = msgdsize(mp);
3028 	if (msg_len > len_needed) {
3029 		(void) adjmsg(mp, len_needed - msg_len);
3030 		msg_len = len_needed;
3031 	}
3032 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
3033 	if (mp1 == NULL) {
3034 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3035 		freemsg(mp);
3036 		return;
3037 	}
3038 	mp1->b_cont = mp;
3039 	mp = mp1;
3040 
3041 	/*
3042 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
3043 	 * node generates be accepted in peace by all on-host destinations.
3044 	 * If we do NOT assume that all on-host destinations trust
3045 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3046 	 * (Look for IXAF_TRUSTED_ICMP).
3047 	 */
3048 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
3049 
3050 	ipha = (ipha_t *)mp->b_rptr;
3051 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3052 	*ipha = icmp_ipha;
3053 	ipha->ipha_src = src;
3054 	ipha->ipha_dst = dst;
3055 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3056 	msg_len += sizeof (icmp_ipha) + len;
3057 	if (msg_len > IP_MAXPACKET) {
3058 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3059 		msg_len = IP_MAXPACKET;
3060 	}
3061 	ipha->ipha_length = htons((uint16_t)msg_len);
3062 	icmph = (icmph_t *)&ipha[1];
3063 	bcopy(stuff, icmph, len);
3064 	icmph->icmph_checksum = 0;
3065 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3066 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3067 
3068 	(void) ip_output_simple(mp, &ixas);
3069 	ixa_cleanup(&ixas);
3070 }
3071 
3072 /*
3073  * Determine if an ICMP error packet can be sent given the rate limit.
3074  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3075  * in milliseconds) and a burst size. Burst size number of packets can
3076  * be sent arbitrarely closely spaced.
3077  * The state is tracked using two variables to implement an approximate
3078  * token bucket filter:
3079  *	icmp_pkt_err_last - lbolt value when the last burst started
3080  *	icmp_pkt_err_sent - number of packets sent in current burst
3081  */
3082 boolean_t
3083 icmp_err_rate_limit(ip_stack_t *ipst)
3084 {
3085 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
3086 	uint_t refilled; /* Number of packets refilled in tbf since last */
3087 	/* Guard against changes by loading into local variable */
3088 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3089 
3090 	if (err_interval == 0)
3091 		return (B_FALSE);
3092 
3093 	if (ipst->ips_icmp_pkt_err_last > now) {
3094 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3095 		ipst->ips_icmp_pkt_err_last = 0;
3096 		ipst->ips_icmp_pkt_err_sent = 0;
3097 	}
3098 	/*
3099 	 * If we are in a burst update the token bucket filter.
3100 	 * Update the "last" time to be close to "now" but make sure
3101 	 * we don't loose precision.
3102 	 */
3103 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3104 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3105 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3106 			ipst->ips_icmp_pkt_err_sent = 0;
3107 		} else {
3108 			ipst->ips_icmp_pkt_err_sent -= refilled;
3109 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3110 		}
3111 	}
3112 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3113 		/* Start of new burst */
3114 		ipst->ips_icmp_pkt_err_last = now;
3115 	}
3116 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3117 		ipst->ips_icmp_pkt_err_sent++;
3118 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3119 		    ipst->ips_icmp_pkt_err_sent));
3120 		return (B_FALSE);
3121 	}
3122 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3123 	return (B_TRUE);
3124 }
3125 
3126 /*
3127  * Check if it is ok to send an IPv4 ICMP error packet in
3128  * response to the IPv4 packet in mp.
3129  * Free the message and return null if no
3130  * ICMP error packet should be sent.
3131  */
3132 static mblk_t *
3133 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
3134 {
3135 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3136 	icmph_t	*icmph;
3137 	ipha_t	*ipha;
3138 	uint_t	len_needed;
3139 
3140 	if (!mp)
3141 		return (NULL);
3142 	ipha = (ipha_t *)mp->b_rptr;
3143 	if (ip_csum_hdr(ipha)) {
3144 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3145 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
3146 		freemsg(mp);
3147 		return (NULL);
3148 	}
3149 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
3150 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
3151 	    CLASSD(ipha->ipha_dst) ||
3152 	    CLASSD(ipha->ipha_src) ||
3153 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3154 		/* Note: only errors to the fragment with offset 0 */
3155 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3156 		freemsg(mp);
3157 		return (NULL);
3158 	}
3159 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3160 		/*
3161 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3162 		 * errors in response to any ICMP errors.
3163 		 */
3164 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3165 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3166 			if (!pullupmsg(mp, len_needed)) {
3167 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3168 				freemsg(mp);
3169 				return (NULL);
3170 			}
3171 			ipha = (ipha_t *)mp->b_rptr;
3172 		}
3173 		icmph = (icmph_t *)
3174 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3175 		switch (icmph->icmph_type) {
3176 		case ICMP_DEST_UNREACHABLE:
3177 		case ICMP_SOURCE_QUENCH:
3178 		case ICMP_TIME_EXCEEDED:
3179 		case ICMP_PARAM_PROBLEM:
3180 		case ICMP_REDIRECT:
3181 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3182 			freemsg(mp);
3183 			return (NULL);
3184 		default:
3185 			break;
3186 		}
3187 	}
3188 	/*
3189 	 * If this is a labeled system, then check to see if we're allowed to
3190 	 * send a response to this particular sender.  If not, then just drop.
3191 	 */
3192 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3193 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3194 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3195 		freemsg(mp);
3196 		return (NULL);
3197 	}
3198 	if (icmp_err_rate_limit(ipst)) {
3199 		/*
3200 		 * Only send ICMP error packets every so often.
3201 		 * This should be done on a per port/source basis,
3202 		 * but for now this will suffice.
3203 		 */
3204 		freemsg(mp);
3205 		return (NULL);
3206 	}
3207 	return (mp);
3208 }
3209 
3210 /*
3211  * Called when a packet was sent out the same link that it arrived on.
3212  * Check if it is ok to send a redirect and then send it.
3213  */
3214 void
3215 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3216     ip_recv_attr_t *ira)
3217 {
3218 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3219 	ipaddr_t	src, nhop;
3220 	mblk_t		*mp1;
3221 	ire_t		*nhop_ire;
3222 
3223 	/*
3224 	 * Check the source address to see if it originated
3225 	 * on the same logical subnet it is going back out on.
3226 	 * If so, we should be able to send it a redirect.
3227 	 * Avoid sending a redirect if the destination
3228 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3229 	 * or if the packet was source routed out this interface.
3230 	 *
3231 	 * We avoid sending a redirect if the
3232 	 * destination is directly connected
3233 	 * because it is possible that multiple
3234 	 * IP subnets may have been configured on
3235 	 * the link, and the source may not
3236 	 * be on the same subnet as ip destination,
3237 	 * even though they are on the same
3238 	 * physical link.
3239 	 */
3240 	if ((ire->ire_type & IRE_ONLINK) ||
3241 	    ip_source_routed(ipha, ipst))
3242 		return;
3243 
3244 	nhop_ire = ire_nexthop(ire);
3245 	if (nhop_ire == NULL)
3246 		return;
3247 
3248 	nhop = nhop_ire->ire_addr;
3249 
3250 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3251 		ire_t	*ire2;
3252 
3253 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3254 		mutex_enter(&nhop_ire->ire_lock);
3255 		ire2 = nhop_ire->ire_dep_parent;
3256 		if (ire2 != NULL)
3257 			ire_refhold(ire2);
3258 		mutex_exit(&nhop_ire->ire_lock);
3259 		ire_refrele(nhop_ire);
3260 		nhop_ire = ire2;
3261 	}
3262 	if (nhop_ire == NULL)
3263 		return;
3264 
3265 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3266 
3267 	src = ipha->ipha_src;
3268 
3269 	/*
3270 	 * We look at the interface ire for the nexthop,
3271 	 * to see if ipha_src is in the same subnet
3272 	 * as the nexthop.
3273 	 */
3274 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3275 		/*
3276 		 * The source is directly connected.
3277 		 */
3278 		mp1 = copymsg(mp);
3279 		if (mp1 != NULL) {
3280 			icmp_send_redirect(mp1, nhop, ira);
3281 		}
3282 	}
3283 	ire_refrele(nhop_ire);
3284 }
3285 
3286 /*
3287  * Generate an ICMP redirect message.
3288  */
3289 static void
3290 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3291 {
3292 	icmph_t	icmph;
3293 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3294 
3295 	mp = icmp_pkt_err_ok(mp, ira);
3296 	if (mp == NULL)
3297 		return;
3298 
3299 	bzero(&icmph, sizeof (icmph_t));
3300 	icmph.icmph_type = ICMP_REDIRECT;
3301 	icmph.icmph_code = 1;
3302 	icmph.icmph_rd_gateway = gateway;
3303 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3304 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3305 }
3306 
3307 /*
3308  * Generate an ICMP time exceeded message.
3309  */
3310 void
3311 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3312 {
3313 	icmph_t	icmph;
3314 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3315 
3316 	mp = icmp_pkt_err_ok(mp, ira);
3317 	if (mp == NULL)
3318 		return;
3319 
3320 	bzero(&icmph, sizeof (icmph_t));
3321 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3322 	icmph.icmph_code = code;
3323 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3324 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3325 }
3326 
3327 /*
3328  * Generate an ICMP unreachable message.
3329  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3330  * constructed by the caller.
3331  */
3332 void
3333 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3334 {
3335 	icmph_t	icmph;
3336 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3337 
3338 	mp = icmp_pkt_err_ok(mp, ira);
3339 	if (mp == NULL)
3340 		return;
3341 
3342 	bzero(&icmph, sizeof (icmph_t));
3343 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3344 	icmph.icmph_code = code;
3345 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3346 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3347 }
3348 
3349 /*
3350  * Latch in the IPsec state for a stream based the policy in the listener
3351  * and the actions in the ip_recv_attr_t.
3352  * Called directly from TCP and SCTP.
3353  */
3354 boolean_t
3355 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3356 {
3357 	ASSERT(lconnp->conn_policy != NULL);
3358 	ASSERT(connp->conn_policy == NULL);
3359 
3360 	IPPH_REFHOLD(lconnp->conn_policy);
3361 	connp->conn_policy = lconnp->conn_policy;
3362 
3363 	if (ira->ira_ipsec_action != NULL) {
3364 		if (connp->conn_latch == NULL) {
3365 			connp->conn_latch = iplatch_create();
3366 			if (connp->conn_latch == NULL)
3367 				return (B_FALSE);
3368 		}
3369 		ipsec_latch_inbound(connp, ira);
3370 	}
3371 	return (B_TRUE);
3372 }
3373 
3374 /*
3375  * Verify whether or not the IP address is a valid local address.
3376  * Could be a unicast, including one for a down interface.
3377  * If allow_mcbc then a multicast or broadcast address is also
3378  * acceptable.
3379  *
3380  * In the case of a broadcast/multicast address, however, the
3381  * upper protocol is expected to reset the src address
3382  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3383  * no packets are emitted with broadcast/multicast address as
3384  * source address (that violates hosts requirements RFC 1122)
3385  * The addresses valid for bind are:
3386  *	(1) - INADDR_ANY (0)
3387  *	(2) - IP address of an UP interface
3388  *	(3) - IP address of a DOWN interface
3389  *	(4) - valid local IP broadcast addresses. In this case
3390  *	the conn will only receive packets destined to
3391  *	the specified broadcast address.
3392  *	(5) - a multicast address. In this case
3393  *	the conn will only receive packets destined to
3394  *	the specified multicast address. Note: the
3395  *	application still has to issue an
3396  *	IP_ADD_MEMBERSHIP socket option.
3397  *
3398  * In all the above cases, the bound address must be valid in the current zone.
3399  * When the address is loopback, multicast or broadcast, there might be many
3400  * matching IREs so bind has to look up based on the zone.
3401  */
3402 ip_laddr_t
3403 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3404     ip_stack_t *ipst, boolean_t allow_mcbc)
3405 {
3406 	ire_t *src_ire;
3407 
3408 	ASSERT(src_addr != INADDR_ANY);
3409 
3410 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3411 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3412 
3413 	/*
3414 	 * If an address other than in6addr_any is requested,
3415 	 * we verify that it is a valid address for bind
3416 	 * Note: Following code is in if-else-if form for
3417 	 * readability compared to a condition check.
3418 	 */
3419 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3420 		/*
3421 		 * (2) Bind to address of local UP interface
3422 		 */
3423 		ire_refrele(src_ire);
3424 		return (IPVL_UNICAST_UP);
3425 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3426 		/*
3427 		 * (4) Bind to broadcast address
3428 		 */
3429 		ire_refrele(src_ire);
3430 		if (allow_mcbc)
3431 			return (IPVL_BCAST);
3432 		else
3433 			return (IPVL_BAD);
3434 	} else if (CLASSD(src_addr)) {
3435 		/* (5) bind to multicast address. */
3436 		if (src_ire != NULL)
3437 			ire_refrele(src_ire);
3438 
3439 		if (allow_mcbc)
3440 			return (IPVL_MCAST);
3441 		else
3442 			return (IPVL_BAD);
3443 	} else {
3444 		ipif_t *ipif;
3445 
3446 		/*
3447 		 * (3) Bind to address of local DOWN interface?
3448 		 * (ipif_lookup_addr() looks up all interfaces
3449 		 * but we do not get here for UP interfaces
3450 		 * - case (2) above)
3451 		 */
3452 		if (src_ire != NULL)
3453 			ire_refrele(src_ire);
3454 
3455 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3456 		if (ipif == NULL)
3457 			return (IPVL_BAD);
3458 
3459 		/* Not a useful source? */
3460 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3461 			ipif_refrele(ipif);
3462 			return (IPVL_BAD);
3463 		}
3464 		ipif_refrele(ipif);
3465 		return (IPVL_UNICAST_DOWN);
3466 	}
3467 }
3468 
3469 /*
3470  * Insert in the bind fanout for IPv4 and IPv6.
3471  * The caller should already have used ip_laddr_verify_v*() before calling
3472  * this.
3473  */
3474 int
3475 ip_laddr_fanout_insert(conn_t *connp)
3476 {
3477 	int		error;
3478 
3479 	/*
3480 	 * Allow setting new policies. For example, disconnects result
3481 	 * in us being called. As we would have set conn_policy_cached
3482 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3483 	 * can change after the disconnect.
3484 	 */
3485 	connp->conn_policy_cached = B_FALSE;
3486 
3487 	error = ipcl_bind_insert(connp);
3488 	if (error != 0) {
3489 		if (connp->conn_anon_port) {
3490 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3491 			    connp->conn_mlp_type, connp->conn_proto,
3492 			    ntohs(connp->conn_lport), B_FALSE);
3493 		}
3494 		connp->conn_mlp_type = mlptSingle;
3495 	}
3496 	return (error);
3497 }
3498 
3499 /*
3500  * Verify that both the source and destination addresses are valid. If
3501  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3502  * i.e. have no route to it.  Protocols like TCP want to verify destination
3503  * reachability, while tunnels do not.
3504  *
3505  * Determine the route, the interface, and (optionally) the source address
3506  * to use to reach a given destination.
3507  * Note that we allow connect to broadcast and multicast addresses when
3508  * IPDF_ALLOW_MCBC is set.
3509  * first_hop and dst_addr are normally the same, but if source routing
3510  * they will differ; in that case the first_hop is what we'll use for the
3511  * routing lookup but the dce and label checks will be done on dst_addr,
3512  *
3513  * If uinfo is set, then we fill in the best available information
3514  * we have for the destination. This is based on (in priority order) any
3515  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3516  * ill_mtu.
3517  *
3518  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3519  * always do the label check on dst_addr.
3520  */
3521 int
3522 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3523     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3524 {
3525 	ire_t		*ire = NULL;
3526 	int		error = 0;
3527 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3528 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3529 	ip_stack_t	*ipst = ixa->ixa_ipst;
3530 	dce_t		*dce;
3531 	uint_t		pmtu;
3532 	uint_t		generation;
3533 	nce_t		*nce;
3534 	ill_t		*ill = NULL;
3535 	boolean_t	multirt = B_FALSE;
3536 
3537 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3538 
3539 	/*
3540 	 * We never send to zero; the ULPs map it to the loopback address.
3541 	 * We can't allow it since we use zero to mean unitialized in some
3542 	 * places.
3543 	 */
3544 	ASSERT(dst_addr != INADDR_ANY);
3545 
3546 	if (is_system_labeled()) {
3547 		ts_label_t *tsl = NULL;
3548 
3549 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3550 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3551 		if (error != 0)
3552 			return (error);
3553 		if (tsl != NULL) {
3554 			/* Update the label */
3555 			ip_xmit_attr_replace_tsl(ixa, tsl);
3556 		}
3557 	}
3558 
3559 	setsrc = INADDR_ANY;
3560 	/*
3561 	 * Select a route; For IPMP interfaces, we would only select
3562 	 * a "hidden" route (i.e., going through a specific under_ill)
3563 	 * if ixa_ifindex has been specified.
3564 	 */
3565 	ire = ip_select_route_v4(firsthop, ixa, &generation, &setsrc, &error,
3566 	    &multirt);
3567 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3568 	if (error != 0)
3569 		goto bad_addr;
3570 
3571 	/*
3572 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3573 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3574 	 * Otherwise the destination needn't be reachable.
3575 	 *
3576 	 * If we match on a reject or black hole, then we've got a
3577 	 * local failure.  May as well fail out the connect() attempt,
3578 	 * since it's never going to succeed.
3579 	 */
3580 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3581 		/*
3582 		 * If we're verifying destination reachability, we always want
3583 		 * to complain here.
3584 		 *
3585 		 * If we're not verifying destination reachability but the
3586 		 * destination has a route, we still want to fail on the
3587 		 * temporary address and broadcast address tests.
3588 		 *
3589 		 * In both cases do we let the code continue so some reasonable
3590 		 * information is returned to the caller. That enables the
3591 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3592 		 * use the generation mismatch path to check for the unreachable
3593 		 * case thereby avoiding any specific check in the main path.
3594 		 */
3595 		ASSERT(generation == IRE_GENERATION_VERIFY);
3596 		if (flags & IPDF_VERIFY_DST) {
3597 			/*
3598 			 * Set errno but continue to set up ixa_ire to be
3599 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3600 			 * That allows callers to use ip_output to get an
3601 			 * ICMP error back.
3602 			 */
3603 			if (!(ire->ire_type & IRE_HOST))
3604 				error = ENETUNREACH;
3605 			else
3606 				error = EHOSTUNREACH;
3607 		}
3608 	}
3609 
3610 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3611 	    !(flags & IPDF_ALLOW_MCBC)) {
3612 		ire_refrele(ire);
3613 		ire = ire_reject(ipst, B_FALSE);
3614 		generation = IRE_GENERATION_VERIFY;
3615 		error = ENETUNREACH;
3616 	}
3617 
3618 	/* Cache things */
3619 	if (ixa->ixa_ire != NULL)
3620 		ire_refrele_notr(ixa->ixa_ire);
3621 #ifdef DEBUG
3622 	ire_refhold_notr(ire);
3623 	ire_refrele(ire);
3624 #endif
3625 	ixa->ixa_ire = ire;
3626 	ixa->ixa_ire_generation = generation;
3627 
3628 	/*
3629 	 * For multicast with multirt we have a flag passed back from
3630 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3631 	 * possible multicast address.
3632 	 * We also need a flag for multicast since we can't check
3633 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3634 	 */
3635 	if (multirt) {
3636 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3637 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3638 	} else {
3639 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3640 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3641 	}
3642 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3643 		/* Get an nce to cache. */
3644 		nce = ire_to_nce(ire, firsthop, NULL);
3645 		if (nce == NULL) {
3646 			/* Allocation failure? */
3647 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3648 		} else {
3649 			if (ixa->ixa_nce != NULL)
3650 				nce_refrele(ixa->ixa_nce);
3651 			ixa->ixa_nce = nce;
3652 		}
3653 	}
3654 
3655 	/*
3656 	 * If the source address is a loopback address, the
3657 	 * destination had best be local or multicast.
3658 	 * If we are sending to an IRE_LOCAL using a loopback source then
3659 	 * it had better be the same zoneid.
3660 	 */
3661 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3662 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3663 			ire = NULL;	/* Stored in ixa_ire */
3664 			error = EADDRNOTAVAIL;
3665 			goto bad_addr;
3666 		}
3667 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3668 			ire = NULL;	/* Stored in ixa_ire */
3669 			error = EADDRNOTAVAIL;
3670 			goto bad_addr;
3671 		}
3672 	}
3673 	if (ire->ire_type & IRE_BROADCAST) {
3674 		/*
3675 		 * If the ULP didn't have a specified source, then we
3676 		 * make sure we reselect the source when sending
3677 		 * broadcasts out different interfaces.
3678 		 */
3679 		if (flags & IPDF_SELECT_SRC)
3680 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3681 		else
3682 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3683 	}
3684 
3685 	/*
3686 	 * Does the caller want us to pick a source address?
3687 	 */
3688 	if (flags & IPDF_SELECT_SRC) {
3689 		ipaddr_t	src_addr;
3690 
3691 		/*
3692 		 * We use use ire_nexthop_ill to avoid the under ipmp
3693 		 * interface for source address selection. Note that for ipmp
3694 		 * probe packets, ixa_ifindex would have been specified, and
3695 		 * the ip_select_route() invocation would have picked an ire
3696 		 * will ire_ill pointing at an under interface.
3697 		 */
3698 		ill = ire_nexthop_ill(ire);
3699 
3700 		/* If unreachable we have no ill but need some source */
3701 		if (ill == NULL) {
3702 			src_addr = htonl(INADDR_LOOPBACK);
3703 			/* Make sure we look for a better source address */
3704 			generation = SRC_GENERATION_VERIFY;
3705 		} else {
3706 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3707 			    ixa->ixa_multicast_ifaddr, zoneid,
3708 			    ipst, &src_addr, &generation, NULL);
3709 			if (error != 0) {
3710 				ire = NULL;	/* Stored in ixa_ire */
3711 				goto bad_addr;
3712 			}
3713 		}
3714 
3715 		/*
3716 		 * We allow the source address to to down.
3717 		 * However, we check that we don't use the loopback address
3718 		 * as a source when sending out on the wire.
3719 		 */
3720 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3721 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3722 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3723 			ire = NULL;	/* Stored in ixa_ire */
3724 			error = EADDRNOTAVAIL;
3725 			goto bad_addr;
3726 		}
3727 
3728 		*src_addrp = src_addr;
3729 		ixa->ixa_src_generation = generation;
3730 	}
3731 
3732 	if (flags & IPDF_UNIQUE_DCE) {
3733 		/* Fallback to the default dce if allocation fails */
3734 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3735 		if (dce != NULL)
3736 			generation = dce->dce_generation;
3737 		else
3738 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3739 	} else {
3740 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3741 	}
3742 	ASSERT(dce != NULL);
3743 	if (ixa->ixa_dce != NULL)
3744 		dce_refrele_notr(ixa->ixa_dce);
3745 #ifdef DEBUG
3746 	dce_refhold_notr(dce);
3747 	dce_refrele(dce);
3748 #endif
3749 	ixa->ixa_dce = dce;
3750 	ixa->ixa_dce_generation = generation;
3751 
3752 	/*
3753 	 * Make sure we don't leave an unreachable ixa_nce in place
3754 	 * since ip_select_route is used when we unplumb i.e., remove
3755 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3756 	 */
3757 	nce = ixa->ixa_nce;
3758 	if (nce != NULL && nce->nce_is_condemned) {
3759 		nce_refrele(nce);
3760 		ixa->ixa_nce = NULL;
3761 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3762 	}
3763 
3764 	/*
3765 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3766 	 * However, we can't do it for IPv4 multicast or broadcast.
3767 	 */
3768 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3769 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3770 
3771 	/*
3772 	 * Set initial value for fragmentation limit. Either conn_ip_output
3773 	 * or ULP might updates it when there are routing changes.
3774 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3775 	 */
3776 	pmtu = ip_get_pmtu(ixa);
3777 	ixa->ixa_fragsize = pmtu;
3778 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3779 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3780 		ixa->ixa_pmtu = pmtu;
3781 
3782 	/*
3783 	 * Extract information useful for some transports.
3784 	 * First we look for DCE metrics. Then we take what we have in
3785 	 * the metrics in the route, where the offlink is used if we have
3786 	 * one.
3787 	 */
3788 	if (uinfo != NULL) {
3789 		bzero(uinfo, sizeof (*uinfo));
3790 
3791 		if (dce->dce_flags & DCEF_UINFO)
3792 			*uinfo = dce->dce_uinfo;
3793 
3794 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3795 
3796 		/* Allow ire_metrics to decrease the path MTU from above */
3797 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3798 			uinfo->iulp_mtu = pmtu;
3799 
3800 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3801 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3802 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3803 	}
3804 
3805 	if (ill != NULL)
3806 		ill_refrele(ill);
3807 
3808 	return (error);
3809 
3810 bad_addr:
3811 	if (ire != NULL)
3812 		ire_refrele(ire);
3813 
3814 	if (ill != NULL)
3815 		ill_refrele(ill);
3816 
3817 	/*
3818 	 * Make sure we don't leave an unreachable ixa_nce in place
3819 	 * since ip_select_route is used when we unplumb i.e., remove
3820 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3821 	 */
3822 	nce = ixa->ixa_nce;
3823 	if (nce != NULL && nce->nce_is_condemned) {
3824 		nce_refrele(nce);
3825 		ixa->ixa_nce = NULL;
3826 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3827 	}
3828 
3829 	return (error);
3830 }
3831 
3832 
3833 /*
3834  * Get the base MTU for the case when path MTU discovery is not used.
3835  * Takes the MTU of the IRE into account.
3836  */
3837 uint_t
3838 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3839 {
3840 	uint_t mtu = ill->ill_mtu;
3841 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3842 
3843 	if (iremtu != 0 && iremtu < mtu)
3844 		mtu = iremtu;
3845 
3846 	return (mtu);
3847 }
3848 
3849 /*
3850  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3851  * Assumes that ixa_ire, dce, and nce have already been set up.
3852  *
3853  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3854  * We avoid path MTU discovery if it is disabled with ndd.
3855  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3856  *
3857  * NOTE: We also used to turn it off for source routed packets. That
3858  * is no longer required since the dce is per final destination.
3859  */
3860 uint_t
3861 ip_get_pmtu(ip_xmit_attr_t *ixa)
3862 {
3863 	ip_stack_t	*ipst = ixa->ixa_ipst;
3864 	dce_t		*dce;
3865 	nce_t		*nce;
3866 	ire_t		*ire;
3867 	uint_t		pmtu;
3868 
3869 	ire = ixa->ixa_ire;
3870 	dce = ixa->ixa_dce;
3871 	nce = ixa->ixa_nce;
3872 
3873 	/*
3874 	 * If path MTU discovery has been turned off by ndd, then we ignore
3875 	 * any dce_pmtu and for IPv4 we will not set DF.
3876 	 */
3877 	if (!ipst->ips_ip_path_mtu_discovery)
3878 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3879 
3880 	pmtu = IP_MAXPACKET;
3881 	/*
3882 	 * Decide whether whether IPv4 sets DF
3883 	 * For IPv6 "no DF" means to use the 1280 mtu
3884 	 */
3885 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3886 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3887 	} else {
3888 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3889 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3890 			pmtu = IPV6_MIN_MTU;
3891 	}
3892 
3893 	/* Check if the PMTU is to old before we use it */
3894 	if ((dce->dce_flags & DCEF_PMTU) &&
3895 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3896 	    ipst->ips_ip_pathmtu_interval) {
3897 		/*
3898 		 * Older than 20 minutes. Drop the path MTU information.
3899 		 */
3900 		mutex_enter(&dce->dce_lock);
3901 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3902 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3903 		mutex_exit(&dce->dce_lock);
3904 		dce_increment_generation(dce);
3905 	}
3906 
3907 	/* The metrics on the route can lower the path MTU */
3908 	if (ire->ire_metrics.iulp_mtu != 0 &&
3909 	    ire->ire_metrics.iulp_mtu < pmtu)
3910 		pmtu = ire->ire_metrics.iulp_mtu;
3911 
3912 	/*
3913 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3914 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3915 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3916 	 */
3917 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3918 		if (dce->dce_flags & DCEF_PMTU) {
3919 			if (dce->dce_pmtu < pmtu)
3920 				pmtu = dce->dce_pmtu;
3921 
3922 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3923 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3924 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3925 			} else {
3926 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3927 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3928 			}
3929 		} else {
3930 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3931 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3932 		}
3933 	}
3934 
3935 	/*
3936 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3937 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3938 	 * mtu as IRE_LOOPBACK.
3939 	 */
3940 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3941 		uint_t loopback_mtu;
3942 
3943 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3944 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3945 
3946 		if (loopback_mtu < pmtu)
3947 			pmtu = loopback_mtu;
3948 	} else if (nce != NULL) {
3949 		/*
3950 		 * Make sure we don't exceed the interface MTU.
3951 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3952 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3953 		 * to tell the transport something larger than zero.
3954 		 */
3955 		if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3956 			pmtu = nce->nce_common->ncec_ill->ill_mtu;
3957 		if (nce->nce_common->ncec_ill != nce->nce_ill &&
3958 		    nce->nce_ill->ill_mtu < pmtu) {
3959 			/*
3960 			 * for interfaces in an IPMP group, the mtu of
3961 			 * the nce_ill (under_ill) could be different
3962 			 * from the mtu of the ncec_ill, so we take the
3963 			 * min of the two.
3964 			 */
3965 			pmtu = nce->nce_ill->ill_mtu;
3966 		}
3967 	}
3968 
3969 	/*
3970 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3971 	 * Only applies to IPv6.
3972 	 */
3973 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3974 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3975 			switch (ixa->ixa_use_min_mtu) {
3976 			case IPV6_USE_MIN_MTU_MULTICAST:
3977 				if (ire->ire_type & IRE_MULTICAST)
3978 					pmtu = IPV6_MIN_MTU;
3979 				break;
3980 			case IPV6_USE_MIN_MTU_ALWAYS:
3981 				pmtu = IPV6_MIN_MTU;
3982 				break;
3983 			case IPV6_USE_MIN_MTU_NEVER:
3984 				break;
3985 			}
3986 		} else {
3987 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3988 			if (ire->ire_type & IRE_MULTICAST)
3989 				pmtu = IPV6_MIN_MTU;
3990 		}
3991 	}
3992 
3993 	/*
3994 	 * After receiving an ICMPv6 "packet too big" message with a
3995 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3996 	 * will insert a 8-byte fragment header in every packet. We compensate
3997 	 * for those cases by returning a smaller path MTU to the ULP.
3998 	 *
3999 	 * In the case of CGTP then ip_output will add a fragment header.
4000 	 * Make sure there is room for it by telling a smaller number
4001 	 * to the transport.
4002 	 *
4003 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
4004 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
4005 	 * which is the size of the packets it can send.
4006 	 */
4007 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
4008 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
4009 		    (ire->ire_flags & RTF_MULTIRT) ||
4010 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
4011 			pmtu -= sizeof (ip6_frag_t);
4012 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
4013 		}
4014 	}
4015 
4016 	return (pmtu);
4017 }
4018 
4019 /*
4020  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4021  * the final piece where we don't.  Return a pointer to the first mblk in the
4022  * result, and update the pointer to the next mblk to chew on.  If anything
4023  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4024  * NULL pointer.
4025  */
4026 mblk_t *
4027 ip_carve_mp(mblk_t **mpp, ssize_t len)
4028 {
4029 	mblk_t	*mp0;
4030 	mblk_t	*mp1;
4031 	mblk_t	*mp2;
4032 
4033 	if (!len || !mpp || !(mp0 = *mpp))
4034 		return (NULL);
4035 	/* If we aren't going to consume the first mblk, we need a dup. */
4036 	if (mp0->b_wptr - mp0->b_rptr > len) {
4037 		mp1 = dupb(mp0);
4038 		if (mp1) {
4039 			/* Partition the data between the two mblks. */
4040 			mp1->b_wptr = mp1->b_rptr + len;
4041 			mp0->b_rptr = mp1->b_wptr;
4042 			/*
4043 			 * after adjustments if mblk not consumed is now
4044 			 * unaligned, try to align it. If this fails free
4045 			 * all messages and let upper layer recover.
4046 			 */
4047 			if (!OK_32PTR(mp0->b_rptr)) {
4048 				if (!pullupmsg(mp0, -1)) {
4049 					freemsg(mp0);
4050 					freemsg(mp1);
4051 					*mpp = NULL;
4052 					return (NULL);
4053 				}
4054 			}
4055 		}
4056 		return (mp1);
4057 	}
4058 	/* Eat through as many mblks as we need to get len bytes. */
4059 	len -= mp0->b_wptr - mp0->b_rptr;
4060 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4061 		if (mp2->b_wptr - mp2->b_rptr > len) {
4062 			/*
4063 			 * We won't consume the entire last mblk.  Like
4064 			 * above, dup and partition it.
4065 			 */
4066 			mp1->b_cont = dupb(mp2);
4067 			mp1 = mp1->b_cont;
4068 			if (!mp1) {
4069 				/*
4070 				 * Trouble.  Rather than go to a lot of
4071 				 * trouble to clean up, we free the messages.
4072 				 * This won't be any worse than losing it on
4073 				 * the wire.
4074 				 */
4075 				freemsg(mp0);
4076 				freemsg(mp2);
4077 				*mpp = NULL;
4078 				return (NULL);
4079 			}
4080 			mp1->b_wptr = mp1->b_rptr + len;
4081 			mp2->b_rptr = mp1->b_wptr;
4082 			/*
4083 			 * after adjustments if mblk not consumed is now
4084 			 * unaligned, try to align it. If this fails free
4085 			 * all messages and let upper layer recover.
4086 			 */
4087 			if (!OK_32PTR(mp2->b_rptr)) {
4088 				if (!pullupmsg(mp2, -1)) {
4089 					freemsg(mp0);
4090 					freemsg(mp2);
4091 					*mpp = NULL;
4092 					return (NULL);
4093 				}
4094 			}
4095 			*mpp = mp2;
4096 			return (mp0);
4097 		}
4098 		/* Decrement len by the amount we just got. */
4099 		len -= mp2->b_wptr - mp2->b_rptr;
4100 	}
4101 	/*
4102 	 * len should be reduced to zero now.  If not our caller has
4103 	 * screwed up.
4104 	 */
4105 	if (len) {
4106 		/* Shouldn't happen! */
4107 		freemsg(mp0);
4108 		*mpp = NULL;
4109 		return (NULL);
4110 	}
4111 	/*
4112 	 * We consumed up to exactly the end of an mblk.  Detach the part
4113 	 * we are returning from the rest of the chain.
4114 	 */
4115 	mp1->b_cont = NULL;
4116 	*mpp = mp2;
4117 	return (mp0);
4118 }
4119 
4120 /* The ill stream is being unplumbed. Called from ip_close */
4121 int
4122 ip_modclose(ill_t *ill)
4123 {
4124 	boolean_t success;
4125 	ipsq_t	*ipsq;
4126 	ipif_t	*ipif;
4127 	queue_t	*q = ill->ill_rq;
4128 	ip_stack_t	*ipst = ill->ill_ipst;
4129 	int	i;
4130 	arl_ill_common_t *ai = ill->ill_common;
4131 
4132 	/*
4133 	 * The punlink prior to this may have initiated a capability
4134 	 * negotiation. But ipsq_enter will block until that finishes or
4135 	 * times out.
4136 	 */
4137 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
4138 
4139 	/*
4140 	 * Open/close/push/pop is guaranteed to be single threaded
4141 	 * per stream by STREAMS. FS guarantees that all references
4142 	 * from top are gone before close is called. So there can't
4143 	 * be another close thread that has set CONDEMNED on this ill.
4144 	 * and cause ipsq_enter to return failure.
4145 	 */
4146 	ASSERT(success);
4147 	ipsq = ill->ill_phyint->phyint_ipsq;
4148 
4149 	/*
4150 	 * Mark it condemned. No new reference will be made to this ill.
4151 	 * Lookup functions will return an error. Threads that try to
4152 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4153 	 * that the refcnt will drop down to zero.
4154 	 */
4155 	mutex_enter(&ill->ill_lock);
4156 	ill->ill_state_flags |= ILL_CONDEMNED;
4157 	for (ipif = ill->ill_ipif; ipif != NULL;
4158 	    ipif = ipif->ipif_next) {
4159 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4160 	}
4161 	/*
4162 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4163 	 * returns  error if ILL_CONDEMNED is set
4164 	 */
4165 	cv_broadcast(&ill->ill_cv);
4166 	mutex_exit(&ill->ill_lock);
4167 
4168 	/*
4169 	 * Send all the deferred DLPI messages downstream which came in
4170 	 * during the small window right before ipsq_enter(). We do this
4171 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4172 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4173 	 */
4174 	ill_dlpi_send_deferred(ill);
4175 
4176 	/*
4177 	 * Shut down fragmentation reassembly.
4178 	 * ill_frag_timer won't start a timer again.
4179 	 * Now cancel any existing timer
4180 	 */
4181 	(void) untimeout(ill->ill_frag_timer_id);
4182 	(void) ill_frag_timeout(ill, 0);
4183 
4184 	/*
4185 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4186 	 * this ill. Then wait for the refcnts to drop to zero.
4187 	 * ill_is_freeable checks whether the ill is really quiescent.
4188 	 * Then make sure that threads that are waiting to enter the
4189 	 * ipsq have seen the error returned by ipsq_enter and have
4190 	 * gone away. Then we call ill_delete_tail which does the
4191 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4192 	 */
4193 	ill_delete(ill);
4194 	mutex_enter(&ill->ill_lock);
4195 	while (!ill_is_freeable(ill))
4196 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4197 
4198 	while (ill->ill_waiters)
4199 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4200 
4201 	mutex_exit(&ill->ill_lock);
4202 
4203 	/*
4204 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4205 	 * it held until the end of the function since the cleanup
4206 	 * below needs to be able to use the ip_stack_t.
4207 	 */
4208 	netstack_hold(ipst->ips_netstack);
4209 
4210 	/* qprocsoff is done via ill_delete_tail */
4211 	ill_delete_tail(ill);
4212 	/*
4213 	 * synchronously wait for arp stream to unbind. After this, we
4214 	 * cannot get any data packets up from the driver.
4215 	 */
4216 	arp_unbind_complete(ill);
4217 	ASSERT(ill->ill_ipst == NULL);
4218 
4219 	/*
4220 	 * Walk through all conns and qenable those that have queued data.
4221 	 * Close synchronization needs this to
4222 	 * be done to ensure that all upper layers blocked
4223 	 * due to flow control to the closing device
4224 	 * get unblocked.
4225 	 */
4226 	ip1dbg(("ip_wsrv: walking\n"));
4227 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4228 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4229 	}
4230 
4231 	/*
4232 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4233 	 * stream is being torn down before ARP was plumbed (e.g.,
4234 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4235 	 * an error
4236 	 */
4237 	if (ai != NULL) {
4238 		ASSERT(!ill->ill_isv6);
4239 		mutex_enter(&ai->ai_lock);
4240 		ai->ai_ill = NULL;
4241 		if (ai->ai_arl == NULL) {
4242 			mutex_destroy(&ai->ai_lock);
4243 			kmem_free(ai, sizeof (*ai));
4244 		} else {
4245 			cv_signal(&ai->ai_ill_unplumb_done);
4246 			mutex_exit(&ai->ai_lock);
4247 		}
4248 	}
4249 
4250 	mutex_enter(&ipst->ips_ip_mi_lock);
4251 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4252 	mutex_exit(&ipst->ips_ip_mi_lock);
4253 
4254 	/*
4255 	 * credp could be null if the open didn't succeed and ip_modopen
4256 	 * itself calls ip_close.
4257 	 */
4258 	if (ill->ill_credp != NULL)
4259 		crfree(ill->ill_credp);
4260 
4261 	mutex_destroy(&ill->ill_saved_ire_lock);
4262 	mutex_destroy(&ill->ill_lock);
4263 	rw_destroy(&ill->ill_mcast_lock);
4264 	mutex_destroy(&ill->ill_mcast_serializer);
4265 	list_destroy(&ill->ill_nce);
4266 
4267 	/*
4268 	 * Now we are done with the module close pieces that
4269 	 * need the netstack_t.
4270 	 */
4271 	netstack_rele(ipst->ips_netstack);
4272 
4273 	mi_close_free((IDP)ill);
4274 	q->q_ptr = WR(q)->q_ptr = NULL;
4275 
4276 	ipsq_exit(ipsq);
4277 
4278 	return (0);
4279 }
4280 
4281 /*
4282  * This is called as part of close() for IP, UDP, ICMP, and RTS
4283  * in order to quiesce the conn.
4284  */
4285 void
4286 ip_quiesce_conn(conn_t *connp)
4287 {
4288 	boolean_t	drain_cleanup_reqd = B_FALSE;
4289 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4290 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4291 	ip_stack_t	*ipst;
4292 
4293 	ASSERT(!IPCL_IS_TCP(connp));
4294 	ipst = connp->conn_netstack->netstack_ip;
4295 
4296 	/*
4297 	 * Mark the conn as closing, and this conn must not be
4298 	 * inserted in future into any list. Eg. conn_drain_insert(),
4299 	 * won't insert this conn into the conn_drain_list.
4300 	 *
4301 	 * conn_idl, and conn_ilg cannot get set henceforth.
4302 	 */
4303 	mutex_enter(&connp->conn_lock);
4304 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4305 	connp->conn_state_flags |= CONN_CLOSING;
4306 	if (connp->conn_idl != NULL)
4307 		drain_cleanup_reqd = B_TRUE;
4308 	if (connp->conn_oper_pending_ill != NULL)
4309 		conn_ioctl_cleanup_reqd = B_TRUE;
4310 	if (connp->conn_dhcpinit_ill != NULL) {
4311 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4312 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4313 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4314 		connp->conn_dhcpinit_ill = NULL;
4315 	}
4316 	if (connp->conn_ilg != NULL)
4317 		ilg_cleanup_reqd = B_TRUE;
4318 	mutex_exit(&connp->conn_lock);
4319 
4320 	if (conn_ioctl_cleanup_reqd)
4321 		conn_ioctl_cleanup(connp);
4322 
4323 	if (is_system_labeled() && connp->conn_anon_port) {
4324 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4325 		    connp->conn_mlp_type, connp->conn_proto,
4326 		    ntohs(connp->conn_lport), B_FALSE);
4327 		connp->conn_anon_port = 0;
4328 	}
4329 	connp->conn_mlp_type = mlptSingle;
4330 
4331 	/*
4332 	 * Remove this conn from any fanout list it is on.
4333 	 * and then wait for any threads currently operating
4334 	 * on this endpoint to finish
4335 	 */
4336 	ipcl_hash_remove(connp);
4337 
4338 	/*
4339 	 * Remove this conn from the drain list, and do
4340 	 * any other cleanup that may be required.
4341 	 * (Only non-tcp conns may have a non-null conn_idl.
4342 	 * TCP conns are never flow controlled, and
4343 	 * conn_idl will be null)
4344 	 */
4345 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4346 		mutex_enter(&connp->conn_idl->idl_lock);
4347 		conn_drain_tail(connp, B_TRUE);
4348 		mutex_exit(&connp->conn_idl->idl_lock);
4349 	}
4350 
4351 	if (connp == ipst->ips_ip_g_mrouter)
4352 		(void) ip_mrouter_done(ipst);
4353 
4354 	if (ilg_cleanup_reqd)
4355 		ilg_delete_all(connp);
4356 
4357 	/*
4358 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4359 	 * callers from write side can't be there now because close
4360 	 * is in progress. The only other caller is ipcl_walk
4361 	 * which checks for the condemned flag.
4362 	 */
4363 	mutex_enter(&connp->conn_lock);
4364 	connp->conn_state_flags |= CONN_CONDEMNED;
4365 	while (connp->conn_ref != 1)
4366 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4367 	connp->conn_state_flags |= CONN_QUIESCED;
4368 	mutex_exit(&connp->conn_lock);
4369 }
4370 
4371 /* ARGSUSED */
4372 int
4373 ip_close(queue_t *q, int flags)
4374 {
4375 	conn_t		*connp;
4376 
4377 	/*
4378 	 * Call the appropriate delete routine depending on whether this is
4379 	 * a module or device.
4380 	 */
4381 	if (WR(q)->q_next != NULL) {
4382 		/* This is a module close */
4383 		return (ip_modclose((ill_t *)q->q_ptr));
4384 	}
4385 
4386 	connp = q->q_ptr;
4387 	ip_quiesce_conn(connp);
4388 
4389 	qprocsoff(q);
4390 
4391 	/*
4392 	 * Now we are truly single threaded on this stream, and can
4393 	 * delete the things hanging off the connp, and finally the connp.
4394 	 * We removed this connp from the fanout list, it cannot be
4395 	 * accessed thru the fanouts, and we already waited for the
4396 	 * conn_ref to drop to 0. We are already in close, so
4397 	 * there cannot be any other thread from the top. qprocsoff
4398 	 * has completed, and service has completed or won't run in
4399 	 * future.
4400 	 */
4401 	ASSERT(connp->conn_ref == 1);
4402 
4403 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4404 
4405 	connp->conn_ref--;
4406 	ipcl_conn_destroy(connp);
4407 
4408 	q->q_ptr = WR(q)->q_ptr = NULL;
4409 	return (0);
4410 }
4411 
4412 /*
4413  * Wapper around putnext() so that ip_rts_request can merely use
4414  * conn_recv.
4415  */
4416 /*ARGSUSED2*/
4417 static void
4418 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4419 {
4420 	conn_t *connp = (conn_t *)arg1;
4421 
4422 	putnext(connp->conn_rq, mp);
4423 }
4424 
4425 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4426 /* ARGSUSED */
4427 static void
4428 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4429 {
4430 	freemsg(mp);
4431 }
4432 
4433 /*
4434  * Called when the module is about to be unloaded
4435  */
4436 void
4437 ip_ddi_destroy(void)
4438 {
4439 	tnet_fini();
4440 
4441 	icmp_ddi_g_destroy();
4442 	rts_ddi_g_destroy();
4443 	udp_ddi_g_destroy();
4444 	sctp_ddi_g_destroy();
4445 	tcp_ddi_g_destroy();
4446 	ilb_ddi_g_destroy();
4447 	dce_g_destroy();
4448 	ipsec_policy_g_destroy();
4449 	ipcl_g_destroy();
4450 	ip_net_g_destroy();
4451 	ip_ire_g_fini();
4452 	inet_minor_destroy(ip_minor_arena_sa);
4453 #if defined(_LP64)
4454 	inet_minor_destroy(ip_minor_arena_la);
4455 #endif
4456 
4457 #ifdef DEBUG
4458 	list_destroy(&ip_thread_list);
4459 	rw_destroy(&ip_thread_rwlock);
4460 	tsd_destroy(&ip_thread_data);
4461 #endif
4462 
4463 	netstack_unregister(NS_IP);
4464 }
4465 
4466 /*
4467  * First step in cleanup.
4468  */
4469 /* ARGSUSED */
4470 static void
4471 ip_stack_shutdown(netstackid_t stackid, void *arg)
4472 {
4473 	ip_stack_t *ipst = (ip_stack_t *)arg;
4474 
4475 #ifdef NS_DEBUG
4476 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4477 #endif
4478 
4479 	/*
4480 	 * Perform cleanup for special interfaces (loopback and IPMP).
4481 	 */
4482 	ip_interface_cleanup(ipst);
4483 
4484 	/*
4485 	 * The *_hook_shutdown()s start the process of notifying any
4486 	 * consumers that things are going away.... nothing is destroyed.
4487 	 */
4488 	ipv4_hook_shutdown(ipst);
4489 	ipv6_hook_shutdown(ipst);
4490 	arp_hook_shutdown(ipst);
4491 
4492 	mutex_enter(&ipst->ips_capab_taskq_lock);
4493 	ipst->ips_capab_taskq_quit = B_TRUE;
4494 	cv_signal(&ipst->ips_capab_taskq_cv);
4495 	mutex_exit(&ipst->ips_capab_taskq_lock);
4496 }
4497 
4498 /*
4499  * Free the IP stack instance.
4500  */
4501 static void
4502 ip_stack_fini(netstackid_t stackid, void *arg)
4503 {
4504 	ip_stack_t *ipst = (ip_stack_t *)arg;
4505 	int ret;
4506 
4507 #ifdef NS_DEBUG
4508 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4509 #endif
4510 	/*
4511 	 * At this point, all of the notifications that the events and
4512 	 * protocols are going away have been run, meaning that we can
4513 	 * now set about starting to clean things up.
4514 	 */
4515 	ipobs_fini(ipst);
4516 	ipv4_hook_destroy(ipst);
4517 	ipv6_hook_destroy(ipst);
4518 	arp_hook_destroy(ipst);
4519 	ip_net_destroy(ipst);
4520 
4521 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4522 	cv_destroy(&ipst->ips_capab_taskq_cv);
4523 
4524 	ipmp_destroy(ipst);
4525 	rw_destroy(&ipst->ips_srcid_lock);
4526 
4527 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4528 	ipst->ips_ip_mibkp = NULL;
4529 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4530 	ipst->ips_icmp_mibkp = NULL;
4531 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4532 	ipst->ips_ip_kstat = NULL;
4533 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4534 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4535 	ipst->ips_ip6_kstat = NULL;
4536 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4537 
4538 	nd_free(&ipst->ips_ip_g_nd);
4539 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
4540 	ipst->ips_param_arr = NULL;
4541 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
4542 	ipst->ips_ndp_arr = NULL;
4543 
4544 	dce_stack_destroy(ipst);
4545 	ip_mrouter_stack_destroy(ipst);
4546 
4547 	mutex_destroy(&ipst->ips_ip_mi_lock);
4548 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4549 	rw_destroy(&ipst->ips_ip_g_nd_lock);
4550 
4551 	ret = untimeout(ipst->ips_igmp_timeout_id);
4552 	if (ret == -1) {
4553 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4554 	} else {
4555 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4556 		ipst->ips_igmp_timeout_id = 0;
4557 	}
4558 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4559 	if (ret == -1) {
4560 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4561 	} else {
4562 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4563 		ipst->ips_igmp_slowtimeout_id = 0;
4564 	}
4565 	ret = untimeout(ipst->ips_mld_timeout_id);
4566 	if (ret == -1) {
4567 		ASSERT(ipst->ips_mld_timeout_id == 0);
4568 	} else {
4569 		ASSERT(ipst->ips_mld_timeout_id != 0);
4570 		ipst->ips_mld_timeout_id = 0;
4571 	}
4572 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4573 	if (ret == -1) {
4574 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4575 	} else {
4576 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4577 		ipst->ips_mld_slowtimeout_id = 0;
4578 	}
4579 
4580 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4581 	mutex_destroy(&ipst->ips_mld_timer_lock);
4582 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4583 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4584 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4585 	rw_destroy(&ipst->ips_ill_g_lock);
4586 
4587 	ip_ire_fini(ipst);
4588 	ip6_asp_free(ipst);
4589 	conn_drain_fini(ipst);
4590 	ipcl_destroy(ipst);
4591 
4592 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4593 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4594 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4595 	ipst->ips_ndp4 = NULL;
4596 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4597 	ipst->ips_ndp6 = NULL;
4598 
4599 	if (ipst->ips_loopback_ksp != NULL) {
4600 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4601 		ipst->ips_loopback_ksp = NULL;
4602 	}
4603 
4604 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4605 	ipst->ips_phyint_g_list = NULL;
4606 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4607 	ipst->ips_ill_g_heads = NULL;
4608 
4609 	ldi_ident_release(ipst->ips_ldi_ident);
4610 	kmem_free(ipst, sizeof (*ipst));
4611 }
4612 
4613 /*
4614  * This function is called from the TSD destructor, and is used to debug
4615  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4616  * details.
4617  */
4618 static void
4619 ip_thread_exit(void *phash)
4620 {
4621 	th_hash_t *thh = phash;
4622 
4623 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4624 	list_remove(&ip_thread_list, thh);
4625 	rw_exit(&ip_thread_rwlock);
4626 	mod_hash_destroy_hash(thh->thh_hash);
4627 	kmem_free(thh, sizeof (*thh));
4628 }
4629 
4630 /*
4631  * Called when the IP kernel module is loaded into the kernel
4632  */
4633 void
4634 ip_ddi_init(void)
4635 {
4636 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4637 
4638 	/*
4639 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4640 	 * initial devices: ip, ip6, tcp, tcp6.
4641 	 */
4642 	/*
4643 	 * If this is a 64-bit kernel, then create two separate arenas -
4644 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4645 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4646 	 */
4647 	ip_minor_arena_la = NULL;
4648 	ip_minor_arena_sa = NULL;
4649 #if defined(_LP64)
4650 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4651 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4652 		cmn_err(CE_PANIC,
4653 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4654 	}
4655 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4656 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4657 		cmn_err(CE_PANIC,
4658 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4659 	}
4660 #else
4661 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4662 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4663 		cmn_err(CE_PANIC,
4664 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4665 	}
4666 #endif
4667 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4668 
4669 	ipcl_g_init();
4670 	ip_ire_g_init();
4671 	ip_net_g_init();
4672 
4673 #ifdef DEBUG
4674 	tsd_create(&ip_thread_data, ip_thread_exit);
4675 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4676 	list_create(&ip_thread_list, sizeof (th_hash_t),
4677 	    offsetof(th_hash_t, thh_link));
4678 #endif
4679 	ipsec_policy_g_init();
4680 	tcp_ddi_g_init();
4681 	sctp_ddi_g_init();
4682 	dce_g_init();
4683 
4684 	/*
4685 	 * We want to be informed each time a stack is created or
4686 	 * destroyed in the kernel, so we can maintain the
4687 	 * set of udp_stack_t's.
4688 	 */
4689 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4690 	    ip_stack_fini);
4691 
4692 	tnet_init();
4693 
4694 	udp_ddi_g_init();
4695 	rts_ddi_g_init();
4696 	icmp_ddi_g_init();
4697 	ilb_ddi_g_init();
4698 }
4699 
4700 /*
4701  * Initialize the IP stack instance.
4702  */
4703 static void *
4704 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4705 {
4706 	ip_stack_t	*ipst;
4707 	ipparam_t	*pa;
4708 	ipndp_t		*na;
4709 	major_t		major;
4710 
4711 #ifdef NS_DEBUG
4712 	printf("ip_stack_init(stack %d)\n", stackid);
4713 #endif
4714 
4715 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4716 	ipst->ips_netstack = ns;
4717 
4718 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4719 	    KM_SLEEP);
4720 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4721 	    KM_SLEEP);
4722 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4723 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4724 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4725 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4726 
4727 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
4728 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4729 	ipst->ips_igmp_deferred_next = INFINITY;
4730 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4731 	ipst->ips_mld_deferred_next = INFINITY;
4732 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4733 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4734 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4735 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4736 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4737 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4738 
4739 	ipcl_init(ipst);
4740 	ip_ire_init(ipst);
4741 	ip6_asp_init(ipst);
4742 	ipif_init(ipst);
4743 	conn_drain_init(ipst);
4744 	ip_mrouter_stack_init(ipst);
4745 	dce_stack_init(ipst);
4746 
4747 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
4748 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
4749 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
4750 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
4751 
4752 	ipst->ips_ip_multirt_log_interval = 1000;
4753 
4754 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
4755 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
4756 	ipst->ips_ill_index = 1;
4757 
4758 	ipst->ips_saved_ip_g_forward = -1;
4759 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4760 
4761 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
4762 	ipst->ips_param_arr = pa;
4763 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
4764 
4765 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
4766 	ipst->ips_ndp_arr = na;
4767 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
4768 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
4769 	    (caddr_t)&ipst->ips_ip_g_forward;
4770 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
4771 	    (caddr_t)&ipst->ips_ipv6_forward;
4772 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
4773 	    "ip_cgtp_filter") == 0);
4774 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
4775 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
4776 
4777 	(void) ip_param_register(&ipst->ips_ip_g_nd,
4778 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
4779 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
4780 
4781 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4782 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4783 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4784 	ipst->ips_ip6_kstat =
4785 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4786 
4787 	ipst->ips_ip_src_id = 1;
4788 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4789 
4790 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4791 
4792 	ip_net_init(ipst, ns);
4793 	ipv4_hook_init(ipst);
4794 	ipv6_hook_init(ipst);
4795 	arp_hook_init(ipst);
4796 	ipmp_init(ipst);
4797 	ipobs_init(ipst);
4798 
4799 	/*
4800 	 * Create the taskq dispatcher thread and initialize related stuff.
4801 	 */
4802 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4803 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4804 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4805 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4806 
4807 	major = mod_name_to_major(INET_NAME);
4808 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4809 	return (ipst);
4810 }
4811 
4812 /*
4813  * Allocate and initialize a DLPI template of the specified length.  (May be
4814  * called as writer.)
4815  */
4816 mblk_t *
4817 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4818 {
4819 	mblk_t	*mp;
4820 
4821 	mp = allocb(len, BPRI_MED);
4822 	if (!mp)
4823 		return (NULL);
4824 
4825 	/*
4826 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4827 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4828 	 * that other DLPI are M_PROTO.
4829 	 */
4830 	if (prim == DL_INFO_REQ) {
4831 		mp->b_datap->db_type = M_PCPROTO;
4832 	} else {
4833 		mp->b_datap->db_type = M_PROTO;
4834 	}
4835 
4836 	mp->b_wptr = mp->b_rptr + len;
4837 	bzero(mp->b_rptr, len);
4838 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4839 	return (mp);
4840 }
4841 
4842 /*
4843  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4844  */
4845 mblk_t *
4846 ip_dlnotify_alloc(uint_t notification, uint_t data)
4847 {
4848 	dl_notify_ind_t	*notifyp;
4849 	mblk_t		*mp;
4850 
4851 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4852 		return (NULL);
4853 
4854 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4855 	notifyp->dl_notification = notification;
4856 	notifyp->dl_data = data;
4857 	return (mp);
4858 }
4859 
4860 /*
4861  * Debug formatting routine.  Returns a character string representation of the
4862  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4863  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4864  *
4865  * Once the ndd table-printing interfaces are removed, this can be changed to
4866  * standard dotted-decimal form.
4867  */
4868 char *
4869 ip_dot_addr(ipaddr_t addr, char *buf)
4870 {
4871 	uint8_t *ap = (uint8_t *)&addr;
4872 
4873 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4874 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4875 	return (buf);
4876 }
4877 
4878 /*
4879  * Write the given MAC address as a printable string in the usual colon-
4880  * separated format.
4881  */
4882 const char *
4883 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4884 {
4885 	char *bp;
4886 
4887 	if (alen == 0 || buflen < 4)
4888 		return ("?");
4889 	bp = buf;
4890 	for (;;) {
4891 		/*
4892 		 * If there are more MAC address bytes available, but we won't
4893 		 * have any room to print them, then add "..." to the string
4894 		 * instead.  See below for the 'magic number' explanation.
4895 		 */
4896 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4897 			(void) strcpy(bp, "...");
4898 			break;
4899 		}
4900 		(void) sprintf(bp, "%02x", *addr++);
4901 		bp += 2;
4902 		if (--alen == 0)
4903 			break;
4904 		*bp++ = ':';
4905 		buflen -= 3;
4906 		/*
4907 		 * At this point, based on the first 'if' statement above,
4908 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4909 		 * buflen >= 4.  The first case leaves room for the final "xx"
4910 		 * number and trailing NUL byte.  The second leaves room for at
4911 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4912 		 * that statement.
4913 		 */
4914 	}
4915 	return (buf);
4916 }
4917 
4918 /*
4919  * Called when it is conceptually a ULP that would sent the packet
4920  * e.g., port unreachable and protocol unreachable. Check that the packet
4921  * would have passed the IPsec global policy before sending the error.
4922  *
4923  * Send an ICMP error after patching up the packet appropriately.
4924  * Uses ip_drop_input and bumps the appropriate MIB.
4925  */
4926 void
4927 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4928     ip_recv_attr_t *ira)
4929 {
4930 	ipha_t		*ipha;
4931 	boolean_t	secure;
4932 	ill_t		*ill = ira->ira_ill;
4933 	ip_stack_t	*ipst = ill->ill_ipst;
4934 	netstack_t	*ns = ipst->ips_netstack;
4935 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4936 
4937 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4938 
4939 	/*
4940 	 * We are generating an icmp error for some inbound packet.
4941 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4942 	 * Before we generate an error, check with global policy
4943 	 * to see whether this is allowed to enter the system. As
4944 	 * there is no "conn", we are checking with global policy.
4945 	 */
4946 	ipha = (ipha_t *)mp->b_rptr;
4947 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4948 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4949 		if (mp == NULL)
4950 			return;
4951 	}
4952 
4953 	/* We never send errors for protocols that we do implement */
4954 	if (ira->ira_protocol == IPPROTO_ICMP ||
4955 	    ira->ira_protocol == IPPROTO_IGMP) {
4956 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4957 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4958 		freemsg(mp);
4959 		return;
4960 	}
4961 	/*
4962 	 * Have to correct checksum since
4963 	 * the packet might have been
4964 	 * fragmented and the reassembly code in ip_rput
4965 	 * does not restore the IP checksum.
4966 	 */
4967 	ipha->ipha_hdr_checksum = 0;
4968 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4969 
4970 	switch (icmp_type) {
4971 	case ICMP_DEST_UNREACHABLE:
4972 		switch (icmp_code) {
4973 		case ICMP_PROTOCOL_UNREACHABLE:
4974 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4975 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4976 			break;
4977 		case ICMP_PORT_UNREACHABLE:
4978 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4979 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4980 			break;
4981 		}
4982 
4983 		icmp_unreachable(mp, icmp_code, ira);
4984 		break;
4985 	default:
4986 #ifdef DEBUG
4987 		panic("ip_fanout_send_icmp_v4: wrong type");
4988 		/*NOTREACHED*/
4989 #else
4990 		freemsg(mp);
4991 		break;
4992 #endif
4993 	}
4994 }
4995 
4996 /*
4997  * Used to send an ICMP error message when a packet is received for
4998  * a protocol that is not supported. The mblk passed as argument
4999  * is consumed by this function.
5000  */
5001 void
5002 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
5003 {
5004 	ipha_t		*ipha;
5005 
5006 	ipha = (ipha_t *)mp->b_rptr;
5007 	if (ira->ira_flags & IRAF_IS_IPV4) {
5008 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
5009 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5010 		    ICMP_PROTOCOL_UNREACHABLE, ira);
5011 	} else {
5012 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
5013 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
5014 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
5015 	}
5016 }
5017 
5018 /*
5019  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
5020  * Handles IPv4 and IPv6.
5021  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5022  * Caller is responsible for dropping references to the conn.
5023  */
5024 void
5025 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5026     ip_recv_attr_t *ira)
5027 {
5028 	ill_t		*ill = ira->ira_ill;
5029 	ip_stack_t	*ipst = ill->ill_ipst;
5030 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5031 	boolean_t	secure;
5032 	uint_t		protocol = ira->ira_protocol;
5033 	iaflags_t	iraflags = ira->ira_flags;
5034 	queue_t		*rq;
5035 
5036 	secure = iraflags & IRAF_IPSEC_SECURE;
5037 
5038 	rq = connp->conn_rq;
5039 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
5040 		switch (protocol) {
5041 		case IPPROTO_ICMPV6:
5042 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
5043 			break;
5044 		case IPPROTO_ICMP:
5045 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
5046 			break;
5047 		default:
5048 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
5049 			break;
5050 		}
5051 		freemsg(mp);
5052 		return;
5053 	}
5054 
5055 	ASSERT(!(IPCL_IS_IPTUN(connp)));
5056 
5057 	if (((iraflags & IRAF_IS_IPV4) ?
5058 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5059 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5060 	    secure) {
5061 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5062 		    ip6h, ira);
5063 		if (mp == NULL) {
5064 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5065 			/* Note that mp is NULL */
5066 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5067 			return;
5068 		}
5069 	}
5070 
5071 	if (iraflags & IRAF_ICMP_ERROR) {
5072 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5073 	} else {
5074 		ill_t *rill = ira->ira_rill;
5075 
5076 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5077 		ira->ira_ill = ira->ira_rill = NULL;
5078 		/* Send it upstream */
5079 		(connp->conn_recv)(connp, mp, NULL, ira);
5080 		ira->ira_ill = ill;
5081 		ira->ira_rill = rill;
5082 	}
5083 }
5084 
5085 /*
5086  * Handle protocols with which IP is less intimate.  There
5087  * can be more than one stream bound to a particular
5088  * protocol.  When this is the case, normally each one gets a copy
5089  * of any incoming packets.
5090  *
5091  * IPsec NOTE :
5092  *
5093  * Don't allow a secure packet going up a non-secure connection.
5094  * We don't allow this because
5095  *
5096  * 1) Reply might go out in clear which will be dropped at
5097  *    the sending side.
5098  * 2) If the reply goes out in clear it will give the
5099  *    adversary enough information for getting the key in
5100  *    most of the cases.
5101  *
5102  * Moreover getting a secure packet when we expect clear
5103  * implies that SA's were added without checking for
5104  * policy on both ends. This should not happen once ISAKMP
5105  * is used to negotiate SAs as SAs will be added only after
5106  * verifying the policy.
5107  *
5108  * Zones notes:
5109  * Earlier in ip_input on a system with multiple shared-IP zones we
5110  * duplicate the multicast and broadcast packets and send them up
5111  * with each explicit zoneid that exists on that ill.
5112  * This means that here we can match the zoneid with SO_ALLZONES being special.
5113  */
5114 void
5115 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
5116 {
5117 	mblk_t		*mp1;
5118 	ipaddr_t	laddr;
5119 	conn_t		*connp, *first_connp, *next_connp;
5120 	connf_t		*connfp;
5121 	ill_t		*ill = ira->ira_ill;
5122 	ip_stack_t	*ipst = ill->ill_ipst;
5123 
5124 	laddr = ipha->ipha_dst;
5125 
5126 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
5127 	mutex_enter(&connfp->connf_lock);
5128 	connp = connfp->connf_head;
5129 	for (connp = connfp->connf_head; connp != NULL;
5130 	    connp = connp->conn_next) {
5131 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5132 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5133 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5134 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
5135 			break;
5136 		}
5137 	}
5138 
5139 	if (connp == NULL) {
5140 		/*
5141 		 * No one bound to these addresses.  Is
5142 		 * there a client that wants all
5143 		 * unclaimed datagrams?
5144 		 */
5145 		mutex_exit(&connfp->connf_lock);
5146 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5147 		    ICMP_PROTOCOL_UNREACHABLE, ira);
5148 		return;
5149 	}
5150 
5151 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5152 
5153 	CONN_INC_REF(connp);
5154 	first_connp = connp;
5155 	connp = connp->conn_next;
5156 
5157 	for (;;) {
5158 		while (connp != NULL) {
5159 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5160 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5161 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5162 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5163 			    ira, connp)))
5164 				break;
5165 			connp = connp->conn_next;
5166 		}
5167 
5168 		if (connp == NULL) {
5169 			/* No more interested clients */
5170 			connp = first_connp;
5171 			break;
5172 		}
5173 		if (((mp1 = dupmsg(mp)) == NULL) &&
5174 		    ((mp1 = copymsg(mp)) == NULL)) {
5175 			/* Memory allocation failed */
5176 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5177 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5178 			connp = first_connp;
5179 			break;
5180 		}
5181 
5182 		CONN_INC_REF(connp);
5183 		mutex_exit(&connfp->connf_lock);
5184 
5185 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5186 		    ira);
5187 
5188 		mutex_enter(&connfp->connf_lock);
5189 		/* Follow the next pointer before releasing the conn. */
5190 		next_connp = connp->conn_next;
5191 		CONN_DEC_REF(connp);
5192 		connp = next_connp;
5193 	}
5194 
5195 	/* Last one.  Send it upstream. */
5196 	mutex_exit(&connfp->connf_lock);
5197 
5198 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5199 
5200 	CONN_DEC_REF(connp);
5201 }
5202 
5203 /*
5204  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5205  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5206  * is not consumed.
5207  *
5208  * One of three things can happen, all of which affect the passed-in mblk:
5209  *
5210  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5211  *
5212  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5213  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5214  *
5215  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5216  */
5217 mblk_t *
5218 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5219 {
5220 	int shift, plen, iph_len;
5221 	ipha_t *ipha;
5222 	udpha_t *udpha;
5223 	uint32_t *spi;
5224 	uint32_t esp_ports;
5225 	uint8_t *orptr;
5226 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5227 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5228 
5229 	ipha = (ipha_t *)mp->b_rptr;
5230 	iph_len = ira->ira_ip_hdr_length;
5231 	plen = ira->ira_pktlen;
5232 
5233 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5234 		/*
5235 		 * Most likely a keepalive for the benefit of an intervening
5236 		 * NAT.  These aren't for us, per se, so drop it.
5237 		 *
5238 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5239 		 * byte packets (keepalives are 1-byte), but we'll drop them
5240 		 * also.
5241 		 */
5242 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5243 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5244 		return (NULL);
5245 	}
5246 
5247 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5248 		/* might as well pull it all up - it might be ESP. */
5249 		if (!pullupmsg(mp, -1)) {
5250 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5251 			    DROPPER(ipss, ipds_esp_nomem),
5252 			    &ipss->ipsec_dropper);
5253 			return (NULL);
5254 		}
5255 
5256 		ipha = (ipha_t *)mp->b_rptr;
5257 	}
5258 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5259 	if (*spi == 0) {
5260 		/* UDP packet - remove 0-spi. */
5261 		shift = sizeof (uint32_t);
5262 	} else {
5263 		/* ESP-in-UDP packet - reduce to ESP. */
5264 		ipha->ipha_protocol = IPPROTO_ESP;
5265 		shift = sizeof (udpha_t);
5266 	}
5267 
5268 	/* Fix IP header */
5269 	ira->ira_pktlen = (plen - shift);
5270 	ipha->ipha_length = htons(ira->ira_pktlen);
5271 	ipha->ipha_hdr_checksum = 0;
5272 
5273 	orptr = mp->b_rptr;
5274 	mp->b_rptr += shift;
5275 
5276 	udpha = (udpha_t *)(orptr + iph_len);
5277 	if (*spi == 0) {
5278 		ASSERT((uint8_t *)ipha == orptr);
5279 		udpha->uha_length = htons(plen - shift - iph_len);
5280 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5281 		esp_ports = 0;
5282 	} else {
5283 		esp_ports = *((uint32_t *)udpha);
5284 		ASSERT(esp_ports != 0);
5285 	}
5286 	ovbcopy(orptr, orptr + shift, iph_len);
5287 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5288 		ipha = (ipha_t *)(orptr + shift);
5289 
5290 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5291 		ira->ira_esp_udp_ports = esp_ports;
5292 		ip_fanout_v4(mp, ipha, ira);
5293 		return (NULL);
5294 	}
5295 	return (mp);
5296 }
5297 
5298 /*
5299  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5300  * Handles IPv4 and IPv6.
5301  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5302  * Caller is responsible for dropping references to the conn.
5303  */
5304 void
5305 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5306     ip_recv_attr_t *ira)
5307 {
5308 	ill_t		*ill = ira->ira_ill;
5309 	ip_stack_t	*ipst = ill->ill_ipst;
5310 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5311 	boolean_t	secure;
5312 	iaflags_t	iraflags = ira->ira_flags;
5313 
5314 	secure = iraflags & IRAF_IPSEC_SECURE;
5315 
5316 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5317 	    !canputnext(connp->conn_rq)) {
5318 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5319 		freemsg(mp);
5320 		return;
5321 	}
5322 
5323 	if (((iraflags & IRAF_IS_IPV4) ?
5324 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5325 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5326 	    secure) {
5327 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5328 		    ip6h, ira);
5329 		if (mp == NULL) {
5330 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5331 			/* Note that mp is NULL */
5332 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5333 			return;
5334 		}
5335 	}
5336 
5337 	/*
5338 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5339 	 * check. Only ip_fanout_v4 has that check.
5340 	 */
5341 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5342 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5343 	} else {
5344 		ill_t *rill = ira->ira_rill;
5345 
5346 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5347 		ira->ira_ill = ira->ira_rill = NULL;
5348 		/* Send it upstream */
5349 		(connp->conn_recv)(connp, mp, NULL, ira);
5350 		ira->ira_ill = ill;
5351 		ira->ira_rill = rill;
5352 	}
5353 }
5354 
5355 /*
5356  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5357  * (Unicast fanout is handled in ip_input_v4.)
5358  *
5359  * If SO_REUSEADDR is set all multicast and broadcast packets
5360  * will be delivered to all conns bound to the same port.
5361  *
5362  * If there is at least one matching AF_INET receiver, then we will
5363  * ignore any AF_INET6 receivers.
5364  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5365  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5366  * packets.
5367  *
5368  * Zones notes:
5369  * Earlier in ip_input on a system with multiple shared-IP zones we
5370  * duplicate the multicast and broadcast packets and send them up
5371  * with each explicit zoneid that exists on that ill.
5372  * This means that here we can match the zoneid with SO_ALLZONES being special.
5373  */
5374 void
5375 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5376     ip_recv_attr_t *ira)
5377 {
5378 	ipaddr_t	laddr;
5379 	in6_addr_t	v6faddr;
5380 	conn_t		*connp;
5381 	connf_t		*connfp;
5382 	ipaddr_t	faddr;
5383 	ill_t		*ill = ira->ira_ill;
5384 	ip_stack_t	*ipst = ill->ill_ipst;
5385 
5386 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5387 
5388 	laddr = ipha->ipha_dst;
5389 	faddr = ipha->ipha_src;
5390 
5391 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5392 	mutex_enter(&connfp->connf_lock);
5393 	connp = connfp->connf_head;
5394 
5395 	/*
5396 	 * If SO_REUSEADDR has been set on the first we send the
5397 	 * packet to all clients that have joined the group and
5398 	 * match the port.
5399 	 */
5400 	while (connp != NULL) {
5401 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5402 		    conn_wantpacket(connp, ira, ipha) &&
5403 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5404 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5405 			break;
5406 		connp = connp->conn_next;
5407 	}
5408 
5409 	if (connp == NULL)
5410 		goto notfound;
5411 
5412 	CONN_INC_REF(connp);
5413 
5414 	if (connp->conn_reuseaddr) {
5415 		conn_t		*first_connp = connp;
5416 		conn_t		*next_connp;
5417 		mblk_t		*mp1;
5418 
5419 		connp = connp->conn_next;
5420 		for (;;) {
5421 			while (connp != NULL) {
5422 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5423 				    fport, faddr) &&
5424 				    conn_wantpacket(connp, ira, ipha) &&
5425 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5426 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5427 				    ira, connp)))
5428 					break;
5429 				connp = connp->conn_next;
5430 			}
5431 			if (connp == NULL) {
5432 				/* No more interested clients */
5433 				connp = first_connp;
5434 				break;
5435 			}
5436 			if (((mp1 = dupmsg(mp)) == NULL) &&
5437 			    ((mp1 = copymsg(mp)) == NULL)) {
5438 				/* Memory allocation failed */
5439 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5440 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5441 				connp = first_connp;
5442 				break;
5443 			}
5444 			CONN_INC_REF(connp);
5445 			mutex_exit(&connfp->connf_lock);
5446 
5447 			IP_STAT(ipst, ip_udp_fanmb);
5448 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5449 			    NULL, ira);
5450 			mutex_enter(&connfp->connf_lock);
5451 			/* Follow the next pointer before releasing the conn */
5452 			next_connp = connp->conn_next;
5453 			CONN_DEC_REF(connp);
5454 			connp = next_connp;
5455 		}
5456 	}
5457 
5458 	/* Last one.  Send it upstream. */
5459 	mutex_exit(&connfp->connf_lock);
5460 	IP_STAT(ipst, ip_udp_fanmb);
5461 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5462 	CONN_DEC_REF(connp);
5463 	return;
5464 
5465 notfound:
5466 	mutex_exit(&connfp->connf_lock);
5467 	/*
5468 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5469 	 * have already been matched above, since they live in the IPv4
5470 	 * fanout tables. This implies we only need to
5471 	 * check for IPv6 in6addr_any endpoints here.
5472 	 * Thus we compare using ipv6_all_zeros instead of the destination
5473 	 * address, except for the multicast group membership lookup which
5474 	 * uses the IPv4 destination.
5475 	 */
5476 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5477 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5478 	mutex_enter(&connfp->connf_lock);
5479 	connp = connfp->connf_head;
5480 	/*
5481 	 * IPv4 multicast packet being delivered to an AF_INET6
5482 	 * in6addr_any endpoint.
5483 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5484 	 * and not conn_wantpacket_v6() since any multicast membership is
5485 	 * for an IPv4-mapped multicast address.
5486 	 */
5487 	while (connp != NULL) {
5488 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5489 		    fport, v6faddr) &&
5490 		    conn_wantpacket(connp, ira, ipha) &&
5491 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5492 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5493 			break;
5494 		connp = connp->conn_next;
5495 	}
5496 
5497 	if (connp == NULL) {
5498 		/*
5499 		 * No one bound to this port.  Is
5500 		 * there a client that wants all
5501 		 * unclaimed datagrams?
5502 		 */
5503 		mutex_exit(&connfp->connf_lock);
5504 
5505 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5506 		    NULL) {
5507 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5508 			ip_fanout_proto_v4(mp, ipha, ira);
5509 		} else {
5510 			/*
5511 			 * We used to attempt to send an icmp error here, but
5512 			 * since this is known to be a multicast packet
5513 			 * and we don't send icmp errors in response to
5514 			 * multicast, just drop the packet and give up sooner.
5515 			 */
5516 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5517 			freemsg(mp);
5518 		}
5519 		return;
5520 	}
5521 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5522 
5523 	/*
5524 	 * If SO_REUSEADDR has been set on the first we send the
5525 	 * packet to all clients that have joined the group and
5526 	 * match the port.
5527 	 */
5528 	if (connp->conn_reuseaddr) {
5529 		conn_t		*first_connp = connp;
5530 		conn_t		*next_connp;
5531 		mblk_t		*mp1;
5532 
5533 		CONN_INC_REF(connp);
5534 		connp = connp->conn_next;
5535 		for (;;) {
5536 			while (connp != NULL) {
5537 				if (IPCL_UDP_MATCH_V6(connp, lport,
5538 				    ipv6_all_zeros, fport, v6faddr) &&
5539 				    conn_wantpacket(connp, ira, ipha) &&
5540 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5541 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5542 				    ira, connp)))
5543 					break;
5544 				connp = connp->conn_next;
5545 			}
5546 			if (connp == NULL) {
5547 				/* No more interested clients */
5548 				connp = first_connp;
5549 				break;
5550 			}
5551 			if (((mp1 = dupmsg(mp)) == NULL) &&
5552 			    ((mp1 = copymsg(mp)) == NULL)) {
5553 				/* Memory allocation failed */
5554 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5555 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5556 				connp = first_connp;
5557 				break;
5558 			}
5559 			CONN_INC_REF(connp);
5560 			mutex_exit(&connfp->connf_lock);
5561 
5562 			IP_STAT(ipst, ip_udp_fanmb);
5563 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5564 			    NULL, ira);
5565 			mutex_enter(&connfp->connf_lock);
5566 			/* Follow the next pointer before releasing the conn */
5567 			next_connp = connp->conn_next;
5568 			CONN_DEC_REF(connp);
5569 			connp = next_connp;
5570 		}
5571 	}
5572 
5573 	/* Last one.  Send it upstream. */
5574 	mutex_exit(&connfp->connf_lock);
5575 	IP_STAT(ipst, ip_udp_fanmb);
5576 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5577 	CONN_DEC_REF(connp);
5578 }
5579 
5580 /*
5581  * Split an incoming packet's IPv4 options into the label and the other options.
5582  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5583  * clearing out any leftover label or options.
5584  * Otherwise it just makes ipp point into the packet.
5585  *
5586  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5587  */
5588 int
5589 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5590 {
5591 	uchar_t		*opt;
5592 	uint32_t	totallen;
5593 	uint32_t	optval;
5594 	uint32_t	optlen;
5595 
5596 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5597 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5598 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5599 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5600 
5601 	/*
5602 	 * Get length (in 4 byte octets) of IP header options.
5603 	 */
5604 	totallen = ipha->ipha_version_and_hdr_length -
5605 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5606 
5607 	if (totallen == 0) {
5608 		if (!allocate)
5609 			return (0);
5610 
5611 		/* Clear out anything from a previous packet */
5612 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5613 			kmem_free(ipp->ipp_ipv4_options,
5614 			    ipp->ipp_ipv4_options_len);
5615 			ipp->ipp_ipv4_options = NULL;
5616 			ipp->ipp_ipv4_options_len = 0;
5617 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5618 		}
5619 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5620 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5621 			ipp->ipp_label_v4 = NULL;
5622 			ipp->ipp_label_len_v4 = 0;
5623 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5624 		}
5625 		return (0);
5626 	}
5627 
5628 	totallen <<= 2;
5629 	opt = (uchar_t *)&ipha[1];
5630 	if (!is_system_labeled()) {
5631 
5632 	copyall:
5633 		if (!allocate) {
5634 			if (totallen != 0) {
5635 				ipp->ipp_ipv4_options = opt;
5636 				ipp->ipp_ipv4_options_len = totallen;
5637 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5638 			}
5639 			return (0);
5640 		}
5641 		/* Just copy all of options */
5642 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5643 			if (totallen == ipp->ipp_ipv4_options_len) {
5644 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5645 				return (0);
5646 			}
5647 			kmem_free(ipp->ipp_ipv4_options,
5648 			    ipp->ipp_ipv4_options_len);
5649 			ipp->ipp_ipv4_options = NULL;
5650 			ipp->ipp_ipv4_options_len = 0;
5651 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5652 		}
5653 		if (totallen == 0)
5654 			return (0);
5655 
5656 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5657 		if (ipp->ipp_ipv4_options == NULL)
5658 			return (ENOMEM);
5659 		ipp->ipp_ipv4_options_len = totallen;
5660 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5661 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5662 		return (0);
5663 	}
5664 
5665 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5666 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5667 		ipp->ipp_label_v4 = NULL;
5668 		ipp->ipp_label_len_v4 = 0;
5669 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5670 	}
5671 
5672 	/*
5673 	 * Search for CIPSO option.
5674 	 * We assume CIPSO is first in options if it is present.
5675 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5676 	 * prior to the CIPSO option.
5677 	 */
5678 	while (totallen != 0) {
5679 		switch (optval = opt[IPOPT_OPTVAL]) {
5680 		case IPOPT_EOL:
5681 			return (0);
5682 		case IPOPT_NOP:
5683 			optlen = 1;
5684 			break;
5685 		default:
5686 			if (totallen <= IPOPT_OLEN)
5687 				return (EINVAL);
5688 			optlen = opt[IPOPT_OLEN];
5689 			if (optlen < 2)
5690 				return (EINVAL);
5691 		}
5692 		if (optlen > totallen)
5693 			return (EINVAL);
5694 
5695 		switch (optval) {
5696 		case IPOPT_COMSEC:
5697 			if (!allocate) {
5698 				ipp->ipp_label_v4 = opt;
5699 				ipp->ipp_label_len_v4 = optlen;
5700 				ipp->ipp_fields |= IPPF_LABEL_V4;
5701 			} else {
5702 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5703 				    KM_NOSLEEP);
5704 				if (ipp->ipp_label_v4 == NULL)
5705 					return (ENOMEM);
5706 				ipp->ipp_label_len_v4 = optlen;
5707 				ipp->ipp_fields |= IPPF_LABEL_V4;
5708 				bcopy(opt, ipp->ipp_label_v4, optlen);
5709 			}
5710 			totallen -= optlen;
5711 			opt += optlen;
5712 
5713 			/* Skip padding bytes until we get to a multiple of 4 */
5714 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5715 				totallen--;
5716 				opt++;
5717 			}
5718 			/* Remaining as ipp_ipv4_options */
5719 			goto copyall;
5720 		}
5721 		totallen -= optlen;
5722 		opt += optlen;
5723 	}
5724 	/* No CIPSO found; return everything as ipp_ipv4_options */
5725 	totallen = ipha->ipha_version_and_hdr_length -
5726 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5727 	totallen <<= 2;
5728 	opt = (uchar_t *)&ipha[1];
5729 	goto copyall;
5730 }
5731 
5732 /*
5733  * Efficient versions of lookup for an IRE when we only
5734  * match the address.
5735  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5736  * Does not handle multicast addresses.
5737  */
5738 uint_t
5739 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5740 {
5741 	ire_t *ire;
5742 	uint_t result;
5743 
5744 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5745 	ASSERT(ire != NULL);
5746 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5747 		result = IRE_NOROUTE;
5748 	else
5749 		result = ire->ire_type;
5750 	ire_refrele(ire);
5751 	return (result);
5752 }
5753 
5754 /*
5755  * Efficient versions of lookup for an IRE when we only
5756  * match the address.
5757  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5758  * Does not handle multicast addresses.
5759  */
5760 uint_t
5761 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5762 {
5763 	ire_t *ire;
5764 	uint_t result;
5765 
5766 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5767 	ASSERT(ire != NULL);
5768 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5769 		result = IRE_NOROUTE;
5770 	else
5771 		result = ire->ire_type;
5772 	ire_refrele(ire);
5773 	return (result);
5774 }
5775 
5776 /*
5777  * Nobody should be sending
5778  * packets up this stream
5779  */
5780 static void
5781 ip_lrput(queue_t *q, mblk_t *mp)
5782 {
5783 	switch (mp->b_datap->db_type) {
5784 	case M_FLUSH:
5785 		/* Turn around */
5786 		if (*mp->b_rptr & FLUSHW) {
5787 			*mp->b_rptr &= ~FLUSHR;
5788 			qreply(q, mp);
5789 			return;
5790 		}
5791 		break;
5792 	}
5793 	freemsg(mp);
5794 }
5795 
5796 /* Nobody should be sending packets down this stream */
5797 /* ARGSUSED */
5798 void
5799 ip_lwput(queue_t *q, mblk_t *mp)
5800 {
5801 	freemsg(mp);
5802 }
5803 
5804 /*
5805  * Move the first hop in any source route to ipha_dst and remove that part of
5806  * the source route.  Called by other protocols.  Errors in option formatting
5807  * are ignored - will be handled by ip_output_options. Return the final
5808  * destination (either ipha_dst or the last entry in a source route.)
5809  */
5810 ipaddr_t
5811 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5812 {
5813 	ipoptp_t	opts;
5814 	uchar_t		*opt;
5815 	uint8_t		optval;
5816 	uint8_t		optlen;
5817 	ipaddr_t	dst;
5818 	int		i;
5819 	ip_stack_t	*ipst = ns->netstack_ip;
5820 
5821 	ip2dbg(("ip_massage_options\n"));
5822 	dst = ipha->ipha_dst;
5823 	for (optval = ipoptp_first(&opts, ipha);
5824 	    optval != IPOPT_EOL;
5825 	    optval = ipoptp_next(&opts)) {
5826 		opt = opts.ipoptp_cur;
5827 		switch (optval) {
5828 			uint8_t off;
5829 		case IPOPT_SSRR:
5830 		case IPOPT_LSRR:
5831 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5832 				ip1dbg(("ip_massage_options: bad src route\n"));
5833 				break;
5834 			}
5835 			optlen = opts.ipoptp_len;
5836 			off = opt[IPOPT_OFFSET];
5837 			off--;
5838 		redo_srr:
5839 			if (optlen < IP_ADDR_LEN ||
5840 			    off > optlen - IP_ADDR_LEN) {
5841 				/* End of source route */
5842 				ip1dbg(("ip_massage_options: end of SR\n"));
5843 				break;
5844 			}
5845 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5846 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5847 			    ntohl(dst)));
5848 			/*
5849 			 * Check if our address is present more than
5850 			 * once as consecutive hops in source route.
5851 			 * XXX verify per-interface ip_forwarding
5852 			 * for source route?
5853 			 */
5854 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5855 				off += IP_ADDR_LEN;
5856 				goto redo_srr;
5857 			}
5858 			if (dst == htonl(INADDR_LOOPBACK)) {
5859 				ip1dbg(("ip_massage_options: loopback addr in "
5860 				    "source route!\n"));
5861 				break;
5862 			}
5863 			/*
5864 			 * Update ipha_dst to be the first hop and remove the
5865 			 * first hop from the source route (by overwriting
5866 			 * part of the option with NOP options).
5867 			 */
5868 			ipha->ipha_dst = dst;
5869 			/* Put the last entry in dst */
5870 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5871 			    3;
5872 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5873 
5874 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5875 			    ntohl(dst)));
5876 			/* Move down and overwrite */
5877 			opt[IP_ADDR_LEN] = opt[0];
5878 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5879 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5880 			for (i = 0; i < IP_ADDR_LEN; i++)
5881 				opt[i] = IPOPT_NOP;
5882 			break;
5883 		}
5884 	}
5885 	return (dst);
5886 }
5887 
5888 /*
5889  * Return the network mask
5890  * associated with the specified address.
5891  */
5892 ipaddr_t
5893 ip_net_mask(ipaddr_t addr)
5894 {
5895 	uchar_t	*up = (uchar_t *)&addr;
5896 	ipaddr_t mask = 0;
5897 	uchar_t	*maskp = (uchar_t *)&mask;
5898 
5899 #if defined(__i386) || defined(__amd64)
5900 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5901 #endif
5902 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5903 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5904 #endif
5905 	if (CLASSD(addr)) {
5906 		maskp[0] = 0xF0;
5907 		return (mask);
5908 	}
5909 
5910 	/* We assume Class E default netmask to be 32 */
5911 	if (CLASSE(addr))
5912 		return (0xffffffffU);
5913 
5914 	if (addr == 0)
5915 		return (0);
5916 	maskp[0] = 0xFF;
5917 	if ((up[0] & 0x80) == 0)
5918 		return (mask);
5919 
5920 	maskp[1] = 0xFF;
5921 	if ((up[0] & 0xC0) == 0x80)
5922 		return (mask);
5923 
5924 	maskp[2] = 0xFF;
5925 	if ((up[0] & 0xE0) == 0xC0)
5926 		return (mask);
5927 
5928 	/* Otherwise return no mask */
5929 	return ((ipaddr_t)0);
5930 }
5931 
5932 /* Name/Value Table Lookup Routine */
5933 char *
5934 ip_nv_lookup(nv_t *nv, int value)
5935 {
5936 	if (!nv)
5937 		return (NULL);
5938 	for (; nv->nv_name; nv++) {
5939 		if (nv->nv_value == value)
5940 			return (nv->nv_name);
5941 	}
5942 	return ("unknown");
5943 }
5944 
5945 static int
5946 ip_wait_for_info_ack(ill_t *ill)
5947 {
5948 	int err;
5949 
5950 	mutex_enter(&ill->ill_lock);
5951 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5952 		/*
5953 		 * Return value of 0 indicates a pending signal.
5954 		 */
5955 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5956 		if (err == 0) {
5957 			mutex_exit(&ill->ill_lock);
5958 			return (EINTR);
5959 		}
5960 	}
5961 	mutex_exit(&ill->ill_lock);
5962 	/*
5963 	 * ip_rput_other could have set an error  in ill_error on
5964 	 * receipt of M_ERROR.
5965 	 */
5966 	return (ill->ill_error);
5967 }
5968 
5969 /*
5970  * This is a module open, i.e. this is a control stream for access
5971  * to a DLPI device.  We allocate an ill_t as the instance data in
5972  * this case.
5973  */
5974 static int
5975 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5976 {
5977 	ill_t	*ill;
5978 	int	err;
5979 	zoneid_t zoneid;
5980 	netstack_t *ns;
5981 	ip_stack_t *ipst;
5982 
5983 	/*
5984 	 * Prevent unprivileged processes from pushing IP so that
5985 	 * they can't send raw IP.
5986 	 */
5987 	if (secpolicy_net_rawaccess(credp) != 0)
5988 		return (EPERM);
5989 
5990 	ns = netstack_find_by_cred(credp);
5991 	ASSERT(ns != NULL);
5992 	ipst = ns->netstack_ip;
5993 	ASSERT(ipst != NULL);
5994 
5995 	/*
5996 	 * For exclusive stacks we set the zoneid to zero
5997 	 * to make IP operate as if in the global zone.
5998 	 */
5999 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
6000 		zoneid = GLOBAL_ZONEID;
6001 	else
6002 		zoneid = crgetzoneid(credp);
6003 
6004 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
6005 	q->q_ptr = WR(q)->q_ptr = ill;
6006 	ill->ill_ipst = ipst;
6007 	ill->ill_zoneid = zoneid;
6008 
6009 	/*
6010 	 * ill_init initializes the ill fields and then sends down
6011 	 * down a DL_INFO_REQ after calling qprocson.
6012 	 */
6013 	err = ill_init(q, ill);
6014 
6015 	if (err != 0) {
6016 		mi_free(ill);
6017 		netstack_rele(ipst->ips_netstack);
6018 		q->q_ptr = NULL;
6019 		WR(q)->q_ptr = NULL;
6020 		return (err);
6021 	}
6022 
6023 	/*
6024 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
6025 	 *
6026 	 * ill_init initializes the ipsq marking this thread as
6027 	 * writer
6028 	 */
6029 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
6030 	err = ip_wait_for_info_ack(ill);
6031 	if (err == 0)
6032 		ill->ill_credp = credp;
6033 	else
6034 		goto fail;
6035 
6036 	crhold(credp);
6037 
6038 	mutex_enter(&ipst->ips_ip_mi_lock);
6039 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
6040 	    sflag, credp);
6041 	mutex_exit(&ipst->ips_ip_mi_lock);
6042 fail:
6043 	if (err) {
6044 		(void) ip_close(q, 0);
6045 		return (err);
6046 	}
6047 	return (0);
6048 }
6049 
6050 /* For /dev/ip aka AF_INET open */
6051 int
6052 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
6053 {
6054 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
6055 }
6056 
6057 /* For /dev/ip6 aka AF_INET6 open */
6058 int
6059 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
6060 {
6061 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
6062 }
6063 
6064 /* IP open routine. */
6065 int
6066 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
6067     boolean_t isv6)
6068 {
6069 	conn_t 		*connp;
6070 	major_t		maj;
6071 	zoneid_t	zoneid;
6072 	netstack_t	*ns;
6073 	ip_stack_t	*ipst;
6074 
6075 	/* Allow reopen. */
6076 	if (q->q_ptr != NULL)
6077 		return (0);
6078 
6079 	if (sflag & MODOPEN) {
6080 		/* This is a module open */
6081 		return (ip_modopen(q, devp, flag, sflag, credp));
6082 	}
6083 
6084 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
6085 		/*
6086 		 * Non streams based socket looking for a stream
6087 		 * to access IP
6088 		 */
6089 		return (ip_helper_stream_setup(q, devp, flag, sflag,
6090 		    credp, isv6));
6091 	}
6092 
6093 	ns = netstack_find_by_cred(credp);
6094 	ASSERT(ns != NULL);
6095 	ipst = ns->netstack_ip;
6096 	ASSERT(ipst != NULL);
6097 
6098 	/*
6099 	 * For exclusive stacks we set the zoneid to zero
6100 	 * to make IP operate as if in the global zone.
6101 	 */
6102 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
6103 		zoneid = GLOBAL_ZONEID;
6104 	else
6105 		zoneid = crgetzoneid(credp);
6106 
6107 	/*
6108 	 * We are opening as a device. This is an IP client stream, and we
6109 	 * allocate an conn_t as the instance data.
6110 	 */
6111 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
6112 
6113 	/*
6114 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
6115 	 * done by netstack_find_by_cred()
6116 	 */
6117 	netstack_rele(ipst->ips_netstack);
6118 
6119 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
6120 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
6121 	connp->conn_ixa->ixa_zoneid = zoneid;
6122 	connp->conn_zoneid = zoneid;
6123 
6124 	connp->conn_rq = q;
6125 	q->q_ptr = WR(q)->q_ptr = connp;
6126 
6127 	/* Minor tells us which /dev entry was opened */
6128 	if (isv6) {
6129 		connp->conn_family = AF_INET6;
6130 		connp->conn_ipversion = IPV6_VERSION;
6131 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
6132 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
6133 	} else {
6134 		connp->conn_family = AF_INET;
6135 		connp->conn_ipversion = IPV4_VERSION;
6136 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
6137 	}
6138 
6139 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
6140 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
6141 		connp->conn_minor_arena = ip_minor_arena_la;
6142 	} else {
6143 		/*
6144 		 * Either minor numbers in the large arena were exhausted
6145 		 * or a non socket application is doing the open.
6146 		 * Try to allocate from the small arena.
6147 		 */
6148 		if ((connp->conn_dev =
6149 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
6150 			/* CONN_DEC_REF takes care of netstack_rele() */
6151 			q->q_ptr = WR(q)->q_ptr = NULL;
6152 			CONN_DEC_REF(connp);
6153 			return (EBUSY);
6154 		}
6155 		connp->conn_minor_arena = ip_minor_arena_sa;
6156 	}
6157 
6158 	maj = getemajor(*devp);
6159 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
6160 
6161 	/*
6162 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
6163 	 */
6164 	connp->conn_cred = credp;
6165 	/* Cache things in ixa without an extra refhold */
6166 	connp->conn_ixa->ixa_cred = connp->conn_cred;
6167 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6168 	if (is_system_labeled())
6169 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6170 
6171 	/*
6172 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6173 	 */
6174 	connp->conn_recv = ip_conn_input;
6175 	connp->conn_recvicmp = ip_conn_input_icmp;
6176 
6177 	crhold(connp->conn_cred);
6178 
6179 	/*
6180 	 * If the caller has the process-wide flag set, then default to MAC
6181 	 * exempt mode.  This allows read-down to unlabeled hosts.
6182 	 */
6183 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6184 		connp->conn_mac_mode = CONN_MAC_AWARE;
6185 
6186 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6187 
6188 	connp->conn_rq = q;
6189 	connp->conn_wq = WR(q);
6190 
6191 	/* Non-zero default values */
6192 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6193 
6194 	/*
6195 	 * Make the conn globally visible to walkers
6196 	 */
6197 	ASSERT(connp->conn_ref == 1);
6198 	mutex_enter(&connp->conn_lock);
6199 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6200 	mutex_exit(&connp->conn_lock);
6201 
6202 	qprocson(q);
6203 
6204 	return (0);
6205 }
6206 
6207 /*
6208  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6209  * all of them are copied to the conn_t. If the req is "zero", the policy is
6210  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6211  * fields.
6212  * We keep only the latest setting of the policy and thus policy setting
6213  * is not incremental/cumulative.
6214  *
6215  * Requests to set policies with multiple alternative actions will
6216  * go through a different API.
6217  */
6218 int
6219 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6220 {
6221 	uint_t ah_req = 0;
6222 	uint_t esp_req = 0;
6223 	uint_t se_req = 0;
6224 	ipsec_act_t *actp = NULL;
6225 	uint_t nact;
6226 	ipsec_policy_head_t *ph;
6227 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6228 	int error = 0;
6229 	netstack_t	*ns = connp->conn_netstack;
6230 	ip_stack_t	*ipst = ns->netstack_ip;
6231 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6232 
6233 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6234 
6235 	/*
6236 	 * The IP_SEC_OPT option does not allow variable length parameters,
6237 	 * hence a request cannot be NULL.
6238 	 */
6239 	if (req == NULL)
6240 		return (EINVAL);
6241 
6242 	ah_req = req->ipsr_ah_req;
6243 	esp_req = req->ipsr_esp_req;
6244 	se_req = req->ipsr_self_encap_req;
6245 
6246 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6247 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6248 		return (EINVAL);
6249 
6250 	/*
6251 	 * Are we dealing with a request to reset the policy (i.e.
6252 	 * zero requests).
6253 	 */
6254 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6255 	    (esp_req & REQ_MASK) == 0 &&
6256 	    (se_req & REQ_MASK) == 0);
6257 
6258 	if (!is_pol_reset) {
6259 		/*
6260 		 * If we couldn't load IPsec, fail with "protocol
6261 		 * not supported".
6262 		 * IPsec may not have been loaded for a request with zero
6263 		 * policies, so we don't fail in this case.
6264 		 */
6265 		mutex_enter(&ipss->ipsec_loader_lock);
6266 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6267 			mutex_exit(&ipss->ipsec_loader_lock);
6268 			return (EPROTONOSUPPORT);
6269 		}
6270 		mutex_exit(&ipss->ipsec_loader_lock);
6271 
6272 		/*
6273 		 * Test for valid requests. Invalid algorithms
6274 		 * need to be tested by IPsec code because new
6275 		 * algorithms can be added dynamically.
6276 		 */
6277 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6278 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6279 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6280 			return (EINVAL);
6281 		}
6282 
6283 		/*
6284 		 * Only privileged users can issue these
6285 		 * requests.
6286 		 */
6287 		if (((ah_req & IPSEC_PREF_NEVER) ||
6288 		    (esp_req & IPSEC_PREF_NEVER) ||
6289 		    (se_req & IPSEC_PREF_NEVER)) &&
6290 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6291 			return (EPERM);
6292 		}
6293 
6294 		/*
6295 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6296 		 * are mutually exclusive.
6297 		 */
6298 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6299 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6300 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6301 			/* Both of them are set */
6302 			return (EINVAL);
6303 		}
6304 	}
6305 
6306 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6307 
6308 	/*
6309 	 * If we have already cached policies in conn_connect(), don't
6310 	 * let them change now. We cache policies for connections
6311 	 * whose src,dst [addr, port] is known.
6312 	 */
6313 	if (connp->conn_policy_cached) {
6314 		return (EINVAL);
6315 	}
6316 
6317 	/*
6318 	 * We have a zero policies, reset the connection policy if already
6319 	 * set. This will cause the connection to inherit the
6320 	 * global policy, if any.
6321 	 */
6322 	if (is_pol_reset) {
6323 		if (connp->conn_policy != NULL) {
6324 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6325 			connp->conn_policy = NULL;
6326 		}
6327 		connp->conn_in_enforce_policy = B_FALSE;
6328 		connp->conn_out_enforce_policy = B_FALSE;
6329 		return (0);
6330 	}
6331 
6332 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6333 	    ipst->ips_netstack);
6334 	if (ph == NULL)
6335 		goto enomem;
6336 
6337 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6338 	if (actp == NULL)
6339 		goto enomem;
6340 
6341 	/*
6342 	 * Always insert IPv4 policy entries, since they can also apply to
6343 	 * ipv6 sockets being used in ipv4-compat mode.
6344 	 */
6345 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6346 	    IPSEC_TYPE_INBOUND, ns))
6347 		goto enomem;
6348 	is_pol_inserted = B_TRUE;
6349 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6350 	    IPSEC_TYPE_OUTBOUND, ns))
6351 		goto enomem;
6352 
6353 	/*
6354 	 * We're looking at a v6 socket, also insert the v6-specific
6355 	 * entries.
6356 	 */
6357 	if (connp->conn_family == AF_INET6) {
6358 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6359 		    IPSEC_TYPE_INBOUND, ns))
6360 			goto enomem;
6361 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6362 		    IPSEC_TYPE_OUTBOUND, ns))
6363 			goto enomem;
6364 	}
6365 
6366 	ipsec_actvec_free(actp, nact);
6367 
6368 	/*
6369 	 * If the requests need security, set enforce_policy.
6370 	 * If the requests are IPSEC_PREF_NEVER, one should
6371 	 * still set conn_out_enforce_policy so that ip_set_destination
6372 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6373 	 * for connections that we don't cache policy in at connect time,
6374 	 * if global policy matches in ip_output_attach_policy, we
6375 	 * don't wrongly inherit global policy. Similarly, we need
6376 	 * to set conn_in_enforce_policy also so that we don't verify
6377 	 * policy wrongly.
6378 	 */
6379 	if ((ah_req & REQ_MASK) != 0 ||
6380 	    (esp_req & REQ_MASK) != 0 ||
6381 	    (se_req & REQ_MASK) != 0) {
6382 		connp->conn_in_enforce_policy = B_TRUE;
6383 		connp->conn_out_enforce_policy = B_TRUE;
6384 	}
6385 
6386 	return (error);
6387 #undef REQ_MASK
6388 
6389 	/*
6390 	 * Common memory-allocation-failure exit path.
6391 	 */
6392 enomem:
6393 	if (actp != NULL)
6394 		ipsec_actvec_free(actp, nact);
6395 	if (is_pol_inserted)
6396 		ipsec_polhead_flush(ph, ns);
6397 	return (ENOMEM);
6398 }
6399 
6400 /*
6401  * Set socket options for joining and leaving multicast groups.
6402  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6403  * The caller has already check that the option name is consistent with
6404  * the address family of the socket.
6405  */
6406 int
6407 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6408     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6409 {
6410 	int		*i1 = (int *)invalp;
6411 	int		error = 0;
6412 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6413 	struct ip_mreq	*v4_mreqp;
6414 	struct ipv6_mreq *v6_mreqp;
6415 	struct group_req *greqp;
6416 	ire_t *ire;
6417 	boolean_t done = B_FALSE;
6418 	ipaddr_t ifaddr;
6419 	in6_addr_t v6group;
6420 	uint_t ifindex;
6421 	boolean_t mcast_opt = B_TRUE;
6422 	mcast_record_t fmode;
6423 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6424 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6425 
6426 	switch (name) {
6427 	case IP_ADD_MEMBERSHIP:
6428 	case IPV6_JOIN_GROUP:
6429 		mcast_opt = B_FALSE;
6430 		/* FALLTHRU */
6431 	case MCAST_JOIN_GROUP:
6432 		fmode = MODE_IS_EXCLUDE;
6433 		optfn = ip_opt_add_group;
6434 		break;
6435 
6436 	case IP_DROP_MEMBERSHIP:
6437 	case IPV6_LEAVE_GROUP:
6438 		mcast_opt = B_FALSE;
6439 		/* FALLTHRU */
6440 	case MCAST_LEAVE_GROUP:
6441 		fmode = MODE_IS_INCLUDE;
6442 		optfn = ip_opt_delete_group;
6443 		break;
6444 	default:
6445 		ASSERT(0);
6446 	}
6447 
6448 	if (mcast_opt) {
6449 		struct sockaddr_in *sin;
6450 		struct sockaddr_in6 *sin6;
6451 
6452 		greqp = (struct group_req *)i1;
6453 		if (greqp->gr_group.ss_family == AF_INET) {
6454 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6455 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6456 		} else {
6457 			if (!inet6)
6458 				return (EINVAL);	/* Not on INET socket */
6459 
6460 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6461 			v6group = sin6->sin6_addr;
6462 		}
6463 		ifaddr = INADDR_ANY;
6464 		ifindex = greqp->gr_interface;
6465 	} else if (inet6) {
6466 		v6_mreqp = (struct ipv6_mreq *)i1;
6467 		v6group = v6_mreqp->ipv6mr_multiaddr;
6468 		ifaddr = INADDR_ANY;
6469 		ifindex = v6_mreqp->ipv6mr_interface;
6470 	} else {
6471 		v4_mreqp = (struct ip_mreq *)i1;
6472 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6473 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6474 		ifindex = 0;
6475 	}
6476 
6477 	/*
6478 	 * In the multirouting case, we need to replicate
6479 	 * the request on all interfaces that will take part
6480 	 * in replication.  We do so because multirouting is
6481 	 * reflective, thus we will probably receive multi-
6482 	 * casts on those interfaces.
6483 	 * The ip_multirt_apply_membership() succeeds if
6484 	 * the operation succeeds on at least one interface.
6485 	 */
6486 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6487 		ipaddr_t group;
6488 
6489 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6490 
6491 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6492 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6493 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6494 	} else {
6495 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6496 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6497 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6498 	}
6499 	if (ire != NULL) {
6500 		if (ire->ire_flags & RTF_MULTIRT) {
6501 			error = ip_multirt_apply_membership(optfn, ire, connp,
6502 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6503 			done = B_TRUE;
6504 		}
6505 		ire_refrele(ire);
6506 	}
6507 
6508 	if (!done) {
6509 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6510 		    fmode, &ipv6_all_zeros);
6511 	}
6512 	return (error);
6513 }
6514 
6515 /*
6516  * Set socket options for joining and leaving multicast groups
6517  * for specific sources.
6518  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6519  * The caller has already check that the option name is consistent with
6520  * the address family of the socket.
6521  */
6522 int
6523 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6524     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6525 {
6526 	int		*i1 = (int *)invalp;
6527 	int		error = 0;
6528 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6529 	struct ip_mreq_source *imreqp;
6530 	struct group_source_req *gsreqp;
6531 	in6_addr_t v6group, v6src;
6532 	uint32_t ifindex;
6533 	ipaddr_t ifaddr;
6534 	boolean_t mcast_opt = B_TRUE;
6535 	mcast_record_t fmode;
6536 	ire_t *ire;
6537 	boolean_t done = B_FALSE;
6538 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6539 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6540 
6541 	switch (name) {
6542 	case IP_BLOCK_SOURCE:
6543 		mcast_opt = B_FALSE;
6544 		/* FALLTHRU */
6545 	case MCAST_BLOCK_SOURCE:
6546 		fmode = MODE_IS_EXCLUDE;
6547 		optfn = ip_opt_add_group;
6548 		break;
6549 
6550 	case IP_UNBLOCK_SOURCE:
6551 		mcast_opt = B_FALSE;
6552 		/* FALLTHRU */
6553 	case MCAST_UNBLOCK_SOURCE:
6554 		fmode = MODE_IS_EXCLUDE;
6555 		optfn = ip_opt_delete_group;
6556 		break;
6557 
6558 	case IP_ADD_SOURCE_MEMBERSHIP:
6559 		mcast_opt = B_FALSE;
6560 		/* FALLTHRU */
6561 	case MCAST_JOIN_SOURCE_GROUP:
6562 		fmode = MODE_IS_INCLUDE;
6563 		optfn = ip_opt_add_group;
6564 		break;
6565 
6566 	case IP_DROP_SOURCE_MEMBERSHIP:
6567 		mcast_opt = B_FALSE;
6568 		/* FALLTHRU */
6569 	case MCAST_LEAVE_SOURCE_GROUP:
6570 		fmode = MODE_IS_INCLUDE;
6571 		optfn = ip_opt_delete_group;
6572 		break;
6573 	default:
6574 		ASSERT(0);
6575 	}
6576 
6577 	if (mcast_opt) {
6578 		gsreqp = (struct group_source_req *)i1;
6579 		ifindex = gsreqp->gsr_interface;
6580 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6581 			struct sockaddr_in *s;
6582 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6583 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6584 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6585 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6586 		} else {
6587 			struct sockaddr_in6 *s6;
6588 
6589 			if (!inet6)
6590 				return (EINVAL);	/* Not on INET socket */
6591 
6592 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6593 			v6group = s6->sin6_addr;
6594 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6595 			v6src = s6->sin6_addr;
6596 		}
6597 		ifaddr = INADDR_ANY;
6598 	} else {
6599 		imreqp = (struct ip_mreq_source *)i1;
6600 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6601 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6602 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6603 		ifindex = 0;
6604 	}
6605 
6606 	/*
6607 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6608 	 */
6609 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6610 		v6src = ipv6_all_zeros;
6611 
6612 	/*
6613 	 * In the multirouting case, we need to replicate
6614 	 * the request as noted in the mcast cases above.
6615 	 */
6616 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6617 		ipaddr_t group;
6618 
6619 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6620 
6621 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6622 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6623 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6624 	} else {
6625 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6626 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6627 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6628 	}
6629 	if (ire != NULL) {
6630 		if (ire->ire_flags & RTF_MULTIRT) {
6631 			error = ip_multirt_apply_membership(optfn, ire, connp,
6632 			    checkonly, &v6group, fmode, &v6src);
6633 			done = B_TRUE;
6634 		}
6635 		ire_refrele(ire);
6636 	}
6637 	if (!done) {
6638 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6639 		    fmode, &v6src);
6640 	}
6641 	return (error);
6642 }
6643 
6644 /*
6645  * Given a destination address and a pointer to where to put the information
6646  * this routine fills in the mtuinfo.
6647  * The socket must be connected.
6648  * For sctp conn_faddr is the primary address.
6649  */
6650 int
6651 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6652 {
6653 	uint32_t	pmtu = IP_MAXPACKET;
6654 	uint_t		scopeid;
6655 
6656 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6657 		return (-1);
6658 
6659 	/* In case we never sent or called ip_set_destination_v4/v6 */
6660 	if (ixa->ixa_ire != NULL)
6661 		pmtu = ip_get_pmtu(ixa);
6662 
6663 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6664 		scopeid = ixa->ixa_scopeid;
6665 	else
6666 		scopeid = 0;
6667 
6668 	bzero(mtuinfo, sizeof (*mtuinfo));
6669 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6670 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6671 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6672 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6673 	mtuinfo->ip6m_mtu = pmtu;
6674 
6675 	return (sizeof (struct ip6_mtuinfo));
6676 }
6677 
6678 /* Named Dispatch routine to get a current value out of our parameter table. */
6679 /* ARGSUSED */
6680 static int
6681 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
6682 {
6683 	ipparam_t *ippa = (ipparam_t *)cp;
6684 
6685 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
6686 	return (0);
6687 }
6688 
6689 /* ARGSUSED */
6690 static int
6691 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
6692 {
6693 
6694 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
6695 	return (0);
6696 }
6697 
6698 /*
6699  * Set ip{,6}_forwarding values.  This means walking through all of the
6700  * ill's and toggling their forwarding values.
6701  */
6702 /* ARGSUSED */
6703 static int
6704 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
6705 {
6706 	long new_value;
6707 	int *forwarding_value = (int *)cp;
6708 	ill_t *ill;
6709 	boolean_t isv6;
6710 	ill_walk_context_t ctx;
6711 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
6712 
6713 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
6714 
6715 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6716 	    new_value < 0 || new_value > 1) {
6717 		return (EINVAL);
6718 	}
6719 
6720 	*forwarding_value = new_value;
6721 
6722 	/*
6723 	 * Regardless of the current value of ip_forwarding, set all per-ill
6724 	 * values of ip_forwarding to the value being set.
6725 	 *
6726 	 * Bring all the ill's up to date with the new global value.
6727 	 */
6728 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
6729 
6730 	if (isv6)
6731 		ill = ILL_START_WALK_V6(&ctx, ipst);
6732 	else
6733 		ill = ILL_START_WALK_V4(&ctx, ipst);
6734 
6735 	for (; ill != NULL; ill = ill_next(&ctx, ill))
6736 		(void) ill_forward_set(ill, new_value != 0);
6737 
6738 	rw_exit(&ipst->ips_ill_g_lock);
6739 	return (0);
6740 }
6741 
6742 /*
6743  * Walk through the param array specified registering each element with the
6744  * Named Dispatch handler. This is called only during init. So it is ok
6745  * not to acquire any locks
6746  */
6747 static boolean_t
6748 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
6749     ipndp_t *ipnd, size_t ipnd_cnt)
6750 {
6751 	for (; ippa_cnt-- > 0; ippa++) {
6752 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
6753 			if (!nd_load(ndp, ippa->ip_param_name,
6754 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
6755 				nd_free(ndp);
6756 				return (B_FALSE);
6757 			}
6758 		}
6759 	}
6760 
6761 	for (; ipnd_cnt-- > 0; ipnd++) {
6762 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
6763 			if (!nd_load(ndp, ipnd->ip_ndp_name,
6764 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
6765 			    ipnd->ip_ndp_data)) {
6766 				nd_free(ndp);
6767 				return (B_FALSE);
6768 			}
6769 		}
6770 	}
6771 
6772 	return (B_TRUE);
6773 }
6774 
6775 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
6776 /* ARGSUSED */
6777 static int
6778 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
6779 {
6780 	long		new_value;
6781 	ipparam_t	*ippa = (ipparam_t *)cp;
6782 
6783 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6784 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
6785 		return (EINVAL);
6786 	}
6787 	ippa->ip_param_value = new_value;
6788 	return (0);
6789 }
6790 
6791 /*
6792  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6793  * When an ipf is passed here for the first time, if
6794  * we already have in-order fragments on the queue, we convert from the fast-
6795  * path reassembly scheme to the hard-case scheme.  From then on, additional
6796  * fragments are reassembled here.  We keep track of the start and end offsets
6797  * of each piece, and the number of holes in the chain.  When the hole count
6798  * goes to zero, we are done!
6799  *
6800  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6801  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6802  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6803  * after the call to ip_reassemble().
6804  */
6805 int
6806 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6807     size_t msg_len)
6808 {
6809 	uint_t	end;
6810 	mblk_t	*next_mp;
6811 	mblk_t	*mp1;
6812 	uint_t	offset;
6813 	boolean_t incr_dups = B_TRUE;
6814 	boolean_t offset_zero_seen = B_FALSE;
6815 	boolean_t pkt_boundary_checked = B_FALSE;
6816 
6817 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6818 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6819 
6820 	/* Add in byte count */
6821 	ipf->ipf_count += msg_len;
6822 	if (ipf->ipf_end) {
6823 		/*
6824 		 * We were part way through in-order reassembly, but now there
6825 		 * is a hole.  We walk through messages already queued, and
6826 		 * mark them for hard case reassembly.  We know that up till
6827 		 * now they were in order starting from offset zero.
6828 		 */
6829 		offset = 0;
6830 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6831 			IP_REASS_SET_START(mp1, offset);
6832 			if (offset == 0) {
6833 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6834 				offset = -ipf->ipf_nf_hdr_len;
6835 			}
6836 			offset += mp1->b_wptr - mp1->b_rptr;
6837 			IP_REASS_SET_END(mp1, offset);
6838 		}
6839 		/* One hole at the end. */
6840 		ipf->ipf_hole_cnt = 1;
6841 		/* Brand it as a hard case, forever. */
6842 		ipf->ipf_end = 0;
6843 	}
6844 	/* Walk through all the new pieces. */
6845 	do {
6846 		end = start + (mp->b_wptr - mp->b_rptr);
6847 		/*
6848 		 * If start is 0, decrease 'end' only for the first mblk of
6849 		 * the fragment. Otherwise 'end' can get wrong value in the
6850 		 * second pass of the loop if first mblk is exactly the
6851 		 * size of ipf_nf_hdr_len.
6852 		 */
6853 		if (start == 0 && !offset_zero_seen) {
6854 			/* First segment */
6855 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6856 			end -= ipf->ipf_nf_hdr_len;
6857 			offset_zero_seen = B_TRUE;
6858 		}
6859 		next_mp = mp->b_cont;
6860 		/*
6861 		 * We are checking to see if there is any interesing data
6862 		 * to process.  If there isn't and the mblk isn't the
6863 		 * one which carries the unfragmentable header then we
6864 		 * drop it.  It's possible to have just the unfragmentable
6865 		 * header come through without any data.  That needs to be
6866 		 * saved.
6867 		 *
6868 		 * If the assert at the top of this function holds then the
6869 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6870 		 * is infrequently traveled enough that the test is left in
6871 		 * to protect against future code changes which break that
6872 		 * invariant.
6873 		 */
6874 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6875 			/* Empty.  Blast it. */
6876 			IP_REASS_SET_START(mp, 0);
6877 			IP_REASS_SET_END(mp, 0);
6878 			/*
6879 			 * If the ipf points to the mblk we are about to free,
6880 			 * update ipf to point to the next mblk (or NULL
6881 			 * if none).
6882 			 */
6883 			if (ipf->ipf_mp->b_cont == mp)
6884 				ipf->ipf_mp->b_cont = next_mp;
6885 			freeb(mp);
6886 			continue;
6887 		}
6888 		mp->b_cont = NULL;
6889 		IP_REASS_SET_START(mp, start);
6890 		IP_REASS_SET_END(mp, end);
6891 		if (!ipf->ipf_tail_mp) {
6892 			ipf->ipf_tail_mp = mp;
6893 			ipf->ipf_mp->b_cont = mp;
6894 			if (start == 0 || !more) {
6895 				ipf->ipf_hole_cnt = 1;
6896 				/*
6897 				 * if the first fragment comes in more than one
6898 				 * mblk, this loop will be executed for each
6899 				 * mblk. Need to adjust hole count so exiting
6900 				 * this routine will leave hole count at 1.
6901 				 */
6902 				if (next_mp)
6903 					ipf->ipf_hole_cnt++;
6904 			} else
6905 				ipf->ipf_hole_cnt = 2;
6906 			continue;
6907 		} else if (ipf->ipf_last_frag_seen && !more &&
6908 		    !pkt_boundary_checked) {
6909 			/*
6910 			 * We check datagram boundary only if this fragment
6911 			 * claims to be the last fragment and we have seen a
6912 			 * last fragment in the past too. We do this only
6913 			 * once for a given fragment.
6914 			 *
6915 			 * start cannot be 0 here as fragments with start=0
6916 			 * and MF=0 gets handled as a complete packet. These
6917 			 * fragments should not reach here.
6918 			 */
6919 
6920 			if (start + msgdsize(mp) !=
6921 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6922 				/*
6923 				 * We have two fragments both of which claim
6924 				 * to be the last fragment but gives conflicting
6925 				 * information about the whole datagram size.
6926 				 * Something fishy is going on. Drop the
6927 				 * fragment and free up the reassembly list.
6928 				 */
6929 				return (IP_REASS_FAILED);
6930 			}
6931 
6932 			/*
6933 			 * We shouldn't come to this code block again for this
6934 			 * particular fragment.
6935 			 */
6936 			pkt_boundary_checked = B_TRUE;
6937 		}
6938 
6939 		/* New stuff at or beyond tail? */
6940 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6941 		if (start >= offset) {
6942 			if (ipf->ipf_last_frag_seen) {
6943 				/* current fragment is beyond last fragment */
6944 				return (IP_REASS_FAILED);
6945 			}
6946 			/* Link it on end. */
6947 			ipf->ipf_tail_mp->b_cont = mp;
6948 			ipf->ipf_tail_mp = mp;
6949 			if (more) {
6950 				if (start != offset)
6951 					ipf->ipf_hole_cnt++;
6952 			} else if (start == offset && next_mp == NULL)
6953 					ipf->ipf_hole_cnt--;
6954 			continue;
6955 		}
6956 		mp1 = ipf->ipf_mp->b_cont;
6957 		offset = IP_REASS_START(mp1);
6958 		/* New stuff at the front? */
6959 		if (start < offset) {
6960 			if (start == 0) {
6961 				if (end >= offset) {
6962 					/* Nailed the hole at the begining. */
6963 					ipf->ipf_hole_cnt--;
6964 				}
6965 			} else if (end < offset) {
6966 				/*
6967 				 * A hole, stuff, and a hole where there used
6968 				 * to be just a hole.
6969 				 */
6970 				ipf->ipf_hole_cnt++;
6971 			}
6972 			mp->b_cont = mp1;
6973 			/* Check for overlap. */
6974 			while (end > offset) {
6975 				if (end < IP_REASS_END(mp1)) {
6976 					mp->b_wptr -= end - offset;
6977 					IP_REASS_SET_END(mp, offset);
6978 					BUMP_MIB(ill->ill_ip_mib,
6979 					    ipIfStatsReasmPartDups);
6980 					break;
6981 				}
6982 				/* Did we cover another hole? */
6983 				if ((mp1->b_cont &&
6984 				    IP_REASS_END(mp1) !=
6985 				    IP_REASS_START(mp1->b_cont) &&
6986 				    end >= IP_REASS_START(mp1->b_cont)) ||
6987 				    (!ipf->ipf_last_frag_seen && !more)) {
6988 					ipf->ipf_hole_cnt--;
6989 				}
6990 				/* Clip out mp1. */
6991 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6992 					/*
6993 					 * After clipping out mp1, this guy
6994 					 * is now hanging off the end.
6995 					 */
6996 					ipf->ipf_tail_mp = mp;
6997 				}
6998 				IP_REASS_SET_START(mp1, 0);
6999 				IP_REASS_SET_END(mp1, 0);
7000 				/* Subtract byte count */
7001 				ipf->ipf_count -= mp1->b_datap->db_lim -
7002 				    mp1->b_datap->db_base;
7003 				freeb(mp1);
7004 				BUMP_MIB(ill->ill_ip_mib,
7005 				    ipIfStatsReasmPartDups);
7006 				mp1 = mp->b_cont;
7007 				if (!mp1)
7008 					break;
7009 				offset = IP_REASS_START(mp1);
7010 			}
7011 			ipf->ipf_mp->b_cont = mp;
7012 			continue;
7013 		}
7014 		/*
7015 		 * The new piece starts somewhere between the start of the head
7016 		 * and before the end of the tail.
7017 		 */
7018 		for (; mp1; mp1 = mp1->b_cont) {
7019 			offset = IP_REASS_END(mp1);
7020 			if (start < offset) {
7021 				if (end <= offset) {
7022 					/* Nothing new. */
7023 					IP_REASS_SET_START(mp, 0);
7024 					IP_REASS_SET_END(mp, 0);
7025 					/* Subtract byte count */
7026 					ipf->ipf_count -= mp->b_datap->db_lim -
7027 					    mp->b_datap->db_base;
7028 					if (incr_dups) {
7029 						ipf->ipf_num_dups++;
7030 						incr_dups = B_FALSE;
7031 					}
7032 					freeb(mp);
7033 					BUMP_MIB(ill->ill_ip_mib,
7034 					    ipIfStatsReasmDuplicates);
7035 					break;
7036 				}
7037 				/*
7038 				 * Trim redundant stuff off beginning of new
7039 				 * piece.
7040 				 */
7041 				IP_REASS_SET_START(mp, offset);
7042 				mp->b_rptr += offset - start;
7043 				BUMP_MIB(ill->ill_ip_mib,
7044 				    ipIfStatsReasmPartDups);
7045 				start = offset;
7046 				if (!mp1->b_cont) {
7047 					/*
7048 					 * After trimming, this guy is now
7049 					 * hanging off the end.
7050 					 */
7051 					mp1->b_cont = mp;
7052 					ipf->ipf_tail_mp = mp;
7053 					if (!more) {
7054 						ipf->ipf_hole_cnt--;
7055 					}
7056 					break;
7057 				}
7058 			}
7059 			if (start >= IP_REASS_START(mp1->b_cont))
7060 				continue;
7061 			/* Fill a hole */
7062 			if (start > offset)
7063 				ipf->ipf_hole_cnt++;
7064 			mp->b_cont = mp1->b_cont;
7065 			mp1->b_cont = mp;
7066 			mp1 = mp->b_cont;
7067 			offset = IP_REASS_START(mp1);
7068 			if (end >= offset) {
7069 				ipf->ipf_hole_cnt--;
7070 				/* Check for overlap. */
7071 				while (end > offset) {
7072 					if (end < IP_REASS_END(mp1)) {
7073 						mp->b_wptr -= end - offset;
7074 						IP_REASS_SET_END(mp, offset);
7075 						/*
7076 						 * TODO we might bump
7077 						 * this up twice if there is
7078 						 * overlap at both ends.
7079 						 */
7080 						BUMP_MIB(ill->ill_ip_mib,
7081 						    ipIfStatsReasmPartDups);
7082 						break;
7083 					}
7084 					/* Did we cover another hole? */
7085 					if ((mp1->b_cont &&
7086 					    IP_REASS_END(mp1)
7087 					    != IP_REASS_START(mp1->b_cont) &&
7088 					    end >=
7089 					    IP_REASS_START(mp1->b_cont)) ||
7090 					    (!ipf->ipf_last_frag_seen &&
7091 					    !more)) {
7092 						ipf->ipf_hole_cnt--;
7093 					}
7094 					/* Clip out mp1. */
7095 					if ((mp->b_cont = mp1->b_cont) ==
7096 					    NULL) {
7097 						/*
7098 						 * After clipping out mp1,
7099 						 * this guy is now hanging
7100 						 * off the end.
7101 						 */
7102 						ipf->ipf_tail_mp = mp;
7103 					}
7104 					IP_REASS_SET_START(mp1, 0);
7105 					IP_REASS_SET_END(mp1, 0);
7106 					/* Subtract byte count */
7107 					ipf->ipf_count -=
7108 					    mp1->b_datap->db_lim -
7109 					    mp1->b_datap->db_base;
7110 					freeb(mp1);
7111 					BUMP_MIB(ill->ill_ip_mib,
7112 					    ipIfStatsReasmPartDups);
7113 					mp1 = mp->b_cont;
7114 					if (!mp1)
7115 						break;
7116 					offset = IP_REASS_START(mp1);
7117 				}
7118 			}
7119 			break;
7120 		}
7121 	} while (start = end, mp = next_mp);
7122 
7123 	/* Fragment just processed could be the last one. Remember this fact */
7124 	if (!more)
7125 		ipf->ipf_last_frag_seen = B_TRUE;
7126 
7127 	/* Still got holes? */
7128 	if (ipf->ipf_hole_cnt)
7129 		return (IP_REASS_PARTIAL);
7130 	/* Clean up overloaded fields to avoid upstream disasters. */
7131 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
7132 		IP_REASS_SET_START(mp1, 0);
7133 		IP_REASS_SET_END(mp1, 0);
7134 	}
7135 	return (IP_REASS_COMPLETE);
7136 }
7137 
7138 /*
7139  * Fragmentation reassembly.  Each ILL has a hash table for
7140  * queuing packets undergoing reassembly for all IPIFs
7141  * associated with the ILL.  The hash is based on the packet
7142  * IP ident field.  The ILL frag hash table was allocated
7143  * as a timer block at the time the ILL was created.  Whenever
7144  * there is anything on the reassembly queue, the timer will
7145  * be running.  Returns the reassembled packet if reassembly completes.
7146  */
7147 mblk_t *
7148 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
7149 {
7150 	uint32_t	frag_offset_flags;
7151 	mblk_t		*t_mp;
7152 	ipaddr_t	dst;
7153 	uint8_t		proto = ipha->ipha_protocol;
7154 	uint32_t	sum_val;
7155 	uint16_t	sum_flags;
7156 	ipf_t		*ipf;
7157 	ipf_t		**ipfp;
7158 	ipfb_t		*ipfb;
7159 	uint16_t	ident;
7160 	uint32_t	offset;
7161 	ipaddr_t	src;
7162 	uint_t		hdr_length;
7163 	uint32_t	end;
7164 	mblk_t		*mp1;
7165 	mblk_t		*tail_mp;
7166 	size_t		count;
7167 	size_t		msg_len;
7168 	uint8_t		ecn_info = 0;
7169 	uint32_t	packet_size;
7170 	boolean_t	pruned = B_FALSE;
7171 	ill_t		*ill = ira->ira_ill;
7172 	ip_stack_t	*ipst = ill->ill_ipst;
7173 
7174 	/*
7175 	 * Drop the fragmented as early as possible, if
7176 	 * we don't have resource(s) to re-assemble.
7177 	 */
7178 	if (ipst->ips_ip_reass_queue_bytes == 0) {
7179 		freemsg(mp);
7180 		return (NULL);
7181 	}
7182 
7183 	/* Check for fragmentation offset; return if there's none */
7184 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7185 	    (IPH_MF | IPH_OFFSET)) == 0)
7186 		return (mp);
7187 
7188 	/*
7189 	 * We utilize hardware computed checksum info only for UDP since
7190 	 * IP fragmentation is a normal occurrence for the protocol.  In
7191 	 * addition, checksum offload support for IP fragments carrying
7192 	 * UDP payload is commonly implemented across network adapters.
7193 	 */
7194 	ASSERT(ira->ira_rill != NULL);
7195 	if (proto == IPPROTO_UDP && dohwcksum &&
7196 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7197 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7198 		mblk_t *mp1 = mp->b_cont;
7199 		int32_t len;
7200 
7201 		/* Record checksum information from the packet */
7202 		sum_val = (uint32_t)DB_CKSUM16(mp);
7203 		sum_flags = DB_CKSUMFLAGS(mp);
7204 
7205 		/* IP payload offset from beginning of mblk */
7206 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7207 
7208 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7209 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7210 		    offset >= DB_CKSUMSTART(mp) &&
7211 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7212 			uint32_t adj;
7213 			/*
7214 			 * Partial checksum has been calculated by hardware
7215 			 * and attached to the packet; in addition, any
7216 			 * prepended extraneous data is even byte aligned.
7217 			 * If any such data exists, we adjust the checksum;
7218 			 * this would also handle any postpended data.
7219 			 */
7220 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7221 			    mp, mp1, len, adj);
7222 
7223 			/* One's complement subtract extraneous checksum */
7224 			if (adj >= sum_val)
7225 				sum_val = ~(adj - sum_val) & 0xFFFF;
7226 			else
7227 				sum_val -= adj;
7228 		}
7229 	} else {
7230 		sum_val = 0;
7231 		sum_flags = 0;
7232 	}
7233 
7234 	/* Clear hardware checksumming flag */
7235 	DB_CKSUMFLAGS(mp) = 0;
7236 
7237 	ident = ipha->ipha_ident;
7238 	offset = (frag_offset_flags << 3) & 0xFFFF;
7239 	src = ipha->ipha_src;
7240 	dst = ipha->ipha_dst;
7241 	hdr_length = IPH_HDR_LENGTH(ipha);
7242 	end = ntohs(ipha->ipha_length) - hdr_length;
7243 
7244 	/* If end == 0 then we have a packet with no data, so just free it */
7245 	if (end == 0) {
7246 		freemsg(mp);
7247 		return (NULL);
7248 	}
7249 
7250 	/* Record the ECN field info. */
7251 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7252 	if (offset != 0) {
7253 		/*
7254 		 * If this isn't the first piece, strip the header, and
7255 		 * add the offset to the end value.
7256 		 */
7257 		mp->b_rptr += hdr_length;
7258 		end += offset;
7259 	}
7260 
7261 	/* Handle vnic loopback of fragments */
7262 	if (mp->b_datap->db_ref > 2)
7263 		msg_len = 0;
7264 	else
7265 		msg_len = MBLKSIZE(mp);
7266 
7267 	tail_mp = mp;
7268 	while (tail_mp->b_cont != NULL) {
7269 		tail_mp = tail_mp->b_cont;
7270 		if (tail_mp->b_datap->db_ref <= 2)
7271 			msg_len += MBLKSIZE(tail_mp);
7272 	}
7273 
7274 	/* If the reassembly list for this ILL will get too big, prune it */
7275 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7276 	    ipst->ips_ip_reass_queue_bytes) {
7277 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7278 		    uint_t, ill->ill_frag_count,
7279 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7280 		ill_frag_prune(ill,
7281 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7282 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7283 		pruned = B_TRUE;
7284 	}
7285 
7286 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7287 	mutex_enter(&ipfb->ipfb_lock);
7288 
7289 	ipfp = &ipfb->ipfb_ipf;
7290 	/* Try to find an existing fragment queue for this packet. */
7291 	for (;;) {
7292 		ipf = ipfp[0];
7293 		if (ipf != NULL) {
7294 			/*
7295 			 * It has to match on ident and src/dst address.
7296 			 */
7297 			if (ipf->ipf_ident == ident &&
7298 			    ipf->ipf_src == src &&
7299 			    ipf->ipf_dst == dst &&
7300 			    ipf->ipf_protocol == proto) {
7301 				/*
7302 				 * If we have received too many
7303 				 * duplicate fragments for this packet
7304 				 * free it.
7305 				 */
7306 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7307 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7308 					freemsg(mp);
7309 					mutex_exit(&ipfb->ipfb_lock);
7310 					return (NULL);
7311 				}
7312 				/* Found it. */
7313 				break;
7314 			}
7315 			ipfp = &ipf->ipf_hash_next;
7316 			continue;
7317 		}
7318 
7319 		/*
7320 		 * If we pruned the list, do we want to store this new
7321 		 * fragment?. We apply an optimization here based on the
7322 		 * fact that most fragments will be received in order.
7323 		 * So if the offset of this incoming fragment is zero,
7324 		 * it is the first fragment of a new packet. We will
7325 		 * keep it.  Otherwise drop the fragment, as we have
7326 		 * probably pruned the packet already (since the
7327 		 * packet cannot be found).
7328 		 */
7329 		if (pruned && offset != 0) {
7330 			mutex_exit(&ipfb->ipfb_lock);
7331 			freemsg(mp);
7332 			return (NULL);
7333 		}
7334 
7335 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7336 			/*
7337 			 * Too many fragmented packets in this hash
7338 			 * bucket. Free the oldest.
7339 			 */
7340 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7341 		}
7342 
7343 		/* New guy.  Allocate a frag message. */
7344 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7345 		if (mp1 == NULL) {
7346 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7347 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7348 			freemsg(mp);
7349 reass_done:
7350 			mutex_exit(&ipfb->ipfb_lock);
7351 			return (NULL);
7352 		}
7353 
7354 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7355 		mp1->b_cont = mp;
7356 
7357 		/* Initialize the fragment header. */
7358 		ipf = (ipf_t *)mp1->b_rptr;
7359 		ipf->ipf_mp = mp1;
7360 		ipf->ipf_ptphn = ipfp;
7361 		ipfp[0] = ipf;
7362 		ipf->ipf_hash_next = NULL;
7363 		ipf->ipf_ident = ident;
7364 		ipf->ipf_protocol = proto;
7365 		ipf->ipf_src = src;
7366 		ipf->ipf_dst = dst;
7367 		ipf->ipf_nf_hdr_len = 0;
7368 		/* Record reassembly start time. */
7369 		ipf->ipf_timestamp = gethrestime_sec();
7370 		/* Record ipf generation and account for frag header */
7371 		ipf->ipf_gen = ill->ill_ipf_gen++;
7372 		ipf->ipf_count = MBLKSIZE(mp1);
7373 		ipf->ipf_last_frag_seen = B_FALSE;
7374 		ipf->ipf_ecn = ecn_info;
7375 		ipf->ipf_num_dups = 0;
7376 		ipfb->ipfb_frag_pkts++;
7377 		ipf->ipf_checksum = 0;
7378 		ipf->ipf_checksum_flags = 0;
7379 
7380 		/* Store checksum value in fragment header */
7381 		if (sum_flags != 0) {
7382 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7383 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7384 			ipf->ipf_checksum = sum_val;
7385 			ipf->ipf_checksum_flags = sum_flags;
7386 		}
7387 
7388 		/*
7389 		 * We handle reassembly two ways.  In the easy case,
7390 		 * where all the fragments show up in order, we do
7391 		 * minimal bookkeeping, and just clip new pieces on
7392 		 * the end.  If we ever see a hole, then we go off
7393 		 * to ip_reassemble which has to mark the pieces and
7394 		 * keep track of the number of holes, etc.  Obviously,
7395 		 * the point of having both mechanisms is so we can
7396 		 * handle the easy case as efficiently as possible.
7397 		 */
7398 		if (offset == 0) {
7399 			/* Easy case, in-order reassembly so far. */
7400 			ipf->ipf_count += msg_len;
7401 			ipf->ipf_tail_mp = tail_mp;
7402 			/*
7403 			 * Keep track of next expected offset in
7404 			 * ipf_end.
7405 			 */
7406 			ipf->ipf_end = end;
7407 			ipf->ipf_nf_hdr_len = hdr_length;
7408 		} else {
7409 			/* Hard case, hole at the beginning. */
7410 			ipf->ipf_tail_mp = NULL;
7411 			/*
7412 			 * ipf_end == 0 means that we have given up
7413 			 * on easy reassembly.
7414 			 */
7415 			ipf->ipf_end = 0;
7416 
7417 			/* Forget checksum offload from now on */
7418 			ipf->ipf_checksum_flags = 0;
7419 
7420 			/*
7421 			 * ipf_hole_cnt is set by ip_reassemble.
7422 			 * ipf_count is updated by ip_reassemble.
7423 			 * No need to check for return value here
7424 			 * as we don't expect reassembly to complete
7425 			 * or fail for the first fragment itself.
7426 			 */
7427 			(void) ip_reassemble(mp, ipf,
7428 			    (frag_offset_flags & IPH_OFFSET) << 3,
7429 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7430 		}
7431 		/* Update per ipfb and ill byte counts */
7432 		ipfb->ipfb_count += ipf->ipf_count;
7433 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7434 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7435 		/* If the frag timer wasn't already going, start it. */
7436 		mutex_enter(&ill->ill_lock);
7437 		ill_frag_timer_start(ill);
7438 		mutex_exit(&ill->ill_lock);
7439 		goto reass_done;
7440 	}
7441 
7442 	/*
7443 	 * If the packet's flag has changed (it could be coming up
7444 	 * from an interface different than the previous, therefore
7445 	 * possibly different checksum capability), then forget about
7446 	 * any stored checksum states.  Otherwise add the value to
7447 	 * the existing one stored in the fragment header.
7448 	 */
7449 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7450 		sum_val += ipf->ipf_checksum;
7451 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7452 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7453 		ipf->ipf_checksum = sum_val;
7454 	} else if (ipf->ipf_checksum_flags != 0) {
7455 		/* Forget checksum offload from now on */
7456 		ipf->ipf_checksum_flags = 0;
7457 	}
7458 
7459 	/*
7460 	 * We have a new piece of a datagram which is already being
7461 	 * reassembled.  Update the ECN info if all IP fragments
7462 	 * are ECN capable.  If there is one which is not, clear
7463 	 * all the info.  If there is at least one which has CE
7464 	 * code point, IP needs to report that up to transport.
7465 	 */
7466 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7467 		if (ecn_info == IPH_ECN_CE)
7468 			ipf->ipf_ecn = IPH_ECN_CE;
7469 	} else {
7470 		ipf->ipf_ecn = IPH_ECN_NECT;
7471 	}
7472 	if (offset && ipf->ipf_end == offset) {
7473 		/* The new fragment fits at the end */
7474 		ipf->ipf_tail_mp->b_cont = mp;
7475 		/* Update the byte count */
7476 		ipf->ipf_count += msg_len;
7477 		/* Update per ipfb and ill byte counts */
7478 		ipfb->ipfb_count += msg_len;
7479 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7480 		atomic_add_32(&ill->ill_frag_count, msg_len);
7481 		if (frag_offset_flags & IPH_MF) {
7482 			/* More to come. */
7483 			ipf->ipf_end = end;
7484 			ipf->ipf_tail_mp = tail_mp;
7485 			goto reass_done;
7486 		}
7487 	} else {
7488 		/* Go do the hard cases. */
7489 		int ret;
7490 
7491 		if (offset == 0)
7492 			ipf->ipf_nf_hdr_len = hdr_length;
7493 
7494 		/* Save current byte count */
7495 		count = ipf->ipf_count;
7496 		ret = ip_reassemble(mp, ipf,
7497 		    (frag_offset_flags & IPH_OFFSET) << 3,
7498 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7499 		/* Count of bytes added and subtracted (freeb()ed) */
7500 		count = ipf->ipf_count - count;
7501 		if (count) {
7502 			/* Update per ipfb and ill byte counts */
7503 			ipfb->ipfb_count += count;
7504 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7505 			atomic_add_32(&ill->ill_frag_count, count);
7506 		}
7507 		if (ret == IP_REASS_PARTIAL) {
7508 			goto reass_done;
7509 		} else if (ret == IP_REASS_FAILED) {
7510 			/* Reassembly failed. Free up all resources */
7511 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7512 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7513 				IP_REASS_SET_START(t_mp, 0);
7514 				IP_REASS_SET_END(t_mp, 0);
7515 			}
7516 			freemsg(mp);
7517 			goto reass_done;
7518 		}
7519 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7520 	}
7521 	/*
7522 	 * We have completed reassembly.  Unhook the frag header from
7523 	 * the reassembly list.
7524 	 *
7525 	 * Before we free the frag header, record the ECN info
7526 	 * to report back to the transport.
7527 	 */
7528 	ecn_info = ipf->ipf_ecn;
7529 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7530 	ipfp = ipf->ipf_ptphn;
7531 
7532 	/* We need to supply these to caller */
7533 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7534 		sum_val = ipf->ipf_checksum;
7535 	else
7536 		sum_val = 0;
7537 
7538 	mp1 = ipf->ipf_mp;
7539 	count = ipf->ipf_count;
7540 	ipf = ipf->ipf_hash_next;
7541 	if (ipf != NULL)
7542 		ipf->ipf_ptphn = ipfp;
7543 	ipfp[0] = ipf;
7544 	atomic_add_32(&ill->ill_frag_count, -count);
7545 	ASSERT(ipfb->ipfb_count >= count);
7546 	ipfb->ipfb_count -= count;
7547 	ipfb->ipfb_frag_pkts--;
7548 	mutex_exit(&ipfb->ipfb_lock);
7549 	/* Ditch the frag header. */
7550 	mp = mp1->b_cont;
7551 
7552 	freeb(mp1);
7553 
7554 	/* Restore original IP length in header. */
7555 	packet_size = (uint32_t)msgdsize(mp);
7556 	if (packet_size > IP_MAXPACKET) {
7557 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7558 		ip_drop_input("Reassembled packet too large", mp, ill);
7559 		freemsg(mp);
7560 		return (NULL);
7561 	}
7562 
7563 	if (DB_REF(mp) > 1) {
7564 		mblk_t *mp2 = copymsg(mp);
7565 
7566 		if (mp2 == NULL) {
7567 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7568 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7569 			freemsg(mp);
7570 			return (NULL);
7571 		}
7572 		freemsg(mp);
7573 		mp = mp2;
7574 	}
7575 	ipha = (ipha_t *)mp->b_rptr;
7576 
7577 	ipha->ipha_length = htons((uint16_t)packet_size);
7578 	/* We're now complete, zip the frag state */
7579 	ipha->ipha_fragment_offset_and_flags = 0;
7580 	/* Record the ECN info. */
7581 	ipha->ipha_type_of_service &= 0xFC;
7582 	ipha->ipha_type_of_service |= ecn_info;
7583 
7584 	/* Update the receive attributes */
7585 	ira->ira_pktlen = packet_size;
7586 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7587 
7588 	/* Reassembly is successful; set checksum information in packet */
7589 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7590 	DB_CKSUMFLAGS(mp) = sum_flags;
7591 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7592 
7593 	return (mp);
7594 }
7595 
7596 /*
7597  * Pullup function that should be used for IP input in order to
7598  * ensure we do not loose the L2 source address; we need the l2 source
7599  * address for IP_RECVSLLA and for ndp_input.
7600  *
7601  * We return either NULL or b_rptr.
7602  */
7603 void *
7604 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7605 {
7606 	ill_t		*ill = ira->ira_ill;
7607 
7608 	if (ip_rput_pullups++ == 0) {
7609 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7610 		    "ip_pullup: %s forced us to "
7611 		    " pullup pkt, hdr len %ld, hdr addr %p",
7612 		    ill->ill_name, len, (void *)mp->b_rptr);
7613 	}
7614 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7615 		ip_setl2src(mp, ira, ira->ira_rill);
7616 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7617 	if (!pullupmsg(mp, len))
7618 		return (NULL);
7619 	else
7620 		return (mp->b_rptr);
7621 }
7622 
7623 /*
7624  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7625  * When called from the ULP ira_rill will be NULL hence the caller has to
7626  * pass in the ill.
7627  */
7628 /* ARGSUSED */
7629 void
7630 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7631 {
7632 	const uchar_t *addr;
7633 	int alen;
7634 
7635 	if (ira->ira_flags & IRAF_L2SRC_SET)
7636 		return;
7637 
7638 	ASSERT(ill != NULL);
7639 	alen = ill->ill_phys_addr_length;
7640 	ASSERT(alen <= sizeof (ira->ira_l2src));
7641 	if (ira->ira_mhip != NULL &&
7642 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7643 		bcopy(addr, ira->ira_l2src, alen);
7644 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7645 	    (addr = ill->ill_phys_addr) != NULL) {
7646 		bcopy(addr, ira->ira_l2src, alen);
7647 	} else {
7648 		bzero(ira->ira_l2src, alen);
7649 	}
7650 	ira->ira_flags |= IRAF_L2SRC_SET;
7651 }
7652 
7653 /*
7654  * check ip header length and align it.
7655  */
7656 mblk_t *
7657 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7658 {
7659 	ill_t	*ill = ira->ira_ill;
7660 	ssize_t len;
7661 
7662 	len = MBLKL(mp);
7663 
7664 	if (!OK_32PTR(mp->b_rptr))
7665 		IP_STAT(ill->ill_ipst, ip_notaligned);
7666 	else
7667 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7668 
7669 	/* Guard against bogus device drivers */
7670 	if (len < 0) {
7671 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7672 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7673 		freemsg(mp);
7674 		return (NULL);
7675 	}
7676 
7677 	if (len == 0) {
7678 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7679 		mblk_t *mp1 = mp->b_cont;
7680 
7681 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7682 			ip_setl2src(mp, ira, ira->ira_rill);
7683 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7684 
7685 		freeb(mp);
7686 		mp = mp1;
7687 		if (mp == NULL)
7688 			return (NULL);
7689 
7690 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7691 			return (mp);
7692 	}
7693 	if (ip_pullup(mp, min_size, ira) == NULL) {
7694 		if (msgdsize(mp) < min_size) {
7695 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7696 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7697 		} else {
7698 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7699 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7700 		}
7701 		freemsg(mp);
7702 		return (NULL);
7703 	}
7704 	return (mp);
7705 }
7706 
7707 /*
7708  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7709  */
7710 mblk_t *
7711 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7712     uint_t min_size, ip_recv_attr_t *ira)
7713 {
7714 	ill_t	*ill = ira->ira_ill;
7715 
7716 	/*
7717 	 * Make sure we have data length consistent
7718 	 * with the IP header.
7719 	 */
7720 	if (mp->b_cont == NULL) {
7721 		/* pkt_len is based on ipha_len, not the mblk length */
7722 		if (pkt_len < min_size) {
7723 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7724 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7725 			freemsg(mp);
7726 			return (NULL);
7727 		}
7728 		if (len < 0) {
7729 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7730 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7731 			freemsg(mp);
7732 			return (NULL);
7733 		}
7734 		/* Drop any pad */
7735 		mp->b_wptr = rptr + pkt_len;
7736 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7737 		ASSERT(pkt_len >= min_size);
7738 		if (pkt_len < min_size) {
7739 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7740 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7741 			freemsg(mp);
7742 			return (NULL);
7743 		}
7744 		if (len < 0) {
7745 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7746 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7747 			freemsg(mp);
7748 			return (NULL);
7749 		}
7750 		/* Drop any pad */
7751 		(void) adjmsg(mp, -len);
7752 		/*
7753 		 * adjmsg may have freed an mblk from the chain, hence
7754 		 * invalidate any hw checksum here. This will force IP to
7755 		 * calculate the checksum in sw, but only for this packet.
7756 		 */
7757 		DB_CKSUMFLAGS(mp) = 0;
7758 		IP_STAT(ill->ill_ipst, ip_multimblk);
7759 	}
7760 	return (mp);
7761 }
7762 
7763 /*
7764  * Check that the IPv4 opt_len is consistent with the packet and pullup
7765  * the options.
7766  */
7767 mblk_t *
7768 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7769     ip_recv_attr_t *ira)
7770 {
7771 	ill_t	*ill = ira->ira_ill;
7772 	ssize_t len;
7773 
7774 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7775 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7776 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7777 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7778 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7779 		freemsg(mp);
7780 		return (NULL);
7781 	}
7782 
7783 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7784 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7785 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7786 		freemsg(mp);
7787 		return (NULL);
7788 	}
7789 	/*
7790 	 * Recompute complete header length and make sure we
7791 	 * have access to all of it.
7792 	 */
7793 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7794 	if (len > (mp->b_wptr - mp->b_rptr)) {
7795 		if (len > pkt_len) {
7796 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7797 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7798 			freemsg(mp);
7799 			return (NULL);
7800 		}
7801 		if (ip_pullup(mp, len, ira) == NULL) {
7802 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7803 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7804 			freemsg(mp);
7805 			return (NULL);
7806 		}
7807 	}
7808 	return (mp);
7809 }
7810 
7811 /*
7812  * Returns a new ire, or the same ire, or NULL.
7813  * If a different IRE is returned, then it is held; the caller
7814  * needs to release it.
7815  * In no case is there any hold/release on the ire argument.
7816  */
7817 ire_t *
7818 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7819 {
7820 	ire_t		*new_ire;
7821 	ill_t		*ire_ill;
7822 	uint_t		ifindex;
7823 	ip_stack_t	*ipst = ill->ill_ipst;
7824 	boolean_t	strict_check = B_FALSE;
7825 
7826 	/*
7827 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7828 	 * issue (e.g. packet received on an underlying interface matched an
7829 	 * IRE_LOCAL on its associated group interface).
7830 	 */
7831 	ASSERT(ire->ire_ill != NULL);
7832 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7833 		return (ire);
7834 
7835 	/*
7836 	 * Do another ire lookup here, using the ingress ill, to see if the
7837 	 * interface is in a usesrc group.
7838 	 * As long as the ills belong to the same group, we don't consider
7839 	 * them to be arriving on the wrong interface. Thus, if the switch
7840 	 * is doing inbound load spreading, we won't drop packets when the
7841 	 * ip*_strict_dst_multihoming switch is on.
7842 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7843 	 * where the local address may not be unique. In this case we were
7844 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7845 	 * actually returned. The new lookup, which is more specific, should
7846 	 * only find the IRE_LOCAL associated with the ingress ill if one
7847 	 * exists.
7848 	 */
7849 	if (ire->ire_ipversion == IPV4_VERSION) {
7850 		if (ipst->ips_ip_strict_dst_multihoming)
7851 			strict_check = B_TRUE;
7852 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7853 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7854 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7855 	} else {
7856 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7857 		if (ipst->ips_ipv6_strict_dst_multihoming)
7858 			strict_check = B_TRUE;
7859 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7860 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7861 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7862 	}
7863 	/*
7864 	 * If the same ire that was returned in ip_input() is found then this
7865 	 * is an indication that usesrc groups are in use. The packet
7866 	 * arrived on a different ill in the group than the one associated with
7867 	 * the destination address.  If a different ire was found then the same
7868 	 * IP address must be hosted on multiple ills. This is possible with
7869 	 * unnumbered point2point interfaces. We switch to use this new ire in
7870 	 * order to have accurate interface statistics.
7871 	 */
7872 	if (new_ire != NULL) {
7873 		/* Note: held in one case but not the other? Caller handles */
7874 		if (new_ire != ire)
7875 			return (new_ire);
7876 		/* Unchanged */
7877 		ire_refrele(new_ire);
7878 		return (ire);
7879 	}
7880 
7881 	/*
7882 	 * Chase pointers once and store locally.
7883 	 */
7884 	ASSERT(ire->ire_ill != NULL);
7885 	ire_ill = ire->ire_ill;
7886 	ifindex = ill->ill_usesrc_ifindex;
7887 
7888 	/*
7889 	 * Check if it's a legal address on the 'usesrc' interface.
7890 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7891 	 * can just check phyint_ifindex.
7892 	 */
7893 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7894 		return (ire);
7895 	}
7896 
7897 	/*
7898 	 * If the ip*_strict_dst_multihoming switch is on then we can
7899 	 * only accept this packet if the interface is marked as routing.
7900 	 */
7901 	if (!(strict_check))
7902 		return (ire);
7903 
7904 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7905 		return (ire);
7906 	}
7907 	return (NULL);
7908 }
7909 
7910 /*
7911  * This function is used to construct a mac_header_info_s from a
7912  * DL_UNITDATA_IND message.
7913  * The address fields in the mhi structure points into the message,
7914  * thus the caller can't use those fields after freeing the message.
7915  *
7916  * We determine whether the packet received is a non-unicast packet
7917  * and in doing so, determine whether or not it is broadcast vs multicast.
7918  * For it to be a broadcast packet, we must have the appropriate mblk_t
7919  * hanging off the ill_t.  If this is either not present or doesn't match
7920  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7921  * to be multicast.  Thus NICs that have no broadcast address (or no
7922  * capability for one, such as point to point links) cannot return as
7923  * the packet being broadcast.
7924  */
7925 void
7926 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7927 {
7928 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7929 	mblk_t *bmp;
7930 	uint_t extra_offset;
7931 
7932 	bzero(mhip, sizeof (struct mac_header_info_s));
7933 
7934 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7935 
7936 	if (ill->ill_sap_length < 0)
7937 		extra_offset = 0;
7938 	else
7939 		extra_offset = ill->ill_sap_length;
7940 
7941 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7942 	    extra_offset;
7943 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7944 	    extra_offset;
7945 
7946 	if (!ind->dl_group_address)
7947 		return;
7948 
7949 	/* Multicast or broadcast */
7950 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7951 
7952 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7953 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7954 	    (bmp = ill->ill_bcast_mp) != NULL) {
7955 		dl_unitdata_req_t *dlur;
7956 		uint8_t *bphys_addr;
7957 
7958 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7959 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7960 		    extra_offset;
7961 
7962 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7963 		    ind->dl_dest_addr_length) == 0)
7964 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7965 	}
7966 }
7967 
7968 /*
7969  * This function is used to construct a mac_header_info_s from a
7970  * M_DATA fastpath message from a DLPI driver.
7971  * The address fields in the mhi structure points into the message,
7972  * thus the caller can't use those fields after freeing the message.
7973  *
7974  * We determine whether the packet received is a non-unicast packet
7975  * and in doing so, determine whether or not it is broadcast vs multicast.
7976  * For it to be a broadcast packet, we must have the appropriate mblk_t
7977  * hanging off the ill_t.  If this is either not present or doesn't match
7978  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7979  * to be multicast.  Thus NICs that have no broadcast address (or no
7980  * capability for one, such as point to point links) cannot return as
7981  * the packet being broadcast.
7982  */
7983 void
7984 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7985 {
7986 	mblk_t *bmp;
7987 	struct ether_header *pether;
7988 
7989 	bzero(mhip, sizeof (struct mac_header_info_s));
7990 
7991 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7992 
7993 	pether = (struct ether_header *)((char *)mp->b_rptr
7994 	    - sizeof (struct ether_header));
7995 
7996 	/*
7997 	 * Make sure the interface is an ethernet type, since we don't
7998 	 * know the header format for anything but Ethernet. Also make
7999 	 * sure we are pointing correctly above db_base.
8000 	 */
8001 	if (ill->ill_type != IFT_ETHER)
8002 		return;
8003 
8004 retry:
8005 	if ((uchar_t *)pether < mp->b_datap->db_base)
8006 		return;
8007 
8008 	/* Is there a VLAN tag? */
8009 	if (ill->ill_isv6) {
8010 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
8011 			pether = (struct ether_header *)((char *)pether - 4);
8012 			goto retry;
8013 		}
8014 	} else {
8015 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
8016 			pether = (struct ether_header *)((char *)pether - 4);
8017 			goto retry;
8018 		}
8019 	}
8020 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
8021 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
8022 
8023 	if (!(mhip->mhi_daddr[0] & 0x01))
8024 		return;
8025 
8026 	/* Multicast or broadcast */
8027 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
8028 
8029 	if ((bmp = ill->ill_bcast_mp) != NULL) {
8030 		dl_unitdata_req_t *dlur;
8031 		uint8_t *bphys_addr;
8032 		uint_t	addrlen;
8033 
8034 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
8035 		addrlen = dlur->dl_dest_addr_length;
8036 		if (ill->ill_sap_length < 0) {
8037 			bphys_addr = (uchar_t *)dlur +
8038 			    dlur->dl_dest_addr_offset;
8039 			addrlen += ill->ill_sap_length;
8040 		} else {
8041 			bphys_addr = (uchar_t *)dlur +
8042 			    dlur->dl_dest_addr_offset +
8043 			    ill->ill_sap_length;
8044 			addrlen -= ill->ill_sap_length;
8045 		}
8046 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
8047 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
8048 	}
8049 }
8050 
8051 /*
8052  * Handle anything but M_DATA messages
8053  * We see the DL_UNITDATA_IND which are part
8054  * of the data path, and also the other messages from the driver.
8055  */
8056 void
8057 ip_rput_notdata(ill_t *ill, mblk_t *mp)
8058 {
8059 	mblk_t		*first_mp;
8060 	struct iocblk   *iocp;
8061 	struct mac_header_info_s mhi;
8062 
8063 	switch (DB_TYPE(mp)) {
8064 	case M_PROTO:
8065 	case M_PCPROTO: {
8066 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
8067 		    DL_UNITDATA_IND) {
8068 			/* Go handle anything other than data elsewhere. */
8069 			ip_rput_dlpi(ill, mp);
8070 			return;
8071 		}
8072 
8073 		first_mp = mp;
8074 		mp = first_mp->b_cont;
8075 		first_mp->b_cont = NULL;
8076 
8077 		if (mp == NULL) {
8078 			freeb(first_mp);
8079 			return;
8080 		}
8081 		ip_dlur_to_mhi(ill, first_mp, &mhi);
8082 		if (ill->ill_isv6)
8083 			ip_input_v6(ill, NULL, mp, &mhi);
8084 		else
8085 			ip_input(ill, NULL, mp, &mhi);
8086 
8087 		/* Ditch the DLPI header. */
8088 		freeb(first_mp);
8089 		return;
8090 	}
8091 	case M_IOCACK:
8092 		iocp = (struct iocblk *)mp->b_rptr;
8093 		switch (iocp->ioc_cmd) {
8094 		case DL_IOC_HDR_INFO:
8095 			ill_fastpath_ack(ill, mp);
8096 			return;
8097 		default:
8098 			putnext(ill->ill_rq, mp);
8099 			return;
8100 		}
8101 		/* FALLTHRU */
8102 	case M_ERROR:
8103 	case M_HANGUP:
8104 		mutex_enter(&ill->ill_lock);
8105 		if (ill->ill_state_flags & ILL_CONDEMNED) {
8106 			mutex_exit(&ill->ill_lock);
8107 			freemsg(mp);
8108 			return;
8109 		}
8110 		ill_refhold_locked(ill);
8111 		mutex_exit(&ill->ill_lock);
8112 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
8113 		    B_FALSE);
8114 		return;
8115 	case M_CTL:
8116 		putnext(ill->ill_rq, mp);
8117 		return;
8118 	case M_IOCNAK:
8119 		ip1dbg(("got iocnak "));
8120 		iocp = (struct iocblk *)mp->b_rptr;
8121 		switch (iocp->ioc_cmd) {
8122 		case DL_IOC_HDR_INFO:
8123 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
8124 			return;
8125 		default:
8126 			break;
8127 		}
8128 		/* FALLTHRU */
8129 	default:
8130 		putnext(ill->ill_rq, mp);
8131 		return;
8132 	}
8133 }
8134 
8135 /* Read side put procedure.  Packets coming from the wire arrive here. */
8136 void
8137 ip_rput(queue_t *q, mblk_t *mp)
8138 {
8139 	ill_t	*ill;
8140 	union DL_primitives *dl;
8141 
8142 	ill = (ill_t *)q->q_ptr;
8143 
8144 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
8145 		/*
8146 		 * If things are opening or closing, only accept high-priority
8147 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
8148 		 * created; on close, things hanging off the ill may have been
8149 		 * freed already.)
8150 		 */
8151 		dl = (union DL_primitives *)mp->b_rptr;
8152 		if (DB_TYPE(mp) != M_PCPROTO ||
8153 		    dl->dl_primitive == DL_UNITDATA_IND) {
8154 			inet_freemsg(mp);
8155 			return;
8156 		}
8157 	}
8158 	if (DB_TYPE(mp) == M_DATA) {
8159 		struct mac_header_info_s mhi;
8160 
8161 		ip_mdata_to_mhi(ill, mp, &mhi);
8162 		ip_input(ill, NULL, mp, &mhi);
8163 	} else {
8164 		ip_rput_notdata(ill, mp);
8165 	}
8166 }
8167 
8168 /*
8169  * Move the information to a copy.
8170  */
8171 mblk_t *
8172 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8173 {
8174 	mblk_t		*mp1;
8175 	ill_t		*ill = ira->ira_ill;
8176 	ip_stack_t	*ipst = ill->ill_ipst;
8177 
8178 	IP_STAT(ipst, ip_db_ref);
8179 
8180 	/* Make sure we have ira_l2src before we loose the original mblk */
8181 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
8182 		ip_setl2src(mp, ira, ira->ira_rill);
8183 
8184 	mp1 = copymsg(mp);
8185 	if (mp1 == NULL) {
8186 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8187 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
8188 		freemsg(mp);
8189 		return (NULL);
8190 	}
8191 	/* preserve the hardware checksum flags and data, if present */
8192 	if (DB_CKSUMFLAGS(mp) != 0) {
8193 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8194 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8195 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8196 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8197 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8198 	}
8199 	freemsg(mp);
8200 	return (mp1);
8201 }
8202 
8203 static void
8204 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8205     t_uscalar_t err)
8206 {
8207 	if (dl_err == DL_SYSERR) {
8208 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8209 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8210 		    ill->ill_name, dl_primstr(prim), err);
8211 		return;
8212 	}
8213 
8214 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8215 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8216 	    dl_errstr(dl_err));
8217 }
8218 
8219 /*
8220  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8221  * than DL_UNITDATA_IND messages. If we need to process this message
8222  * exclusively, we call qwriter_ip, in which case we also need to call
8223  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8224  */
8225 void
8226 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8227 {
8228 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8229 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8230 	queue_t		*q = ill->ill_rq;
8231 	t_uscalar_t	prim = dloa->dl_primitive;
8232 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8233 
8234 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8235 	    char *, dl_primstr(prim), ill_t *, ill);
8236 	ip1dbg(("ip_rput_dlpi"));
8237 
8238 	/*
8239 	 * If we received an ACK but didn't send a request for it, then it
8240 	 * can't be part of any pending operation; discard up-front.
8241 	 */
8242 	switch (prim) {
8243 	case DL_ERROR_ACK:
8244 		reqprim = dlea->dl_error_primitive;
8245 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8246 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8247 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8248 		    dlea->dl_unix_errno));
8249 		break;
8250 	case DL_OK_ACK:
8251 		reqprim = dloa->dl_correct_primitive;
8252 		break;
8253 	case DL_INFO_ACK:
8254 		reqprim = DL_INFO_REQ;
8255 		break;
8256 	case DL_BIND_ACK:
8257 		reqprim = DL_BIND_REQ;
8258 		break;
8259 	case DL_PHYS_ADDR_ACK:
8260 		reqprim = DL_PHYS_ADDR_REQ;
8261 		break;
8262 	case DL_NOTIFY_ACK:
8263 		reqprim = DL_NOTIFY_REQ;
8264 		break;
8265 	case DL_CAPABILITY_ACK:
8266 		reqprim = DL_CAPABILITY_REQ;
8267 		break;
8268 	}
8269 
8270 	if (prim != DL_NOTIFY_IND) {
8271 		if (reqprim == DL_PRIM_INVAL ||
8272 		    !ill_dlpi_pending(ill, reqprim)) {
8273 			/* Not a DLPI message we support or expected */
8274 			freemsg(mp);
8275 			return;
8276 		}
8277 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8278 		    dl_primstr(reqprim)));
8279 	}
8280 
8281 	switch (reqprim) {
8282 	case DL_UNBIND_REQ:
8283 		/*
8284 		 * NOTE: we mark the unbind as complete even if we got a
8285 		 * DL_ERROR_ACK, since there's not much else we can do.
8286 		 */
8287 		mutex_enter(&ill->ill_lock);
8288 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8289 		cv_signal(&ill->ill_cv);
8290 		mutex_exit(&ill->ill_lock);
8291 		break;
8292 
8293 	case DL_ENABMULTI_REQ:
8294 		if (prim == DL_OK_ACK) {
8295 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8296 				ill->ill_dlpi_multicast_state = IDS_OK;
8297 		}
8298 		break;
8299 	}
8300 
8301 	/*
8302 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8303 	 * need to become writer to continue to process it.  Because an
8304 	 * exclusive operation doesn't complete until replies to all queued
8305 	 * DLPI messages have been received, we know we're in the middle of an
8306 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8307 	 *
8308 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8309 	 * Since this is on the ill stream we unconditionally bump up the
8310 	 * refcount without doing ILL_CAN_LOOKUP().
8311 	 */
8312 	ill_refhold(ill);
8313 	if (prim == DL_NOTIFY_IND)
8314 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8315 	else
8316 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8317 }
8318 
8319 /*
8320  * Handling of DLPI messages that require exclusive access to the ipsq.
8321  *
8322  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8323  * happen here. (along with mi_copy_done)
8324  */
8325 /* ARGSUSED */
8326 static void
8327 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8328 {
8329 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8330 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8331 	int		err = 0;
8332 	ill_t		*ill = (ill_t *)q->q_ptr;
8333 	ipif_t		*ipif = NULL;
8334 	mblk_t		*mp1 = NULL;
8335 	conn_t		*connp = NULL;
8336 	t_uscalar_t	paddrreq;
8337 	mblk_t		*mp_hw;
8338 	boolean_t	success;
8339 	boolean_t	ioctl_aborted = B_FALSE;
8340 	boolean_t	log = B_TRUE;
8341 
8342 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8343 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8344 
8345 	ip1dbg(("ip_rput_dlpi_writer .."));
8346 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8347 	ASSERT(IAM_WRITER_ILL(ill));
8348 
8349 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8350 	/*
8351 	 * The current ioctl could have been aborted by the user and a new
8352 	 * ioctl to bring up another ill could have started. We could still
8353 	 * get a response from the driver later.
8354 	 */
8355 	if (ipif != NULL && ipif->ipif_ill != ill)
8356 		ioctl_aborted = B_TRUE;
8357 
8358 	switch (dloa->dl_primitive) {
8359 	case DL_ERROR_ACK:
8360 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8361 		    dl_primstr(dlea->dl_error_primitive)));
8362 
8363 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8364 		    char *, dl_primstr(dlea->dl_error_primitive),
8365 		    ill_t *, ill);
8366 
8367 		switch (dlea->dl_error_primitive) {
8368 		case DL_DISABMULTI_REQ:
8369 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8370 			break;
8371 		case DL_PROMISCON_REQ:
8372 		case DL_PROMISCOFF_REQ:
8373 		case DL_UNBIND_REQ:
8374 		case DL_ATTACH_REQ:
8375 		case DL_INFO_REQ:
8376 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8377 			break;
8378 		case DL_NOTIFY_REQ:
8379 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8380 			log = B_FALSE;
8381 			break;
8382 		case DL_PHYS_ADDR_REQ:
8383 			/*
8384 			 * For IPv6 only, there are two additional
8385 			 * phys_addr_req's sent to the driver to get the
8386 			 * IPv6 token and lla. This allows IP to acquire
8387 			 * the hardware address format for a given interface
8388 			 * without having built in knowledge of the hardware
8389 			 * address. ill_phys_addr_pend keeps track of the last
8390 			 * DL_PAR sent so we know which response we are
8391 			 * dealing with. ill_dlpi_done will update
8392 			 * ill_phys_addr_pend when it sends the next req.
8393 			 * We don't complete the IOCTL until all three DL_PARs
8394 			 * have been attempted, so set *_len to 0 and break.
8395 			 */
8396 			paddrreq = ill->ill_phys_addr_pend;
8397 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8398 			if (paddrreq == DL_IPV6_TOKEN) {
8399 				ill->ill_token_length = 0;
8400 				log = B_FALSE;
8401 				break;
8402 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8403 				ill->ill_nd_lla_len = 0;
8404 				log = B_FALSE;
8405 				break;
8406 			}
8407 			/*
8408 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8409 			 * We presumably have an IOCTL hanging out waiting
8410 			 * for completion. Find it and complete the IOCTL
8411 			 * with the error noted.
8412 			 * However, ill_dl_phys was called on an ill queue
8413 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8414 			 * set. But the ioctl is known to be pending on ill_wq.
8415 			 */
8416 			if (!ill->ill_ifname_pending)
8417 				break;
8418 			ill->ill_ifname_pending = 0;
8419 			if (!ioctl_aborted)
8420 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8421 			if (mp1 != NULL) {
8422 				/*
8423 				 * This operation (SIOCSLIFNAME) must have
8424 				 * happened on the ill. Assert there is no conn
8425 				 */
8426 				ASSERT(connp == NULL);
8427 				q = ill->ill_wq;
8428 			}
8429 			break;
8430 		case DL_BIND_REQ:
8431 			ill_dlpi_done(ill, DL_BIND_REQ);
8432 			if (ill->ill_ifname_pending)
8433 				break;
8434 			/*
8435 			 * Something went wrong with the bind.  We presumably
8436 			 * have an IOCTL hanging out waiting for completion.
8437 			 * Find it, take down the interface that was coming
8438 			 * up, and complete the IOCTL with the error noted.
8439 			 */
8440 			if (!ioctl_aborted)
8441 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8442 			if (mp1 != NULL) {
8443 				/*
8444 				 * This might be a result of a DL_NOTE_REPLUMB
8445 				 * notification. In that case, connp is NULL.
8446 				 */
8447 				if (connp != NULL)
8448 					q = CONNP_TO_WQ(connp);
8449 
8450 				(void) ipif_down(ipif, NULL, NULL);
8451 				/* error is set below the switch */
8452 			}
8453 			break;
8454 		case DL_ENABMULTI_REQ:
8455 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8456 
8457 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8458 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8459 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8460 
8461 				printf("ip: joining multicasts failed (%d)"
8462 				    " on %s - will use link layer "
8463 				    "broadcasts for multicast\n",
8464 				    dlea->dl_errno, ill->ill_name);
8465 
8466 				/*
8467 				 * Set up for multi_bcast; We are the
8468 				 * writer, so ok to access ill->ill_ipif
8469 				 * without any lock.
8470 				 */
8471 				mutex_enter(&ill->ill_phyint->phyint_lock);
8472 				ill->ill_phyint->phyint_flags |=
8473 				    PHYI_MULTI_BCAST;
8474 				mutex_exit(&ill->ill_phyint->phyint_lock);
8475 
8476 			}
8477 			freemsg(mp);	/* Don't want to pass this up */
8478 			return;
8479 		case DL_CAPABILITY_REQ:
8480 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8481 			    "DL_CAPABILITY REQ\n"));
8482 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8483 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8484 			ill_capability_done(ill);
8485 			freemsg(mp);
8486 			return;
8487 		}
8488 		/*
8489 		 * Note the error for IOCTL completion (mp1 is set when
8490 		 * ready to complete ioctl). If ill_ifname_pending_err is
8491 		 * set, an error occured during plumbing (ill_ifname_pending),
8492 		 * so we want to report that error.
8493 		 *
8494 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8495 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8496 		 * expected to get errack'd if the driver doesn't support
8497 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8498 		 * if these error conditions are encountered.
8499 		 */
8500 		if (mp1 != NULL) {
8501 			if (ill->ill_ifname_pending_err != 0)  {
8502 				err = ill->ill_ifname_pending_err;
8503 				ill->ill_ifname_pending_err = 0;
8504 			} else {
8505 				err = dlea->dl_unix_errno ?
8506 				    dlea->dl_unix_errno : ENXIO;
8507 			}
8508 		/*
8509 		 * If we're plumbing an interface and an error hasn't already
8510 		 * been saved, set ill_ifname_pending_err to the error passed
8511 		 * up. Ignore the error if log is B_FALSE (see comment above).
8512 		 */
8513 		} else if (log && ill->ill_ifname_pending &&
8514 		    ill->ill_ifname_pending_err == 0) {
8515 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8516 			    dlea->dl_unix_errno : ENXIO;
8517 		}
8518 
8519 		if (log)
8520 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8521 			    dlea->dl_errno, dlea->dl_unix_errno);
8522 		break;
8523 	case DL_CAPABILITY_ACK:
8524 		ill_capability_ack(ill, mp);
8525 		/*
8526 		 * The message has been handed off to ill_capability_ack
8527 		 * and must not be freed below
8528 		 */
8529 		mp = NULL;
8530 		break;
8531 
8532 	case DL_INFO_ACK:
8533 		/* Call a routine to handle this one. */
8534 		ill_dlpi_done(ill, DL_INFO_REQ);
8535 		ip_ll_subnet_defaults(ill, mp);
8536 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8537 		return;
8538 	case DL_BIND_ACK:
8539 		/*
8540 		 * We should have an IOCTL waiting on this unless
8541 		 * sent by ill_dl_phys, in which case just return
8542 		 */
8543 		ill_dlpi_done(ill, DL_BIND_REQ);
8544 		if (ill->ill_ifname_pending) {
8545 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8546 			    ill_t *, ill, mblk_t *, mp);
8547 			break;
8548 		}
8549 		if (!ioctl_aborted)
8550 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8551 		if (mp1 == NULL) {
8552 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8553 			break;
8554 		}
8555 		/*
8556 		 * mp1 was added by ill_dl_up(). if that is a result of
8557 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8558 		 */
8559 		if (connp != NULL)
8560 			q = CONNP_TO_WQ(connp);
8561 		/*
8562 		 * We are exclusive. So nothing can change even after
8563 		 * we get the pending mp.
8564 		 */
8565 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8566 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8567 
8568 		mutex_enter(&ill->ill_lock);
8569 		ill->ill_dl_up = 1;
8570 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8571 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8572 		mutex_exit(&ill->ill_lock);
8573 
8574 		/*
8575 		 * Now bring up the resolver; when that is complete, we'll
8576 		 * create IREs.  Note that we intentionally mirror what
8577 		 * ipif_up() would have done, because we got here by way of
8578 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8579 		 */
8580 		if (ill->ill_isv6) {
8581 			/*
8582 			 * v6 interfaces.
8583 			 * Unlike ARP which has to do another bind
8584 			 * and attach, once we get here we are
8585 			 * done with NDP
8586 			 */
8587 			(void) ipif_resolver_up(ipif, Res_act_initial);
8588 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8589 				err = ipif_up_done_v6(ipif);
8590 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8591 			/*
8592 			 * ARP and other v4 external resolvers.
8593 			 * Leave the pending mblk intact so that
8594 			 * the ioctl completes in ip_rput().
8595 			 */
8596 			if (connp != NULL)
8597 				mutex_enter(&connp->conn_lock);
8598 			mutex_enter(&ill->ill_lock);
8599 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8600 			mutex_exit(&ill->ill_lock);
8601 			if (connp != NULL)
8602 				mutex_exit(&connp->conn_lock);
8603 			if (success) {
8604 				err = ipif_resolver_up(ipif, Res_act_initial);
8605 				if (err == EINPROGRESS) {
8606 					freemsg(mp);
8607 					return;
8608 				}
8609 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8610 			} else {
8611 				/* The conn has started closing */
8612 				err = EINTR;
8613 			}
8614 		} else {
8615 			/*
8616 			 * This one is complete. Reply to pending ioctl.
8617 			 */
8618 			(void) ipif_resolver_up(ipif, Res_act_initial);
8619 			err = ipif_up_done(ipif);
8620 		}
8621 
8622 		if ((err == 0) && (ill->ill_up_ipifs)) {
8623 			err = ill_up_ipifs(ill, q, mp1);
8624 			if (err == EINPROGRESS) {
8625 				freemsg(mp);
8626 				return;
8627 			}
8628 		}
8629 
8630 		/*
8631 		 * If we have a moved ipif to bring up, and everything has
8632 		 * succeeded to this point, bring it up on the IPMP ill.
8633 		 * Otherwise, leave it down -- the admin can try to bring it
8634 		 * up by hand if need be.
8635 		 */
8636 		if (ill->ill_move_ipif != NULL) {
8637 			if (err != 0) {
8638 				ill->ill_move_ipif = NULL;
8639 			} else {
8640 				ipif = ill->ill_move_ipif;
8641 				ill->ill_move_ipif = NULL;
8642 				err = ipif_up(ipif, q, mp1);
8643 				if (err == EINPROGRESS) {
8644 					freemsg(mp);
8645 					return;
8646 				}
8647 			}
8648 		}
8649 		break;
8650 
8651 	case DL_NOTIFY_IND: {
8652 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8653 		uint_t orig_mtu;
8654 
8655 		switch (notify->dl_notification) {
8656 		case DL_NOTE_PHYS_ADDR:
8657 			err = ill_set_phys_addr(ill, mp);
8658 			break;
8659 
8660 		case DL_NOTE_REPLUMB:
8661 			/*
8662 			 * Directly return after calling ill_replumb().
8663 			 * Note that we should not free mp as it is reused
8664 			 * in the ill_replumb() function.
8665 			 */
8666 			err = ill_replumb(ill, mp);
8667 			return;
8668 
8669 		case DL_NOTE_FASTPATH_FLUSH:
8670 			nce_flush(ill, B_FALSE);
8671 			break;
8672 
8673 		case DL_NOTE_SDU_SIZE:
8674 			/*
8675 			 * The dce and fragmentation code can cope with
8676 			 * this changing while packets are being sent.
8677 			 * When packets are sent ip_output will discover
8678 			 * a change.
8679 			 *
8680 			 * Change the MTU size of the interface.
8681 			 */
8682 			mutex_enter(&ill->ill_lock);
8683 			ill->ill_current_frag = (uint_t)notify->dl_data;
8684 			if (ill->ill_current_frag > ill->ill_max_frag)
8685 				ill->ill_max_frag = ill->ill_current_frag;
8686 
8687 			orig_mtu = ill->ill_mtu;
8688 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8689 				ill->ill_mtu = ill->ill_current_frag;
8690 
8691 				/*
8692 				 * If ill_user_mtu was set (via
8693 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8694 				 */
8695 				if (ill->ill_user_mtu != 0 &&
8696 				    ill->ill_user_mtu < ill->ill_mtu)
8697 					ill->ill_mtu = ill->ill_user_mtu;
8698 
8699 				if (ill->ill_isv6) {
8700 					if (ill->ill_mtu < IPV6_MIN_MTU)
8701 						ill->ill_mtu = IPV6_MIN_MTU;
8702 				} else {
8703 					if (ill->ill_mtu < IP_MIN_MTU)
8704 						ill->ill_mtu = IP_MIN_MTU;
8705 				}
8706 			}
8707 			mutex_exit(&ill->ill_lock);
8708 			/*
8709 			 * Make sure all dce_generation checks find out
8710 			 * that ill_mtu has changed.
8711 			 */
8712 			if (orig_mtu != ill->ill_mtu) {
8713 				dce_increment_all_generations(ill->ill_isv6,
8714 				    ill->ill_ipst);
8715 			}
8716 
8717 			/*
8718 			 * Refresh IPMP meta-interface MTU if necessary.
8719 			 */
8720 			if (IS_UNDER_IPMP(ill))
8721 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8722 			break;
8723 
8724 		case DL_NOTE_LINK_UP:
8725 		case DL_NOTE_LINK_DOWN: {
8726 			/*
8727 			 * We are writer. ill / phyint / ipsq assocs stable.
8728 			 * The RUNNING flag reflects the state of the link.
8729 			 */
8730 			phyint_t *phyint = ill->ill_phyint;
8731 			uint64_t new_phyint_flags;
8732 			boolean_t changed = B_FALSE;
8733 			boolean_t went_up;
8734 
8735 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8736 			mutex_enter(&phyint->phyint_lock);
8737 
8738 			new_phyint_flags = went_up ?
8739 			    phyint->phyint_flags | PHYI_RUNNING :
8740 			    phyint->phyint_flags & ~PHYI_RUNNING;
8741 
8742 			if (IS_IPMP(ill)) {
8743 				new_phyint_flags = went_up ?
8744 				    new_phyint_flags & ~PHYI_FAILED :
8745 				    new_phyint_flags | PHYI_FAILED;
8746 			}
8747 
8748 			if (new_phyint_flags != phyint->phyint_flags) {
8749 				phyint->phyint_flags = new_phyint_flags;
8750 				changed = B_TRUE;
8751 			}
8752 			mutex_exit(&phyint->phyint_lock);
8753 			/*
8754 			 * ill_restart_dad handles the DAD restart and routing
8755 			 * socket notification logic.
8756 			 */
8757 			if (changed) {
8758 				ill_restart_dad(phyint->phyint_illv4, went_up);
8759 				ill_restart_dad(phyint->phyint_illv6, went_up);
8760 			}
8761 			break;
8762 		}
8763 		case DL_NOTE_PROMISC_ON_PHYS: {
8764 			phyint_t *phyint = ill->ill_phyint;
8765 
8766 			mutex_enter(&phyint->phyint_lock);
8767 			phyint->phyint_flags |= PHYI_PROMISC;
8768 			mutex_exit(&phyint->phyint_lock);
8769 			break;
8770 		}
8771 		case DL_NOTE_PROMISC_OFF_PHYS: {
8772 			phyint_t *phyint = ill->ill_phyint;
8773 
8774 			mutex_enter(&phyint->phyint_lock);
8775 			phyint->phyint_flags &= ~PHYI_PROMISC;
8776 			mutex_exit(&phyint->phyint_lock);
8777 			break;
8778 		}
8779 		case DL_NOTE_CAPAB_RENEG:
8780 			/*
8781 			 * Something changed on the driver side.
8782 			 * It wants us to renegotiate the capabilities
8783 			 * on this ill. One possible cause is the aggregation
8784 			 * interface under us where a port got added or
8785 			 * went away.
8786 			 *
8787 			 * If the capability negotiation is already done
8788 			 * or is in progress, reset the capabilities and
8789 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8790 			 * so that when the ack comes back, we can start
8791 			 * the renegotiation process.
8792 			 *
8793 			 * Note that if ill_capab_reneg is already B_TRUE
8794 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8795 			 * the capability resetting request has been sent
8796 			 * and the renegotiation has not been started yet;
8797 			 * nothing needs to be done in this case.
8798 			 */
8799 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8800 			ill_capability_reset(ill, B_TRUE);
8801 			ipsq_current_finish(ipsq);
8802 			break;
8803 		default:
8804 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8805 			    "type 0x%x for DL_NOTIFY_IND\n",
8806 			    notify->dl_notification));
8807 			break;
8808 		}
8809 
8810 		/*
8811 		 * As this is an asynchronous operation, we
8812 		 * should not call ill_dlpi_done
8813 		 */
8814 		break;
8815 	}
8816 	case DL_NOTIFY_ACK: {
8817 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8818 
8819 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8820 			ill->ill_note_link = 1;
8821 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8822 		break;
8823 	}
8824 	case DL_PHYS_ADDR_ACK: {
8825 		/*
8826 		 * As part of plumbing the interface via SIOCSLIFNAME,
8827 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8828 		 * whose answers we receive here.  As each answer is received,
8829 		 * we call ill_dlpi_done() to dispatch the next request as
8830 		 * we're processing the current one.  Once all answers have
8831 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8832 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8833 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8834 		 * available, but we know the ioctl is pending on ill_wq.)
8835 		 */
8836 		uint_t	paddrlen, paddroff;
8837 		uint8_t	*addr;
8838 
8839 		paddrreq = ill->ill_phys_addr_pend;
8840 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8841 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8842 		addr = mp->b_rptr + paddroff;
8843 
8844 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8845 		if (paddrreq == DL_IPV6_TOKEN) {
8846 			/*
8847 			 * bcopy to low-order bits of ill_token
8848 			 *
8849 			 * XXX Temporary hack - currently, all known tokens
8850 			 * are 64 bits, so I'll cheat for the moment.
8851 			 */
8852 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8853 			ill->ill_token_length = paddrlen;
8854 			break;
8855 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8856 			ASSERT(ill->ill_nd_lla_mp == NULL);
8857 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8858 			mp = NULL;
8859 			break;
8860 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8861 			ASSERT(ill->ill_dest_addr_mp == NULL);
8862 			ill->ill_dest_addr_mp = mp;
8863 			ill->ill_dest_addr = addr;
8864 			mp = NULL;
8865 			if (ill->ill_isv6) {
8866 				ill_setdesttoken(ill);
8867 				ipif_setdestlinklocal(ill->ill_ipif);
8868 			}
8869 			break;
8870 		}
8871 
8872 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8873 		ASSERT(ill->ill_phys_addr_mp == NULL);
8874 		if (!ill->ill_ifname_pending)
8875 			break;
8876 		ill->ill_ifname_pending = 0;
8877 		if (!ioctl_aborted)
8878 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8879 		if (mp1 != NULL) {
8880 			ASSERT(connp == NULL);
8881 			q = ill->ill_wq;
8882 		}
8883 		/*
8884 		 * If any error acks received during the plumbing sequence,
8885 		 * ill_ifname_pending_err will be set. Break out and send up
8886 		 * the error to the pending ioctl.
8887 		 */
8888 		if (ill->ill_ifname_pending_err != 0) {
8889 			err = ill->ill_ifname_pending_err;
8890 			ill->ill_ifname_pending_err = 0;
8891 			break;
8892 		}
8893 
8894 		ill->ill_phys_addr_mp = mp;
8895 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8896 		mp = NULL;
8897 
8898 		/*
8899 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8900 		 * provider doesn't support physical addresses.  We check both
8901 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8902 		 * not have physical addresses, but historically adversises a
8903 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8904 		 * its DL_PHYS_ADDR_ACK.
8905 		 */
8906 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8907 			ill->ill_phys_addr = NULL;
8908 		} else if (paddrlen != ill->ill_phys_addr_length) {
8909 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8910 			    paddrlen, ill->ill_phys_addr_length));
8911 			err = EINVAL;
8912 			break;
8913 		}
8914 
8915 		if (ill->ill_nd_lla_mp == NULL) {
8916 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8917 				err = ENOMEM;
8918 				break;
8919 			}
8920 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8921 		}
8922 
8923 		if (ill->ill_isv6) {
8924 			ill_setdefaulttoken(ill);
8925 			ipif_setlinklocal(ill->ill_ipif);
8926 		}
8927 		break;
8928 	}
8929 	case DL_OK_ACK:
8930 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8931 		    dl_primstr((int)dloa->dl_correct_primitive),
8932 		    dloa->dl_correct_primitive));
8933 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8934 		    char *, dl_primstr(dloa->dl_correct_primitive),
8935 		    ill_t *, ill);
8936 
8937 		switch (dloa->dl_correct_primitive) {
8938 		case DL_ENABMULTI_REQ:
8939 		case DL_DISABMULTI_REQ:
8940 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8941 			break;
8942 		case DL_PROMISCON_REQ:
8943 		case DL_PROMISCOFF_REQ:
8944 		case DL_UNBIND_REQ:
8945 		case DL_ATTACH_REQ:
8946 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8947 			break;
8948 		}
8949 		break;
8950 	default:
8951 		break;
8952 	}
8953 
8954 	freemsg(mp);
8955 	if (mp1 == NULL)
8956 		return;
8957 
8958 	/*
8959 	 * The operation must complete without EINPROGRESS since
8960 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8961 	 * the operation will be stuck forever inside the IPSQ.
8962 	 */
8963 	ASSERT(err != EINPROGRESS);
8964 
8965 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8966 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8967 	    ipif_t *, NULL);
8968 
8969 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8970 	case 0:
8971 		ipsq_current_finish(ipsq);
8972 		break;
8973 
8974 	case SIOCSLIFNAME:
8975 	case IF_UNITSEL: {
8976 		ill_t *ill_other = ILL_OTHER(ill);
8977 
8978 		/*
8979 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8980 		 * ill has a peer which is in an IPMP group, then place ill
8981 		 * into the same group.  One catch: although ifconfig plumbs
8982 		 * the appropriate IPMP meta-interface prior to plumbing this
8983 		 * ill, it is possible for multiple ifconfig applications to
8984 		 * race (or for another application to adjust plumbing), in
8985 		 * which case the IPMP meta-interface we need will be missing.
8986 		 * If so, kick the phyint out of the group.
8987 		 */
8988 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8989 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8990 			ipmp_illgrp_t	*illg;
8991 
8992 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8993 			if (illg == NULL)
8994 				ipmp_phyint_leave_grp(ill->ill_phyint);
8995 			else
8996 				ipmp_ill_join_illgrp(ill, illg);
8997 		}
8998 
8999 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
9000 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
9001 		else
9002 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
9003 		break;
9004 	}
9005 	case SIOCLIFADDIF:
9006 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
9007 		break;
9008 
9009 	default:
9010 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
9011 		break;
9012 	}
9013 }
9014 
9015 /*
9016  * ip_rput_other is called by ip_rput to handle messages modifying the global
9017  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
9018  */
9019 /* ARGSUSED */
9020 void
9021 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
9022 {
9023 	ill_t		*ill = q->q_ptr;
9024 	struct iocblk	*iocp;
9025 
9026 	ip1dbg(("ip_rput_other "));
9027 	if (ipsq != NULL) {
9028 		ASSERT(IAM_WRITER_IPSQ(ipsq));
9029 		ASSERT(ipsq->ipsq_xop ==
9030 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
9031 	}
9032 
9033 	switch (mp->b_datap->db_type) {
9034 	case M_ERROR:
9035 	case M_HANGUP:
9036 		/*
9037 		 * The device has a problem.  We force the ILL down.  It can
9038 		 * be brought up again manually using SIOCSIFFLAGS (via
9039 		 * ifconfig or equivalent).
9040 		 */
9041 		ASSERT(ipsq != NULL);
9042 		if (mp->b_rptr < mp->b_wptr)
9043 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
9044 		if (ill->ill_error == 0)
9045 			ill->ill_error = ENXIO;
9046 		if (!ill_down_start(q, mp))
9047 			return;
9048 		ipif_all_down_tail(ipsq, q, mp, NULL);
9049 		break;
9050 	case M_IOCNAK: {
9051 		iocp = (struct iocblk *)mp->b_rptr;
9052 
9053 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
9054 		/*
9055 		 * If this was the first attempt, turn off the fastpath
9056 		 * probing.
9057 		 */
9058 		mutex_enter(&ill->ill_lock);
9059 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
9060 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
9061 			mutex_exit(&ill->ill_lock);
9062 			/*
9063 			 * don't flush the nce_t entries: we use them
9064 			 * as an index to the ncec itself.
9065 			 */
9066 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
9067 			    ill->ill_name));
9068 		} else {
9069 			mutex_exit(&ill->ill_lock);
9070 		}
9071 		freemsg(mp);
9072 		break;
9073 	}
9074 	default:
9075 		ASSERT(0);
9076 		break;
9077 	}
9078 }
9079 
9080 /*
9081  * Update any source route, record route or timestamp options
9082  * When it fails it has consumed the message and BUMPed the MIB.
9083  */
9084 boolean_t
9085 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
9086     ip_recv_attr_t *ira)
9087 {
9088 	ipoptp_t	opts;
9089 	uchar_t		*opt;
9090 	uint8_t		optval;
9091 	uint8_t		optlen;
9092 	ipaddr_t	dst;
9093 	ipaddr_t	ifaddr;
9094 	uint32_t	ts;
9095 	timestruc_t	now;
9096 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9097 
9098 	ip2dbg(("ip_forward_options\n"));
9099 	dst = ipha->ipha_dst;
9100 	for (optval = ipoptp_first(&opts, ipha);
9101 	    optval != IPOPT_EOL;
9102 	    optval = ipoptp_next(&opts)) {
9103 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9104 		opt = opts.ipoptp_cur;
9105 		optlen = opts.ipoptp_len;
9106 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
9107 		    optval, opts.ipoptp_len));
9108 		switch (optval) {
9109 			uint32_t off;
9110 		case IPOPT_SSRR:
9111 		case IPOPT_LSRR:
9112 			/* Check if adminstratively disabled */
9113 			if (!ipst->ips_ip_forward_src_routed) {
9114 				BUMP_MIB(dst_ill->ill_ip_mib,
9115 				    ipIfStatsForwProhibits);
9116 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
9117 				    mp, dst_ill);
9118 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
9119 				    ira);
9120 				return (B_FALSE);
9121 			}
9122 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9123 				/*
9124 				 * Must be partial since ip_input_options
9125 				 * checked for strict.
9126 				 */
9127 				break;
9128 			}
9129 			off = opt[IPOPT_OFFSET];
9130 			off--;
9131 		redo_srr:
9132 			if (optlen < IP_ADDR_LEN ||
9133 			    off > optlen - IP_ADDR_LEN) {
9134 				/* End of source route */
9135 				ip1dbg((
9136 				    "ip_forward_options: end of SR\n"));
9137 				break;
9138 			}
9139 			/* Pick a reasonable address on the outbound if */
9140 			ASSERT(dst_ill != NULL);
9141 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9142 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9143 			    NULL) != 0) {
9144 				/* No source! Shouldn't happen */
9145 				ifaddr = INADDR_ANY;
9146 			}
9147 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9148 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9149 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
9150 			    ntohl(dst)));
9151 
9152 			/*
9153 			 * Check if our address is present more than
9154 			 * once as consecutive hops in source route.
9155 			 */
9156 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9157 				off += IP_ADDR_LEN;
9158 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9159 				goto redo_srr;
9160 			}
9161 			ipha->ipha_dst = dst;
9162 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9163 			break;
9164 		case IPOPT_RR:
9165 			off = opt[IPOPT_OFFSET];
9166 			off--;
9167 			if (optlen < IP_ADDR_LEN ||
9168 			    off > optlen - IP_ADDR_LEN) {
9169 				/* No more room - ignore */
9170 				ip1dbg((
9171 				    "ip_forward_options: end of RR\n"));
9172 				break;
9173 			}
9174 			/* Pick a reasonable address on the outbound if */
9175 			ASSERT(dst_ill != NULL);
9176 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9177 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9178 			    NULL) != 0) {
9179 				/* No source! Shouldn't happen */
9180 				ifaddr = INADDR_ANY;
9181 			}
9182 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9183 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9184 			break;
9185 		case IPOPT_TS:
9186 			/* Insert timestamp if there is room */
9187 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9188 			case IPOPT_TS_TSONLY:
9189 				off = IPOPT_TS_TIMELEN;
9190 				break;
9191 			case IPOPT_TS_PRESPEC:
9192 			case IPOPT_TS_PRESPEC_RFC791:
9193 				/* Verify that the address matched */
9194 				off = opt[IPOPT_OFFSET] - 1;
9195 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9196 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9197 					/* Not for us */
9198 					break;
9199 				}
9200 				/* FALLTHRU */
9201 			case IPOPT_TS_TSANDADDR:
9202 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9203 				break;
9204 			default:
9205 				/*
9206 				 * ip_*put_options should have already
9207 				 * dropped this packet.
9208 				 */
9209 				cmn_err(CE_PANIC, "ip_forward_options: "
9210 				    "unknown IT - bug in ip_input_options?\n");
9211 				return (B_TRUE);	/* Keep "lint" happy */
9212 			}
9213 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9214 				/* Increase overflow counter */
9215 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9216 				opt[IPOPT_POS_OV_FLG] =
9217 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9218 				    (off << 4));
9219 				break;
9220 			}
9221 			off = opt[IPOPT_OFFSET] - 1;
9222 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9223 			case IPOPT_TS_PRESPEC:
9224 			case IPOPT_TS_PRESPEC_RFC791:
9225 			case IPOPT_TS_TSANDADDR:
9226 				/* Pick a reasonable addr on the outbound if */
9227 				ASSERT(dst_ill != NULL);
9228 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9229 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9230 				    NULL, NULL) != 0) {
9231 					/* No source! Shouldn't happen */
9232 					ifaddr = INADDR_ANY;
9233 				}
9234 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9235 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9236 				/* FALLTHRU */
9237 			case IPOPT_TS_TSONLY:
9238 				off = opt[IPOPT_OFFSET] - 1;
9239 				/* Compute # of milliseconds since midnight */
9240 				gethrestime(&now);
9241 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9242 				    now.tv_nsec / (NANOSEC / MILLISEC);
9243 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9244 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9245 				break;
9246 			}
9247 			break;
9248 		}
9249 	}
9250 	return (B_TRUE);
9251 }
9252 
9253 /*
9254  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9255  * returns 'true' if there are still fragments left on the queue, in
9256  * which case we restart the timer.
9257  */
9258 void
9259 ill_frag_timer(void *arg)
9260 {
9261 	ill_t	*ill = (ill_t *)arg;
9262 	boolean_t frag_pending;
9263 	ip_stack_t	*ipst = ill->ill_ipst;
9264 	time_t	timeout;
9265 
9266 	mutex_enter(&ill->ill_lock);
9267 	ASSERT(!ill->ill_fragtimer_executing);
9268 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9269 		ill->ill_frag_timer_id = 0;
9270 		mutex_exit(&ill->ill_lock);
9271 		return;
9272 	}
9273 	ill->ill_fragtimer_executing = 1;
9274 	mutex_exit(&ill->ill_lock);
9275 
9276 	if (ill->ill_isv6)
9277 		timeout = ipst->ips_ipv6_frag_timeout;
9278 	else
9279 		timeout = ipst->ips_ip_g_frag_timeout;
9280 
9281 	frag_pending = ill_frag_timeout(ill, timeout);
9282 
9283 	/*
9284 	 * Restart the timer, if we have fragments pending or if someone
9285 	 * wanted us to be scheduled again.
9286 	 */
9287 	mutex_enter(&ill->ill_lock);
9288 	ill->ill_fragtimer_executing = 0;
9289 	ill->ill_frag_timer_id = 0;
9290 	if (frag_pending || ill->ill_fragtimer_needrestart)
9291 		ill_frag_timer_start(ill);
9292 	mutex_exit(&ill->ill_lock);
9293 }
9294 
9295 void
9296 ill_frag_timer_start(ill_t *ill)
9297 {
9298 	ip_stack_t	*ipst = ill->ill_ipst;
9299 	clock_t	timeo_ms;
9300 
9301 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9302 
9303 	/* If the ill is closing or opening don't proceed */
9304 	if (ill->ill_state_flags & ILL_CONDEMNED)
9305 		return;
9306 
9307 	if (ill->ill_fragtimer_executing) {
9308 		/*
9309 		 * ill_frag_timer is currently executing. Just record the
9310 		 * the fact that we want the timer to be restarted.
9311 		 * ill_frag_timer will post a timeout before it returns,
9312 		 * ensuring it will be called again.
9313 		 */
9314 		ill->ill_fragtimer_needrestart = 1;
9315 		return;
9316 	}
9317 
9318 	if (ill->ill_frag_timer_id == 0) {
9319 		if (ill->ill_isv6)
9320 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
9321 		else
9322 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
9323 		/*
9324 		 * The timer is neither running nor is the timeout handler
9325 		 * executing. Post a timeout so that ill_frag_timer will be
9326 		 * called
9327 		 */
9328 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9329 		    MSEC_TO_TICK(timeo_ms >> 1));
9330 		ill->ill_fragtimer_needrestart = 0;
9331 	}
9332 }
9333 
9334 /*
9335  * Update any source route, record route or timestamp options.
9336  * Check that we are at end of strict source route.
9337  * The options have already been checked for sanity in ip_input_options().
9338  */
9339 boolean_t
9340 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9341 {
9342 	ipoptp_t	opts;
9343 	uchar_t		*opt;
9344 	uint8_t		optval;
9345 	uint8_t		optlen;
9346 	ipaddr_t	dst;
9347 	ipaddr_t	ifaddr;
9348 	uint32_t	ts;
9349 	timestruc_t	now;
9350 	ill_t		*ill = ira->ira_ill;
9351 	ip_stack_t	*ipst = ill->ill_ipst;
9352 
9353 	ip2dbg(("ip_input_local_options\n"));
9354 
9355 	for (optval = ipoptp_first(&opts, ipha);
9356 	    optval != IPOPT_EOL;
9357 	    optval = ipoptp_next(&opts)) {
9358 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9359 		opt = opts.ipoptp_cur;
9360 		optlen = opts.ipoptp_len;
9361 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9362 		    optval, optlen));
9363 		switch (optval) {
9364 			uint32_t off;
9365 		case IPOPT_SSRR:
9366 		case IPOPT_LSRR:
9367 			off = opt[IPOPT_OFFSET];
9368 			off--;
9369 			if (optlen < IP_ADDR_LEN ||
9370 			    off > optlen - IP_ADDR_LEN) {
9371 				/* End of source route */
9372 				ip1dbg(("ip_input_local_options: end of SR\n"));
9373 				break;
9374 			}
9375 			/*
9376 			 * This will only happen if two consecutive entries
9377 			 * in the source route contains our address or if
9378 			 * it is a packet with a loose source route which
9379 			 * reaches us before consuming the whole source route
9380 			 */
9381 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9382 			if (optval == IPOPT_SSRR) {
9383 				goto bad_src_route;
9384 			}
9385 			/*
9386 			 * Hack: instead of dropping the packet truncate the
9387 			 * source route to what has been used by filling the
9388 			 * rest with IPOPT_NOP.
9389 			 */
9390 			opt[IPOPT_OLEN] = (uint8_t)off;
9391 			while (off < optlen) {
9392 				opt[off++] = IPOPT_NOP;
9393 			}
9394 			break;
9395 		case IPOPT_RR:
9396 			off = opt[IPOPT_OFFSET];
9397 			off--;
9398 			if (optlen < IP_ADDR_LEN ||
9399 			    off > optlen - IP_ADDR_LEN) {
9400 				/* No more room - ignore */
9401 				ip1dbg((
9402 				    "ip_input_local_options: end of RR\n"));
9403 				break;
9404 			}
9405 			/* Pick a reasonable address on the outbound if */
9406 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9407 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9408 			    NULL) != 0) {
9409 				/* No source! Shouldn't happen */
9410 				ifaddr = INADDR_ANY;
9411 			}
9412 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9413 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9414 			break;
9415 		case IPOPT_TS:
9416 			/* Insert timestamp if there is romm */
9417 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9418 			case IPOPT_TS_TSONLY:
9419 				off = IPOPT_TS_TIMELEN;
9420 				break;
9421 			case IPOPT_TS_PRESPEC:
9422 			case IPOPT_TS_PRESPEC_RFC791:
9423 				/* Verify that the address matched */
9424 				off = opt[IPOPT_OFFSET] - 1;
9425 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9426 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9427 					/* Not for us */
9428 					break;
9429 				}
9430 				/* FALLTHRU */
9431 			case IPOPT_TS_TSANDADDR:
9432 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9433 				break;
9434 			default:
9435 				/*
9436 				 * ip_*put_options should have already
9437 				 * dropped this packet.
9438 				 */
9439 				cmn_err(CE_PANIC, "ip_input_local_options: "
9440 				    "unknown IT - bug in ip_input_options?\n");
9441 				return (B_TRUE);	/* Keep "lint" happy */
9442 			}
9443 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9444 				/* Increase overflow counter */
9445 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9446 				opt[IPOPT_POS_OV_FLG] =
9447 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9448 				    (off << 4));
9449 				break;
9450 			}
9451 			off = opt[IPOPT_OFFSET] - 1;
9452 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9453 			case IPOPT_TS_PRESPEC:
9454 			case IPOPT_TS_PRESPEC_RFC791:
9455 			case IPOPT_TS_TSANDADDR:
9456 				/* Pick a reasonable addr on the outbound if */
9457 				if (ip_select_source_v4(ill, INADDR_ANY,
9458 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9459 				    &ifaddr, NULL, NULL) != 0) {
9460 					/* No source! Shouldn't happen */
9461 					ifaddr = INADDR_ANY;
9462 				}
9463 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9464 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9465 				/* FALLTHRU */
9466 			case IPOPT_TS_TSONLY:
9467 				off = opt[IPOPT_OFFSET] - 1;
9468 				/* Compute # of milliseconds since midnight */
9469 				gethrestime(&now);
9470 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9471 				    now.tv_nsec / (NANOSEC / MILLISEC);
9472 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9473 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9474 				break;
9475 			}
9476 			break;
9477 		}
9478 	}
9479 	return (B_TRUE);
9480 
9481 bad_src_route:
9482 	/* make sure we clear any indication of a hardware checksum */
9483 	DB_CKSUMFLAGS(mp) = 0;
9484 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9485 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9486 	return (B_FALSE);
9487 
9488 }
9489 
9490 /*
9491  * Process IP options in an inbound packet.  Always returns the nexthop.
9492  * Normally this is the passed in nexthop, but if there is an option
9493  * that effects the nexthop (such as a source route) that will be returned.
9494  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9495  * and mp freed.
9496  */
9497 ipaddr_t
9498 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9499     ip_recv_attr_t *ira, int *errorp)
9500 {
9501 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9502 	ipoptp_t	opts;
9503 	uchar_t		*opt;
9504 	uint8_t		optval;
9505 	uint8_t		optlen;
9506 	intptr_t	code = 0;
9507 	ire_t		*ire;
9508 
9509 	ip2dbg(("ip_input_options\n"));
9510 	*errorp = 0;
9511 	for (optval = ipoptp_first(&opts, ipha);
9512 	    optval != IPOPT_EOL;
9513 	    optval = ipoptp_next(&opts)) {
9514 		opt = opts.ipoptp_cur;
9515 		optlen = opts.ipoptp_len;
9516 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9517 		    optval, optlen));
9518 		/*
9519 		 * Note: we need to verify the checksum before we
9520 		 * modify anything thus this routine only extracts the next
9521 		 * hop dst from any source route.
9522 		 */
9523 		switch (optval) {
9524 			uint32_t off;
9525 		case IPOPT_SSRR:
9526 		case IPOPT_LSRR:
9527 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9528 				if (optval == IPOPT_SSRR) {
9529 					ip1dbg(("ip_input_options: not next"
9530 					    " strict source route 0x%x\n",
9531 					    ntohl(dst)));
9532 					code = (char *)&ipha->ipha_dst -
9533 					    (char *)ipha;
9534 					goto param_prob; /* RouterReq's */
9535 				}
9536 				ip2dbg(("ip_input_options: "
9537 				    "not next source route 0x%x\n",
9538 				    ntohl(dst)));
9539 				break;
9540 			}
9541 
9542 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9543 				ip1dbg((
9544 				    "ip_input_options: bad option offset\n"));
9545 				code = (char *)&opt[IPOPT_OLEN] -
9546 				    (char *)ipha;
9547 				goto param_prob;
9548 			}
9549 			off = opt[IPOPT_OFFSET];
9550 			off--;
9551 		redo_srr:
9552 			if (optlen < IP_ADDR_LEN ||
9553 			    off > optlen - IP_ADDR_LEN) {
9554 				/* End of source route */
9555 				ip1dbg(("ip_input_options: end of SR\n"));
9556 				break;
9557 			}
9558 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9559 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9560 			    ntohl(dst)));
9561 
9562 			/*
9563 			 * Check if our address is present more than
9564 			 * once as consecutive hops in source route.
9565 			 * XXX verify per-interface ip_forwarding
9566 			 * for source route?
9567 			 */
9568 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9569 				off += IP_ADDR_LEN;
9570 				goto redo_srr;
9571 			}
9572 
9573 			if (dst == htonl(INADDR_LOOPBACK)) {
9574 				ip1dbg(("ip_input_options: loopback addr in "
9575 				    "source route!\n"));
9576 				goto bad_src_route;
9577 			}
9578 			/*
9579 			 * For strict: verify that dst is directly
9580 			 * reachable.
9581 			 */
9582 			if (optval == IPOPT_SSRR) {
9583 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9584 				    IRE_IF_ALL, NULL, ALL_ZONES,
9585 				    ira->ira_tsl,
9586 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9587 				    NULL);
9588 				if (ire == NULL) {
9589 					ip1dbg(("ip_input_options: SSRR not "
9590 					    "directly reachable: 0x%x\n",
9591 					    ntohl(dst)));
9592 					goto bad_src_route;
9593 				}
9594 				ire_refrele(ire);
9595 			}
9596 			/*
9597 			 * Defer update of the offset and the record route
9598 			 * until the packet is forwarded.
9599 			 */
9600 			break;
9601 		case IPOPT_RR:
9602 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9603 				ip1dbg((
9604 				    "ip_input_options: bad option offset\n"));
9605 				code = (char *)&opt[IPOPT_OLEN] -
9606 				    (char *)ipha;
9607 				goto param_prob;
9608 			}
9609 			break;
9610 		case IPOPT_TS:
9611 			/*
9612 			 * Verify that length >= 5 and that there is either
9613 			 * room for another timestamp or that the overflow
9614 			 * counter is not maxed out.
9615 			 */
9616 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9617 			if (optlen < IPOPT_MINLEN_IT) {
9618 				goto param_prob;
9619 			}
9620 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9621 				ip1dbg((
9622 				    "ip_input_options: bad option offset\n"));
9623 				code = (char *)&opt[IPOPT_OFFSET] -
9624 				    (char *)ipha;
9625 				goto param_prob;
9626 			}
9627 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9628 			case IPOPT_TS_TSONLY:
9629 				off = IPOPT_TS_TIMELEN;
9630 				break;
9631 			case IPOPT_TS_TSANDADDR:
9632 			case IPOPT_TS_PRESPEC:
9633 			case IPOPT_TS_PRESPEC_RFC791:
9634 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9635 				break;
9636 			default:
9637 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9638 				    (char *)ipha;
9639 				goto param_prob;
9640 			}
9641 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9642 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9643 				/*
9644 				 * No room and the overflow counter is 15
9645 				 * already.
9646 				 */
9647 				goto param_prob;
9648 			}
9649 			break;
9650 		}
9651 	}
9652 
9653 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9654 		return (dst);
9655 	}
9656 
9657 	ip1dbg(("ip_input_options: error processing IP options."));
9658 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9659 
9660 param_prob:
9661 	/* make sure we clear any indication of a hardware checksum */
9662 	DB_CKSUMFLAGS(mp) = 0;
9663 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9664 	icmp_param_problem(mp, (uint8_t)code, ira);
9665 	*errorp = -1;
9666 	return (dst);
9667 
9668 bad_src_route:
9669 	/* make sure we clear any indication of a hardware checksum */
9670 	DB_CKSUMFLAGS(mp) = 0;
9671 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9672 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9673 	*errorp = -1;
9674 	return (dst);
9675 }
9676 
9677 /*
9678  * IP & ICMP info in >=14 msg's ...
9679  *  - ip fixed part (mib2_ip_t)
9680  *  - icmp fixed part (mib2_icmp_t)
9681  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9682  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9683  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9684  *  - ipRouteAttributeTable (ip 102)	labeled routes
9685  *  - ip multicast membership (ip_member_t)
9686  *  - ip multicast source filtering (ip_grpsrc_t)
9687  *  - igmp fixed part (struct igmpstat)
9688  *  - multicast routing stats (struct mrtstat)
9689  *  - multicast routing vifs (array of struct vifctl)
9690  *  - multicast routing routes (array of struct mfcctl)
9691  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9692  *					One per ill plus one generic
9693  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9694  *					One per ill plus one generic
9695  *  - ipv6RouteEntry			all IPv6 IREs
9696  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9697  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9698  *  - ipv6AddrEntry			all IPv6 ipifs
9699  *  - ipv6 multicast membership (ipv6_member_t)
9700  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9701  *
9702  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9703  * already filled in by the caller.
9704  * Return value of 0 indicates that no messages were sent and caller
9705  * should free mpctl.
9706  */
9707 int
9708 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
9709 {
9710 	ip_stack_t *ipst;
9711 	sctp_stack_t *sctps;
9712 
9713 	if (q->q_next != NULL) {
9714 		ipst = ILLQ_TO_IPST(q);
9715 	} else {
9716 		ipst = CONNQ_TO_IPST(q);
9717 	}
9718 	ASSERT(ipst != NULL);
9719 	sctps = ipst->ips_netstack->netstack_sctp;
9720 
9721 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9722 		return (0);
9723 	}
9724 
9725 	/*
9726 	 * For the purposes of the (broken) packet shell use
9727 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9728 	 * to make TCP and UDP appear first in the list of mib items.
9729 	 * TBD: We could expand this and use it in netstat so that
9730 	 * the kernel doesn't have to produce large tables (connections,
9731 	 * routes, etc) when netstat only wants the statistics or a particular
9732 	 * table.
9733 	 */
9734 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9735 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9736 			return (1);
9737 		}
9738 	}
9739 
9740 	if (level != MIB2_TCP) {
9741 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
9742 			return (1);
9743 		}
9744 	}
9745 
9746 	if (level != MIB2_UDP) {
9747 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
9748 			return (1);
9749 		}
9750 	}
9751 
9752 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9753 	    ipst)) == NULL) {
9754 		return (1);
9755 	}
9756 
9757 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
9758 		return (1);
9759 	}
9760 
9761 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9762 		return (1);
9763 	}
9764 
9765 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9766 		return (1);
9767 	}
9768 
9769 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9770 		return (1);
9771 	}
9772 
9773 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9774 		return (1);
9775 	}
9776 
9777 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
9778 		return (1);
9779 	}
9780 
9781 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
9782 		return (1);
9783 	}
9784 
9785 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9786 		return (1);
9787 	}
9788 
9789 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9790 		return (1);
9791 	}
9792 
9793 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9794 		return (1);
9795 	}
9796 
9797 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9798 		return (1);
9799 	}
9800 
9801 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9802 		return (1);
9803 	}
9804 
9805 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9806 		return (1);
9807 	}
9808 
9809 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9810 	if (mpctl == NULL)
9811 		return (1);
9812 
9813 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9814 	if (mpctl == NULL)
9815 		return (1);
9816 
9817 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9818 		return (1);
9819 	}
9820 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9821 		return (1);
9822 	}
9823 	freemsg(mpctl);
9824 	return (1);
9825 }
9826 
9827 /* Get global (legacy) IPv4 statistics */
9828 static mblk_t *
9829 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9830     ip_stack_t *ipst)
9831 {
9832 	mib2_ip_t		old_ip_mib;
9833 	struct opthdr		*optp;
9834 	mblk_t			*mp2ctl;
9835 
9836 	/*
9837 	 * make a copy of the original message
9838 	 */
9839 	mp2ctl = copymsg(mpctl);
9840 
9841 	/* fixed length IP structure... */
9842 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9843 	optp->level = MIB2_IP;
9844 	optp->name = 0;
9845 	SET_MIB(old_ip_mib.ipForwarding,
9846 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9847 	SET_MIB(old_ip_mib.ipDefaultTTL,
9848 	    (uint32_t)ipst->ips_ip_def_ttl);
9849 	SET_MIB(old_ip_mib.ipReasmTimeout,
9850 	    ipst->ips_ip_g_frag_timeout);
9851 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9852 	    sizeof (mib2_ipAddrEntry_t));
9853 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9854 	    sizeof (mib2_ipRouteEntry_t));
9855 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9856 	    sizeof (mib2_ipNetToMediaEntry_t));
9857 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9858 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9859 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9860 	    sizeof (mib2_ipAttributeEntry_t));
9861 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9862 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9863 
9864 	/*
9865 	 * Grab the statistics from the new IP MIB
9866 	 */
9867 	SET_MIB(old_ip_mib.ipInReceives,
9868 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9869 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9870 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9871 	SET_MIB(old_ip_mib.ipForwDatagrams,
9872 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9873 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9874 	    ipmib->ipIfStatsInUnknownProtos);
9875 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9876 	SET_MIB(old_ip_mib.ipInDelivers,
9877 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9878 	SET_MIB(old_ip_mib.ipOutRequests,
9879 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9880 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9881 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9882 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9883 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9884 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9885 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9886 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9887 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9888 
9889 	/* ipRoutingDiscards is not being used */
9890 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9891 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9892 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9893 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9894 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9895 	    ipmib->ipIfStatsReasmDuplicates);
9896 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9897 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9898 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9899 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9900 	SET_MIB(old_ip_mib.rawipInOverflows,
9901 	    ipmib->rawipIfStatsInOverflows);
9902 
9903 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9904 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9905 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9906 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9907 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9908 	    ipmib->ipIfStatsOutSwitchIPVersion);
9909 
9910 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9911 	    (int)sizeof (old_ip_mib))) {
9912 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9913 		    (uint_t)sizeof (old_ip_mib)));
9914 	}
9915 
9916 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9917 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9918 	    (int)optp->level, (int)optp->name, (int)optp->len));
9919 	qreply(q, mpctl);
9920 	return (mp2ctl);
9921 }
9922 
9923 /* Per interface IPv4 statistics */
9924 static mblk_t *
9925 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9926 {
9927 	struct opthdr		*optp;
9928 	mblk_t			*mp2ctl;
9929 	ill_t			*ill;
9930 	ill_walk_context_t	ctx;
9931 	mblk_t			*mp_tail = NULL;
9932 	mib2_ipIfStatsEntry_t	global_ip_mib;
9933 
9934 	/*
9935 	 * Make a copy of the original message
9936 	 */
9937 	mp2ctl = copymsg(mpctl);
9938 
9939 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9940 	optp->level = MIB2_IP;
9941 	optp->name = MIB2_IP_TRAFFIC_STATS;
9942 	/* Include "unknown interface" ip_mib */
9943 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9944 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9945 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9946 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9947 	    (ipst->ips_ip_g_forward ? 1 : 2));
9948 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9949 	    (uint32_t)ipst->ips_ip_def_ttl);
9950 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9951 	    sizeof (mib2_ipIfStatsEntry_t));
9952 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9953 	    sizeof (mib2_ipAddrEntry_t));
9954 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9955 	    sizeof (mib2_ipRouteEntry_t));
9956 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9957 	    sizeof (mib2_ipNetToMediaEntry_t));
9958 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9959 	    sizeof (ip_member_t));
9960 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9961 	    sizeof (ip_grpsrc_t));
9962 
9963 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9964 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
9965 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9966 		    "failed to allocate %u bytes\n",
9967 		    (uint_t)sizeof (ipst->ips_ip_mib)));
9968 	}
9969 
9970 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9971 
9972 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9973 	ill = ILL_START_WALK_V4(&ctx, ipst);
9974 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9975 		ill->ill_ip_mib->ipIfStatsIfIndex =
9976 		    ill->ill_phyint->phyint_ifindex;
9977 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9978 		    (ipst->ips_ip_g_forward ? 1 : 2));
9979 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9980 		    (uint32_t)ipst->ips_ip_def_ttl);
9981 
9982 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9983 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9984 		    (char *)ill->ill_ip_mib,
9985 		    (int)sizeof (*ill->ill_ip_mib))) {
9986 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9987 			    "failed to allocate %u bytes\n",
9988 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9989 		}
9990 	}
9991 	rw_exit(&ipst->ips_ill_g_lock);
9992 
9993 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9994 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9995 	    "level %d, name %d, len %d\n",
9996 	    (int)optp->level, (int)optp->name, (int)optp->len));
9997 	qreply(q, mpctl);
9998 
9999 	if (mp2ctl == NULL)
10000 		return (NULL);
10001 
10002 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
10003 }
10004 
10005 /* Global IPv4 ICMP statistics */
10006 static mblk_t *
10007 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10008 {
10009 	struct opthdr		*optp;
10010 	mblk_t			*mp2ctl;
10011 
10012 	/*
10013 	 * Make a copy of the original message
10014 	 */
10015 	mp2ctl = copymsg(mpctl);
10016 
10017 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10018 	optp->level = MIB2_ICMP;
10019 	optp->name = 0;
10020 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
10021 	    (int)sizeof (ipst->ips_icmp_mib))) {
10022 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
10023 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
10024 	}
10025 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10026 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
10027 	    (int)optp->level, (int)optp->name, (int)optp->len));
10028 	qreply(q, mpctl);
10029 	return (mp2ctl);
10030 }
10031 
10032 /* Global IPv4 IGMP statistics */
10033 static mblk_t *
10034 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10035 {
10036 	struct opthdr		*optp;
10037 	mblk_t			*mp2ctl;
10038 
10039 	/*
10040 	 * make a copy of the original message
10041 	 */
10042 	mp2ctl = copymsg(mpctl);
10043 
10044 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10045 	optp->level = EXPER_IGMP;
10046 	optp->name = 0;
10047 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
10048 	    (int)sizeof (ipst->ips_igmpstat))) {
10049 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
10050 		    (uint_t)sizeof (ipst->ips_igmpstat)));
10051 	}
10052 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10053 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
10054 	    (int)optp->level, (int)optp->name, (int)optp->len));
10055 	qreply(q, mpctl);
10056 	return (mp2ctl);
10057 }
10058 
10059 /* Global IPv4 Multicast Routing statistics */
10060 static mblk_t *
10061 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10062 {
10063 	struct opthdr		*optp;
10064 	mblk_t			*mp2ctl;
10065 
10066 	/*
10067 	 * make a copy of the original message
10068 	 */
10069 	mp2ctl = copymsg(mpctl);
10070 
10071 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10072 	optp->level = EXPER_DVMRP;
10073 	optp->name = 0;
10074 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
10075 		ip0dbg(("ip_mroute_stats: failed\n"));
10076 	}
10077 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10078 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
10079 	    (int)optp->level, (int)optp->name, (int)optp->len));
10080 	qreply(q, mpctl);
10081 	return (mp2ctl);
10082 }
10083 
10084 /* IPv4 address information */
10085 static mblk_t *
10086 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10087 {
10088 	struct opthdr		*optp;
10089 	mblk_t			*mp2ctl;
10090 	mblk_t			*mp_tail = NULL;
10091 	ill_t			*ill;
10092 	ipif_t			*ipif;
10093 	uint_t			bitval;
10094 	mib2_ipAddrEntry_t	mae;
10095 	zoneid_t		zoneid;
10096 	ill_walk_context_t ctx;
10097 
10098 	/*
10099 	 * make a copy of the original message
10100 	 */
10101 	mp2ctl = copymsg(mpctl);
10102 
10103 	/* ipAddrEntryTable */
10104 
10105 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10106 	optp->level = MIB2_IP;
10107 	optp->name = MIB2_IP_ADDR;
10108 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10109 
10110 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10111 	ill = ILL_START_WALK_V4(&ctx, ipst);
10112 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10113 		for (ipif = ill->ill_ipif; ipif != NULL;
10114 		    ipif = ipif->ipif_next) {
10115 			if (ipif->ipif_zoneid != zoneid &&
10116 			    ipif->ipif_zoneid != ALL_ZONES)
10117 				continue;
10118 			/* Sum of count from dead IRE_LO* and our current */
10119 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10120 			if (ipif->ipif_ire_local != NULL) {
10121 				mae.ipAdEntInfo.ae_ibcnt +=
10122 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10123 			}
10124 			mae.ipAdEntInfo.ae_obcnt = 0;
10125 			mae.ipAdEntInfo.ae_focnt = 0;
10126 
10127 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
10128 			    OCTET_LENGTH);
10129 			mae.ipAdEntIfIndex.o_length =
10130 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
10131 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
10132 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
10133 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
10134 			mae.ipAdEntInfo.ae_subnet_len =
10135 			    ip_mask_to_plen(ipif->ipif_net_mask);
10136 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
10137 			for (bitval = 1;
10138 			    bitval &&
10139 			    !(bitval & ipif->ipif_brd_addr);
10140 			    bitval <<= 1)
10141 				noop;
10142 			mae.ipAdEntBcastAddr = bitval;
10143 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10144 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10145 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
10146 			mae.ipAdEntInfo.ae_broadcast_addr =
10147 			    ipif->ipif_brd_addr;
10148 			mae.ipAdEntInfo.ae_pp_dst_addr =
10149 			    ipif->ipif_pp_dst_addr;
10150 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10151 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10152 			mae.ipAdEntRetransmitTime =
10153 			    ill->ill_reachable_retrans_time;
10154 
10155 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10156 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
10157 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10158 				    "allocate %u bytes\n",
10159 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
10160 			}
10161 		}
10162 	}
10163 	rw_exit(&ipst->ips_ill_g_lock);
10164 
10165 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10166 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10167 	    (int)optp->level, (int)optp->name, (int)optp->len));
10168 	qreply(q, mpctl);
10169 	return (mp2ctl);
10170 }
10171 
10172 /* IPv6 address information */
10173 static mblk_t *
10174 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10175 {
10176 	struct opthdr		*optp;
10177 	mblk_t			*mp2ctl;
10178 	mblk_t			*mp_tail = NULL;
10179 	ill_t			*ill;
10180 	ipif_t			*ipif;
10181 	mib2_ipv6AddrEntry_t	mae6;
10182 	zoneid_t		zoneid;
10183 	ill_walk_context_t	ctx;
10184 
10185 	/*
10186 	 * make a copy of the original message
10187 	 */
10188 	mp2ctl = copymsg(mpctl);
10189 
10190 	/* ipv6AddrEntryTable */
10191 
10192 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10193 	optp->level = MIB2_IP6;
10194 	optp->name = MIB2_IP6_ADDR;
10195 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10196 
10197 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10198 	ill = ILL_START_WALK_V6(&ctx, ipst);
10199 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10200 		for (ipif = ill->ill_ipif; ipif != NULL;
10201 		    ipif = ipif->ipif_next) {
10202 			if (ipif->ipif_zoneid != zoneid &&
10203 			    ipif->ipif_zoneid != ALL_ZONES)
10204 				continue;
10205 			/* Sum of count from dead IRE_LO* and our current */
10206 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10207 			if (ipif->ipif_ire_local != NULL) {
10208 				mae6.ipv6AddrInfo.ae_ibcnt +=
10209 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10210 			}
10211 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10212 			mae6.ipv6AddrInfo.ae_focnt = 0;
10213 
10214 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10215 			    OCTET_LENGTH);
10216 			mae6.ipv6AddrIfIndex.o_length =
10217 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10218 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10219 			mae6.ipv6AddrPfxLength =
10220 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10221 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10222 			mae6.ipv6AddrInfo.ae_subnet_len =
10223 			    mae6.ipv6AddrPfxLength;
10224 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10225 
10226 			/* Type: stateless(1), stateful(2), unknown(3) */
10227 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10228 				mae6.ipv6AddrType = 1;
10229 			else
10230 				mae6.ipv6AddrType = 2;
10231 			/* Anycast: true(1), false(2) */
10232 			if (ipif->ipif_flags & IPIF_ANYCAST)
10233 				mae6.ipv6AddrAnycastFlag = 1;
10234 			else
10235 				mae6.ipv6AddrAnycastFlag = 2;
10236 
10237 			/*
10238 			 * Address status: preferred(1), deprecated(2),
10239 			 * invalid(3), inaccessible(4), unknown(5)
10240 			 */
10241 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10242 				mae6.ipv6AddrStatus = 3;
10243 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10244 				mae6.ipv6AddrStatus = 2;
10245 			else
10246 				mae6.ipv6AddrStatus = 1;
10247 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10248 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
10249 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10250 			    ipif->ipif_v6pp_dst_addr;
10251 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10252 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10253 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10254 			mae6.ipv6AddrIdentifier = ill->ill_token;
10255 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10256 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10257 			mae6.ipv6AddrRetransmitTime =
10258 			    ill->ill_reachable_retrans_time;
10259 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10260 			    (char *)&mae6,
10261 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
10262 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10263 				    "allocate %u bytes\n",
10264 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
10265 			}
10266 		}
10267 	}
10268 	rw_exit(&ipst->ips_ill_g_lock);
10269 
10270 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10271 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10272 	    (int)optp->level, (int)optp->name, (int)optp->len));
10273 	qreply(q, mpctl);
10274 	return (mp2ctl);
10275 }
10276 
10277 /* IPv4 multicast group membership. */
10278 static mblk_t *
10279 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10280 {
10281 	struct opthdr		*optp;
10282 	mblk_t			*mp2ctl;
10283 	ill_t			*ill;
10284 	ipif_t			*ipif;
10285 	ilm_t			*ilm;
10286 	ip_member_t		ipm;
10287 	mblk_t			*mp_tail = NULL;
10288 	ill_walk_context_t	ctx;
10289 	zoneid_t		zoneid;
10290 
10291 	/*
10292 	 * make a copy of the original message
10293 	 */
10294 	mp2ctl = copymsg(mpctl);
10295 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10296 
10297 	/* ipGroupMember table */
10298 	optp = (struct opthdr *)&mpctl->b_rptr[
10299 	    sizeof (struct T_optmgmt_ack)];
10300 	optp->level = MIB2_IP;
10301 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10302 
10303 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10304 	ill = ILL_START_WALK_V4(&ctx, ipst);
10305 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10306 		/* Make sure the ill isn't going away. */
10307 		if (!ill_check_and_refhold(ill))
10308 			continue;
10309 		rw_exit(&ipst->ips_ill_g_lock);
10310 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10311 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10312 			if (ilm->ilm_zoneid != zoneid &&
10313 			    ilm->ilm_zoneid != ALL_ZONES)
10314 				continue;
10315 
10316 			/* Is there an ipif for ilm_ifaddr? */
10317 			for (ipif = ill->ill_ipif; ipif != NULL;
10318 			    ipif = ipif->ipif_next) {
10319 				if (!IPIF_IS_CONDEMNED(ipif) &&
10320 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10321 				    ilm->ilm_ifaddr != INADDR_ANY)
10322 					break;
10323 			}
10324 			if (ipif != NULL) {
10325 				ipif_get_name(ipif,
10326 				    ipm.ipGroupMemberIfIndex.o_bytes,
10327 				    OCTET_LENGTH);
10328 			} else {
10329 				ill_get_name(ill,
10330 				    ipm.ipGroupMemberIfIndex.o_bytes,
10331 				    OCTET_LENGTH);
10332 			}
10333 			ipm.ipGroupMemberIfIndex.o_length =
10334 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10335 
10336 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10337 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10338 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10339 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10340 			    (char *)&ipm, (int)sizeof (ipm))) {
10341 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10342 				    "failed to allocate %u bytes\n",
10343 				    (uint_t)sizeof (ipm)));
10344 			}
10345 		}
10346 		rw_exit(&ill->ill_mcast_lock);
10347 		ill_refrele(ill);
10348 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10349 	}
10350 	rw_exit(&ipst->ips_ill_g_lock);
10351 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10352 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10353 	    (int)optp->level, (int)optp->name, (int)optp->len));
10354 	qreply(q, mpctl);
10355 	return (mp2ctl);
10356 }
10357 
10358 /* IPv6 multicast group membership. */
10359 static mblk_t *
10360 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10361 {
10362 	struct opthdr		*optp;
10363 	mblk_t			*mp2ctl;
10364 	ill_t			*ill;
10365 	ilm_t			*ilm;
10366 	ipv6_member_t		ipm6;
10367 	mblk_t			*mp_tail = NULL;
10368 	ill_walk_context_t	ctx;
10369 	zoneid_t		zoneid;
10370 
10371 	/*
10372 	 * make a copy of the original message
10373 	 */
10374 	mp2ctl = copymsg(mpctl);
10375 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10376 
10377 	/* ip6GroupMember table */
10378 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10379 	optp->level = MIB2_IP6;
10380 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10381 
10382 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10383 	ill = ILL_START_WALK_V6(&ctx, ipst);
10384 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10385 		/* Make sure the ill isn't going away. */
10386 		if (!ill_check_and_refhold(ill))
10387 			continue;
10388 		rw_exit(&ipst->ips_ill_g_lock);
10389 		/*
10390 		 * Normally we don't have any members on under IPMP interfaces.
10391 		 * We report them as a debugging aid.
10392 		 */
10393 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10394 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10395 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10396 			if (ilm->ilm_zoneid != zoneid &&
10397 			    ilm->ilm_zoneid != ALL_ZONES)
10398 				continue;	/* not this zone */
10399 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10400 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10401 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10402 			if (!snmp_append_data2(mpctl->b_cont,
10403 			    &mp_tail,
10404 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10405 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10406 				    "failed to allocate %u bytes\n",
10407 				    (uint_t)sizeof (ipm6)));
10408 			}
10409 		}
10410 		rw_exit(&ill->ill_mcast_lock);
10411 		ill_refrele(ill);
10412 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10413 	}
10414 	rw_exit(&ipst->ips_ill_g_lock);
10415 
10416 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10417 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10418 	    (int)optp->level, (int)optp->name, (int)optp->len));
10419 	qreply(q, mpctl);
10420 	return (mp2ctl);
10421 }
10422 
10423 /* IP multicast filtered sources */
10424 static mblk_t *
10425 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10426 {
10427 	struct opthdr		*optp;
10428 	mblk_t			*mp2ctl;
10429 	ill_t			*ill;
10430 	ipif_t			*ipif;
10431 	ilm_t			*ilm;
10432 	ip_grpsrc_t		ips;
10433 	mblk_t			*mp_tail = NULL;
10434 	ill_walk_context_t	ctx;
10435 	zoneid_t		zoneid;
10436 	int			i;
10437 	slist_t			*sl;
10438 
10439 	/*
10440 	 * make a copy of the original message
10441 	 */
10442 	mp2ctl = copymsg(mpctl);
10443 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10444 
10445 	/* ipGroupSource table */
10446 	optp = (struct opthdr *)&mpctl->b_rptr[
10447 	    sizeof (struct T_optmgmt_ack)];
10448 	optp->level = MIB2_IP;
10449 	optp->name = EXPER_IP_GROUP_SOURCES;
10450 
10451 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10452 	ill = ILL_START_WALK_V4(&ctx, ipst);
10453 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10454 		/* Make sure the ill isn't going away. */
10455 		if (!ill_check_and_refhold(ill))
10456 			continue;
10457 		rw_exit(&ipst->ips_ill_g_lock);
10458 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10459 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10460 			sl = ilm->ilm_filter;
10461 			if (ilm->ilm_zoneid != zoneid &&
10462 			    ilm->ilm_zoneid != ALL_ZONES)
10463 				continue;
10464 			if (SLIST_IS_EMPTY(sl))
10465 				continue;
10466 
10467 			/* Is there an ipif for ilm_ifaddr? */
10468 			for (ipif = ill->ill_ipif; ipif != NULL;
10469 			    ipif = ipif->ipif_next) {
10470 				if (!IPIF_IS_CONDEMNED(ipif) &&
10471 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10472 				    ilm->ilm_ifaddr != INADDR_ANY)
10473 					break;
10474 			}
10475 			if (ipif != NULL) {
10476 				ipif_get_name(ipif,
10477 				    ips.ipGroupSourceIfIndex.o_bytes,
10478 				    OCTET_LENGTH);
10479 			} else {
10480 				ill_get_name(ill,
10481 				    ips.ipGroupSourceIfIndex.o_bytes,
10482 				    OCTET_LENGTH);
10483 			}
10484 			ips.ipGroupSourceIfIndex.o_length =
10485 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10486 
10487 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10488 			for (i = 0; i < sl->sl_numsrc; i++) {
10489 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10490 					continue;
10491 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10492 				    ips.ipGroupSourceAddress);
10493 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10494 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10495 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10496 					    " failed to allocate %u bytes\n",
10497 					    (uint_t)sizeof (ips)));
10498 				}
10499 			}
10500 		}
10501 		rw_exit(&ill->ill_mcast_lock);
10502 		ill_refrele(ill);
10503 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10504 	}
10505 	rw_exit(&ipst->ips_ill_g_lock);
10506 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10507 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10508 	    (int)optp->level, (int)optp->name, (int)optp->len));
10509 	qreply(q, mpctl);
10510 	return (mp2ctl);
10511 }
10512 
10513 /* IPv6 multicast filtered sources. */
10514 static mblk_t *
10515 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10516 {
10517 	struct opthdr		*optp;
10518 	mblk_t			*mp2ctl;
10519 	ill_t			*ill;
10520 	ilm_t			*ilm;
10521 	ipv6_grpsrc_t		ips6;
10522 	mblk_t			*mp_tail = NULL;
10523 	ill_walk_context_t	ctx;
10524 	zoneid_t		zoneid;
10525 	int			i;
10526 	slist_t			*sl;
10527 
10528 	/*
10529 	 * make a copy of the original message
10530 	 */
10531 	mp2ctl = copymsg(mpctl);
10532 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10533 
10534 	/* ip6GroupMember table */
10535 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10536 	optp->level = MIB2_IP6;
10537 	optp->name = EXPER_IP6_GROUP_SOURCES;
10538 
10539 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10540 	ill = ILL_START_WALK_V6(&ctx, ipst);
10541 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10542 		/* Make sure the ill isn't going away. */
10543 		if (!ill_check_and_refhold(ill))
10544 			continue;
10545 		rw_exit(&ipst->ips_ill_g_lock);
10546 		/*
10547 		 * Normally we don't have any members on under IPMP interfaces.
10548 		 * We report them as a debugging aid.
10549 		 */
10550 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10551 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10552 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10553 			sl = ilm->ilm_filter;
10554 			if (ilm->ilm_zoneid != zoneid &&
10555 			    ilm->ilm_zoneid != ALL_ZONES)
10556 				continue;
10557 			if (SLIST_IS_EMPTY(sl))
10558 				continue;
10559 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10560 			for (i = 0; i < sl->sl_numsrc; i++) {
10561 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10562 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10563 				    (char *)&ips6, (int)sizeof (ips6))) {
10564 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10565 					    "group_src: failed to allocate "
10566 					    "%u bytes\n",
10567 					    (uint_t)sizeof (ips6)));
10568 				}
10569 			}
10570 		}
10571 		rw_exit(&ill->ill_mcast_lock);
10572 		ill_refrele(ill);
10573 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10574 	}
10575 	rw_exit(&ipst->ips_ill_g_lock);
10576 
10577 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10578 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10579 	    (int)optp->level, (int)optp->name, (int)optp->len));
10580 	qreply(q, mpctl);
10581 	return (mp2ctl);
10582 }
10583 
10584 /* Multicast routing virtual interface table. */
10585 static mblk_t *
10586 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10587 {
10588 	struct opthdr		*optp;
10589 	mblk_t			*mp2ctl;
10590 
10591 	/*
10592 	 * make a copy of the original message
10593 	 */
10594 	mp2ctl = copymsg(mpctl);
10595 
10596 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10597 	optp->level = EXPER_DVMRP;
10598 	optp->name = EXPER_DVMRP_VIF;
10599 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10600 		ip0dbg(("ip_mroute_vif: failed\n"));
10601 	}
10602 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10603 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10604 	    (int)optp->level, (int)optp->name, (int)optp->len));
10605 	qreply(q, mpctl);
10606 	return (mp2ctl);
10607 }
10608 
10609 /* Multicast routing table. */
10610 static mblk_t *
10611 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10612 {
10613 	struct opthdr		*optp;
10614 	mblk_t			*mp2ctl;
10615 
10616 	/*
10617 	 * make a copy of the original message
10618 	 */
10619 	mp2ctl = copymsg(mpctl);
10620 
10621 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10622 	optp->level = EXPER_DVMRP;
10623 	optp->name = EXPER_DVMRP_MRT;
10624 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10625 		ip0dbg(("ip_mroute_mrt: failed\n"));
10626 	}
10627 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10628 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10629 	    (int)optp->level, (int)optp->name, (int)optp->len));
10630 	qreply(q, mpctl);
10631 	return (mp2ctl);
10632 }
10633 
10634 /*
10635  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10636  * in one IRE walk.
10637  */
10638 static mblk_t *
10639 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10640     ip_stack_t *ipst)
10641 {
10642 	struct opthdr	*optp;
10643 	mblk_t		*mp2ctl;	/* Returned */
10644 	mblk_t		*mp3ctl;	/* nettomedia */
10645 	mblk_t		*mp4ctl;	/* routeattrs */
10646 	iproutedata_t	ird;
10647 	zoneid_t	zoneid;
10648 
10649 	/*
10650 	 * make copies of the original message
10651 	 *	- mp2ctl is returned unchanged to the caller for his use
10652 	 *	- mpctl is sent upstream as ipRouteEntryTable
10653 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10654 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10655 	 */
10656 	mp2ctl = copymsg(mpctl);
10657 	mp3ctl = copymsg(mpctl);
10658 	mp4ctl = copymsg(mpctl);
10659 	if (mp3ctl == NULL || mp4ctl == NULL) {
10660 		freemsg(mp4ctl);
10661 		freemsg(mp3ctl);
10662 		freemsg(mp2ctl);
10663 		freemsg(mpctl);
10664 		return (NULL);
10665 	}
10666 
10667 	bzero(&ird, sizeof (ird));
10668 
10669 	ird.ird_route.lp_head = mpctl->b_cont;
10670 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10671 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10672 	/*
10673 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10674 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10675 	 * intended a temporary solution until a proper MIB API is provided
10676 	 * that provides complete filtering/caller-opt-in.
10677 	 */
10678 	if (level == EXPER_IP_AND_ALL_IRES)
10679 		ird.ird_flags |= IRD_REPORT_ALL;
10680 
10681 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10682 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10683 
10684 	/* ipRouteEntryTable in mpctl */
10685 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10686 	optp->level = MIB2_IP;
10687 	optp->name = MIB2_IP_ROUTE;
10688 	optp->len = msgdsize(ird.ird_route.lp_head);
10689 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10690 	    (int)optp->level, (int)optp->name, (int)optp->len));
10691 	qreply(q, mpctl);
10692 
10693 	/* ipNetToMediaEntryTable in mp3ctl */
10694 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10695 
10696 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10697 	optp->level = MIB2_IP;
10698 	optp->name = MIB2_IP_MEDIA;
10699 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10700 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10701 	    (int)optp->level, (int)optp->name, (int)optp->len));
10702 	qreply(q, mp3ctl);
10703 
10704 	/* ipRouteAttributeTable in mp4ctl */
10705 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10706 	optp->level = MIB2_IP;
10707 	optp->name = EXPER_IP_RTATTR;
10708 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10709 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10710 	    (int)optp->level, (int)optp->name, (int)optp->len));
10711 	if (optp->len == 0)
10712 		freemsg(mp4ctl);
10713 	else
10714 		qreply(q, mp4ctl);
10715 
10716 	return (mp2ctl);
10717 }
10718 
10719 /*
10720  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10721  * ipv6NetToMediaEntryTable in an NDP walk.
10722  */
10723 static mblk_t *
10724 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10725     ip_stack_t *ipst)
10726 {
10727 	struct opthdr	*optp;
10728 	mblk_t		*mp2ctl;	/* Returned */
10729 	mblk_t		*mp3ctl;	/* nettomedia */
10730 	mblk_t		*mp4ctl;	/* routeattrs */
10731 	iproutedata_t	ird;
10732 	zoneid_t	zoneid;
10733 
10734 	/*
10735 	 * make copies of the original message
10736 	 *	- mp2ctl is returned unchanged to the caller for his use
10737 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10738 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10739 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10740 	 */
10741 	mp2ctl = copymsg(mpctl);
10742 	mp3ctl = copymsg(mpctl);
10743 	mp4ctl = copymsg(mpctl);
10744 	if (mp3ctl == NULL || mp4ctl == NULL) {
10745 		freemsg(mp4ctl);
10746 		freemsg(mp3ctl);
10747 		freemsg(mp2ctl);
10748 		freemsg(mpctl);
10749 		return (NULL);
10750 	}
10751 
10752 	bzero(&ird, sizeof (ird));
10753 
10754 	ird.ird_route.lp_head = mpctl->b_cont;
10755 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10756 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10757 	/*
10758 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10759 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10760 	 * intended a temporary solution until a proper MIB API is provided
10761 	 * that provides complete filtering/caller-opt-in.
10762 	 */
10763 	if (level == EXPER_IP_AND_ALL_IRES)
10764 		ird.ird_flags |= IRD_REPORT_ALL;
10765 
10766 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10767 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10768 
10769 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10770 	optp->level = MIB2_IP6;
10771 	optp->name = MIB2_IP6_ROUTE;
10772 	optp->len = msgdsize(ird.ird_route.lp_head);
10773 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10774 	    (int)optp->level, (int)optp->name, (int)optp->len));
10775 	qreply(q, mpctl);
10776 
10777 	/* ipv6NetToMediaEntryTable in mp3ctl */
10778 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10779 
10780 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10781 	optp->level = MIB2_IP6;
10782 	optp->name = MIB2_IP6_MEDIA;
10783 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10784 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10785 	    (int)optp->level, (int)optp->name, (int)optp->len));
10786 	qreply(q, mp3ctl);
10787 
10788 	/* ipv6RouteAttributeTable in mp4ctl */
10789 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10790 	optp->level = MIB2_IP6;
10791 	optp->name = EXPER_IP_RTATTR;
10792 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10793 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10794 	    (int)optp->level, (int)optp->name, (int)optp->len));
10795 	if (optp->len == 0)
10796 		freemsg(mp4ctl);
10797 	else
10798 		qreply(q, mp4ctl);
10799 
10800 	return (mp2ctl);
10801 }
10802 
10803 /*
10804  * IPv6 mib: One per ill
10805  */
10806 static mblk_t *
10807 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10808 {
10809 	struct opthdr		*optp;
10810 	mblk_t			*mp2ctl;
10811 	ill_t			*ill;
10812 	ill_walk_context_t	ctx;
10813 	mblk_t			*mp_tail = NULL;
10814 
10815 	/*
10816 	 * Make a copy of the original message
10817 	 */
10818 	mp2ctl = copymsg(mpctl);
10819 
10820 	/* fixed length IPv6 structure ... */
10821 
10822 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10823 	optp->level = MIB2_IP6;
10824 	optp->name = 0;
10825 	/* Include "unknown interface" ip6_mib */
10826 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10827 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10828 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10829 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10830 	    ipst->ips_ipv6_forward ? 1 : 2);
10831 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10832 	    ipst->ips_ipv6_def_hops);
10833 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10834 	    sizeof (mib2_ipIfStatsEntry_t));
10835 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10836 	    sizeof (mib2_ipv6AddrEntry_t));
10837 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10838 	    sizeof (mib2_ipv6RouteEntry_t));
10839 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10840 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10841 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10842 	    sizeof (ipv6_member_t));
10843 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10844 	    sizeof (ipv6_grpsrc_t));
10845 
10846 	/*
10847 	 * Synchronize 64- and 32-bit counters
10848 	 */
10849 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10850 	    ipIfStatsHCInReceives);
10851 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10852 	    ipIfStatsHCInDelivers);
10853 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10854 	    ipIfStatsHCOutRequests);
10855 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10856 	    ipIfStatsHCOutForwDatagrams);
10857 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10858 	    ipIfStatsHCOutMcastPkts);
10859 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10860 	    ipIfStatsHCInMcastPkts);
10861 
10862 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10863 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
10864 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10865 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
10866 	}
10867 
10868 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10869 	ill = ILL_START_WALK_V6(&ctx, ipst);
10870 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10871 		ill->ill_ip_mib->ipIfStatsIfIndex =
10872 		    ill->ill_phyint->phyint_ifindex;
10873 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10874 		    ipst->ips_ipv6_forward ? 1 : 2);
10875 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10876 		    ill->ill_max_hops);
10877 
10878 		/*
10879 		 * Synchronize 64- and 32-bit counters
10880 		 */
10881 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10882 		    ipIfStatsHCInReceives);
10883 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10884 		    ipIfStatsHCInDelivers);
10885 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10886 		    ipIfStatsHCOutRequests);
10887 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10888 		    ipIfStatsHCOutForwDatagrams);
10889 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10890 		    ipIfStatsHCOutMcastPkts);
10891 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10892 		    ipIfStatsHCInMcastPkts);
10893 
10894 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10895 		    (char *)ill->ill_ip_mib,
10896 		    (int)sizeof (*ill->ill_ip_mib))) {
10897 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10898 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
10899 		}
10900 	}
10901 	rw_exit(&ipst->ips_ill_g_lock);
10902 
10903 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10904 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10905 	    (int)optp->level, (int)optp->name, (int)optp->len));
10906 	qreply(q, mpctl);
10907 	return (mp2ctl);
10908 }
10909 
10910 /*
10911  * ICMPv6 mib: One per ill
10912  */
10913 static mblk_t *
10914 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10915 {
10916 	struct opthdr		*optp;
10917 	mblk_t			*mp2ctl;
10918 	ill_t			*ill;
10919 	ill_walk_context_t	ctx;
10920 	mblk_t			*mp_tail = NULL;
10921 	/*
10922 	 * Make a copy of the original message
10923 	 */
10924 	mp2ctl = copymsg(mpctl);
10925 
10926 	/* fixed length ICMPv6 structure ... */
10927 
10928 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10929 	optp->level = MIB2_ICMP6;
10930 	optp->name = 0;
10931 	/* Include "unknown interface" icmp6_mib */
10932 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10933 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10934 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10935 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10936 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10937 	    (char *)&ipst->ips_icmp6_mib,
10938 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10939 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10940 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10941 	}
10942 
10943 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10944 	ill = ILL_START_WALK_V6(&ctx, ipst);
10945 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10946 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10947 		    ill->ill_phyint->phyint_ifindex;
10948 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10949 		    (char *)ill->ill_icmp6_mib,
10950 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10951 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10952 			    "%u bytes\n",
10953 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10954 		}
10955 	}
10956 	rw_exit(&ipst->ips_ill_g_lock);
10957 
10958 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10959 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10960 	    (int)optp->level, (int)optp->name, (int)optp->len));
10961 	qreply(q, mpctl);
10962 	return (mp2ctl);
10963 }
10964 
10965 /*
10966  * ire_walk routine to create both ipRouteEntryTable and
10967  * ipRouteAttributeTable in one IRE walk
10968  */
10969 static void
10970 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10971 {
10972 	ill_t				*ill;
10973 	mib2_ipRouteEntry_t		*re;
10974 	mib2_ipAttributeEntry_t		iaes;
10975 	tsol_ire_gw_secattr_t		*attrp;
10976 	tsol_gc_t			*gc = NULL;
10977 	tsol_gcgrp_t			*gcgrp = NULL;
10978 	ip_stack_t			*ipst = ire->ire_ipst;
10979 
10980 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10981 
10982 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10983 		if (ire->ire_testhidden)
10984 			return;
10985 		if (ire->ire_type & IRE_IF_CLONE)
10986 			return;
10987 	}
10988 
10989 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10990 		return;
10991 
10992 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10993 		mutex_enter(&attrp->igsa_lock);
10994 		if ((gc = attrp->igsa_gc) != NULL) {
10995 			gcgrp = gc->gc_grp;
10996 			ASSERT(gcgrp != NULL);
10997 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10998 		}
10999 		mutex_exit(&attrp->igsa_lock);
11000 	}
11001 	/*
11002 	 * Return all IRE types for route table... let caller pick and choose
11003 	 */
11004 	re->ipRouteDest = ire->ire_addr;
11005 	ill = ire->ire_ill;
11006 	re->ipRouteIfIndex.o_length = 0;
11007 	if (ill != NULL) {
11008 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
11009 		re->ipRouteIfIndex.o_length =
11010 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
11011 	}
11012 	re->ipRouteMetric1 = -1;
11013 	re->ipRouteMetric2 = -1;
11014 	re->ipRouteMetric3 = -1;
11015 	re->ipRouteMetric4 = -1;
11016 
11017 	re->ipRouteNextHop = ire->ire_gateway_addr;
11018 	/* indirect(4), direct(3), or invalid(2) */
11019 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11020 		re->ipRouteType = 2;
11021 	else if (ire->ire_type & IRE_ONLINK)
11022 		re->ipRouteType = 3;
11023 	else
11024 		re->ipRouteType = 4;
11025 
11026 	re->ipRouteProto = -1;
11027 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
11028 	re->ipRouteMask = ire->ire_mask;
11029 	re->ipRouteMetric5 = -1;
11030 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11031 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
11032 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11033 
11034 	re->ipRouteInfo.re_frag_flag	= 0;
11035 	re->ipRouteInfo.re_rtt		= 0;
11036 	re->ipRouteInfo.re_src_addr	= 0;
11037 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
11038 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11039 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11040 	re->ipRouteInfo.re_flags	= ire->ire_flags;
11041 
11042 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11043 	if (ire->ire_type & IRE_INTERFACE) {
11044 		ire_t *child;
11045 
11046 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11047 		child = ire->ire_dep_children;
11048 		while (child != NULL) {
11049 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
11050 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11051 			child = child->ire_dep_sib_next;
11052 		}
11053 		rw_exit(&ipst->ips_ire_dep_lock);
11054 	}
11055 
11056 	if (ire->ire_flags & RTF_DYNAMIC) {
11057 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11058 	} else {
11059 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
11060 	}
11061 
11062 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11063 	    (char *)re, (int)sizeof (*re))) {
11064 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
11065 		    (uint_t)sizeof (*re)));
11066 	}
11067 
11068 	if (gc != NULL) {
11069 		iaes.iae_routeidx = ird->ird_idx;
11070 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11071 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11072 
11073 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11074 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11075 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
11076 			    "bytes\n", (uint_t)sizeof (iaes)));
11077 		}
11078 	}
11079 
11080 	/* bump route index for next pass */
11081 	ird->ird_idx++;
11082 
11083 	kmem_free(re, sizeof (*re));
11084 	if (gcgrp != NULL)
11085 		rw_exit(&gcgrp->gcgrp_rwlock);
11086 }
11087 
11088 /*
11089  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
11090  */
11091 static void
11092 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
11093 {
11094 	ill_t				*ill;
11095 	mib2_ipv6RouteEntry_t		*re;
11096 	mib2_ipAttributeEntry_t		iaes;
11097 	tsol_ire_gw_secattr_t		*attrp;
11098 	tsol_gc_t			*gc = NULL;
11099 	tsol_gcgrp_t			*gcgrp = NULL;
11100 	ip_stack_t			*ipst = ire->ire_ipst;
11101 
11102 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
11103 
11104 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11105 		if (ire->ire_testhidden)
11106 			return;
11107 		if (ire->ire_type & IRE_IF_CLONE)
11108 			return;
11109 	}
11110 
11111 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11112 		return;
11113 
11114 	if ((attrp = ire->ire_gw_secattr) != NULL) {
11115 		mutex_enter(&attrp->igsa_lock);
11116 		if ((gc = attrp->igsa_gc) != NULL) {
11117 			gcgrp = gc->gc_grp;
11118 			ASSERT(gcgrp != NULL);
11119 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11120 		}
11121 		mutex_exit(&attrp->igsa_lock);
11122 	}
11123 	/*
11124 	 * Return all IRE types for route table... let caller pick and choose
11125 	 */
11126 	re->ipv6RouteDest = ire->ire_addr_v6;
11127 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11128 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
11129 	re->ipv6RouteIfIndex.o_length = 0;
11130 	ill = ire->ire_ill;
11131 	if (ill != NULL) {
11132 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11133 		re->ipv6RouteIfIndex.o_length =
11134 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11135 	}
11136 
11137 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
11138 
11139 	mutex_enter(&ire->ire_lock);
11140 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11141 	mutex_exit(&ire->ire_lock);
11142 
11143 	/* remote(4), local(3), or discard(2) */
11144 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11145 		re->ipv6RouteType = 2;
11146 	else if (ire->ire_type & IRE_ONLINK)
11147 		re->ipv6RouteType = 3;
11148 	else
11149 		re->ipv6RouteType = 4;
11150 
11151 	re->ipv6RouteProtocol	= -1;
11152 	re->ipv6RoutePolicy	= 0;
11153 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
11154 	re->ipv6RouteNextHopRDI	= 0;
11155 	re->ipv6RouteWeight	= 0;
11156 	re->ipv6RouteMetric	= 0;
11157 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11158 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11159 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11160 
11161 	re->ipv6RouteInfo.re_frag_flag	= 0;
11162 	re->ipv6RouteInfo.re_rtt	= 0;
11163 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
11164 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11165 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11166 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
11167 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
11168 
11169 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11170 	if (ire->ire_type & IRE_INTERFACE) {
11171 		ire_t *child;
11172 
11173 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11174 		child = ire->ire_dep_children;
11175 		while (child != NULL) {
11176 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11177 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11178 			child = child->ire_dep_sib_next;
11179 		}
11180 		rw_exit(&ipst->ips_ire_dep_lock);
11181 	}
11182 	if (ire->ire_flags & RTF_DYNAMIC) {
11183 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11184 	} else {
11185 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
11186 	}
11187 
11188 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11189 	    (char *)re, (int)sizeof (*re))) {
11190 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11191 		    (uint_t)sizeof (*re)));
11192 	}
11193 
11194 	if (gc != NULL) {
11195 		iaes.iae_routeidx = ird->ird_idx;
11196 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11197 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11198 
11199 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11200 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11201 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11202 			    "bytes\n", (uint_t)sizeof (iaes)));
11203 		}
11204 	}
11205 
11206 	/* bump route index for next pass */
11207 	ird->ird_idx++;
11208 
11209 	kmem_free(re, sizeof (*re));
11210 	if (gcgrp != NULL)
11211 		rw_exit(&gcgrp->gcgrp_rwlock);
11212 }
11213 
11214 /*
11215  * ncec_walk routine to create ipv6NetToMediaEntryTable
11216  */
11217 static int
11218 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11219 {
11220 	ill_t				*ill;
11221 	mib2_ipv6NetToMediaEntry_t	ntme;
11222 
11223 	ill = ncec->ncec_ill;
11224 	/* skip arpce entries, and loopback ncec entries */
11225 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11226 		return (0);
11227 	/*
11228 	 * Neighbor cache entry attached to IRE with on-link
11229 	 * destination.
11230 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11231 	 */
11232 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11233 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11234 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11235 	if (ncec->ncec_lladdr != NULL) {
11236 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11237 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11238 	}
11239 	/*
11240 	 * Note: Returns ND_* states. Should be:
11241 	 * reachable(1), stale(2), delay(3), probe(4),
11242 	 * invalid(5), unknown(6)
11243 	 */
11244 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11245 	ntme.ipv6NetToMediaLastUpdated = 0;
11246 
11247 	/* other(1), dynamic(2), static(3), local(4) */
11248 	if (NCE_MYADDR(ncec)) {
11249 		ntme.ipv6NetToMediaType = 4;
11250 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11251 		ntme.ipv6NetToMediaType = 1; /* proxy */
11252 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11253 		ntme.ipv6NetToMediaType = 3;
11254 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11255 		ntme.ipv6NetToMediaType = 1;
11256 	} else {
11257 		ntme.ipv6NetToMediaType = 2;
11258 	}
11259 
11260 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11261 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11262 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11263 		    (uint_t)sizeof (ntme)));
11264 	}
11265 	return (0);
11266 }
11267 
11268 int
11269 nce2ace(ncec_t *ncec)
11270 {
11271 	int flags = 0;
11272 
11273 	if (NCE_ISREACHABLE(ncec))
11274 		flags |= ACE_F_RESOLVED;
11275 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11276 		flags |= ACE_F_AUTHORITY;
11277 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11278 		flags |= ACE_F_PUBLISH;
11279 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11280 		flags |= ACE_F_PERMANENT;
11281 	if (NCE_MYADDR(ncec))
11282 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11283 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11284 		flags |= ACE_F_UNVERIFIED;
11285 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11286 		flags |= ACE_F_AUTHORITY;
11287 	if (ncec->ncec_flags & NCE_F_DELAYED)
11288 		flags |= ACE_F_DELAYED;
11289 	return (flags);
11290 }
11291 
11292 /*
11293  * ncec_walk routine to create ipNetToMediaEntryTable
11294  */
11295 static int
11296 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11297 {
11298 	ill_t				*ill;
11299 	mib2_ipNetToMediaEntry_t	ntme;
11300 	const char			*name = "unknown";
11301 	ipaddr_t			ncec_addr;
11302 
11303 	ill = ncec->ncec_ill;
11304 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11305 	    ill->ill_net_type == IRE_LOOPBACK)
11306 		return (0);
11307 
11308 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11309 	name = ill->ill_name;
11310 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11311 	if (NCE_MYADDR(ncec)) {
11312 		ntme.ipNetToMediaType = 4;
11313 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11314 		ntme.ipNetToMediaType = 1;
11315 	} else {
11316 		ntme.ipNetToMediaType = 3;
11317 	}
11318 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11319 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11320 	    ntme.ipNetToMediaIfIndex.o_length);
11321 
11322 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11323 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11324 
11325 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11326 	ncec_addr = INADDR_BROADCAST;
11327 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11328 	    sizeof (ncec_addr));
11329 	/*
11330 	 * map all the flags to the ACE counterpart.
11331 	 */
11332 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11333 
11334 	ntme.ipNetToMediaPhysAddress.o_length =
11335 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11336 
11337 	if (!NCE_ISREACHABLE(ncec))
11338 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11339 	else {
11340 		if (ncec->ncec_lladdr != NULL) {
11341 			bcopy(ncec->ncec_lladdr,
11342 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11343 			    ntme.ipNetToMediaPhysAddress.o_length);
11344 		}
11345 	}
11346 
11347 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11348 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11349 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11350 		    (uint_t)sizeof (ntme)));
11351 	}
11352 	return (0);
11353 }
11354 
11355 /*
11356  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11357  */
11358 /* ARGSUSED */
11359 int
11360 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11361 {
11362 	switch (level) {
11363 	case MIB2_IP:
11364 	case MIB2_ICMP:
11365 		switch (name) {
11366 		default:
11367 			break;
11368 		}
11369 		return (1);
11370 	default:
11371 		return (1);
11372 	}
11373 }
11374 
11375 /*
11376  * When there exists both a 64- and 32-bit counter of a particular type
11377  * (i.e., InReceives), only the 64-bit counters are added.
11378  */
11379 void
11380 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11381 {
11382 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11383 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11384 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11385 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11386 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11387 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11388 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11389 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11390 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11391 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11392 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11393 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11394 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11395 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11396 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11397 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11398 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11399 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11400 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11401 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11402 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11403 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11404 	    o2->ipIfStatsInWrongIPVersion);
11405 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11406 	    o2->ipIfStatsInWrongIPVersion);
11407 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11408 	    o2->ipIfStatsOutSwitchIPVersion);
11409 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11410 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11411 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11412 	    o2->ipIfStatsHCInForwDatagrams);
11413 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11414 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11415 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11416 	    o2->ipIfStatsHCOutForwDatagrams);
11417 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11418 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11419 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11420 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11421 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11422 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11423 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11424 	    o2->ipIfStatsHCOutMcastOctets);
11425 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11426 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11427 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11428 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11429 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11430 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11431 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11432 }
11433 
11434 void
11435 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11436 {
11437 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11438 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11439 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11440 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11441 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11442 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11443 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11444 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11445 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11446 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11447 	    o2->ipv6IfIcmpInRouterSolicits);
11448 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11449 	    o2->ipv6IfIcmpInRouterAdvertisements);
11450 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11451 	    o2->ipv6IfIcmpInNeighborSolicits);
11452 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11453 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11454 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11455 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11456 	    o2->ipv6IfIcmpInGroupMembQueries);
11457 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11458 	    o2->ipv6IfIcmpInGroupMembResponses);
11459 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11460 	    o2->ipv6IfIcmpInGroupMembReductions);
11461 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11462 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11463 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11464 	    o2->ipv6IfIcmpOutDestUnreachs);
11465 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11466 	    o2->ipv6IfIcmpOutAdminProhibs);
11467 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11468 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11469 	    o2->ipv6IfIcmpOutParmProblems);
11470 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11471 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11472 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11473 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11474 	    o2->ipv6IfIcmpOutRouterSolicits);
11475 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11476 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11477 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11478 	    o2->ipv6IfIcmpOutNeighborSolicits);
11479 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11480 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11481 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11482 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11483 	    o2->ipv6IfIcmpOutGroupMembQueries);
11484 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11485 	    o2->ipv6IfIcmpOutGroupMembResponses);
11486 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11487 	    o2->ipv6IfIcmpOutGroupMembReductions);
11488 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11489 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11490 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11491 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11492 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11493 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11494 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11495 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11496 	    o2->ipv6IfIcmpInGroupMembTotal);
11497 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11498 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11499 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11500 	    o2->ipv6IfIcmpInGroupMembBadReports);
11501 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11502 	    o2->ipv6IfIcmpInGroupMembOurReports);
11503 }
11504 
11505 /*
11506  * Called before the options are updated to check if this packet will
11507  * be source routed from here.
11508  * This routine assumes that the options are well formed i.e. that they
11509  * have already been checked.
11510  */
11511 boolean_t
11512 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11513 {
11514 	ipoptp_t	opts;
11515 	uchar_t		*opt;
11516 	uint8_t		optval;
11517 	uint8_t		optlen;
11518 	ipaddr_t	dst;
11519 
11520 	if (IS_SIMPLE_IPH(ipha)) {
11521 		ip2dbg(("not source routed\n"));
11522 		return (B_FALSE);
11523 	}
11524 	dst = ipha->ipha_dst;
11525 	for (optval = ipoptp_first(&opts, ipha);
11526 	    optval != IPOPT_EOL;
11527 	    optval = ipoptp_next(&opts)) {
11528 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11529 		opt = opts.ipoptp_cur;
11530 		optlen = opts.ipoptp_len;
11531 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11532 		    optval, optlen));
11533 		switch (optval) {
11534 			uint32_t off;
11535 		case IPOPT_SSRR:
11536 		case IPOPT_LSRR:
11537 			/*
11538 			 * If dst is one of our addresses and there are some
11539 			 * entries left in the source route return (true).
11540 			 */
11541 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11542 				ip2dbg(("ip_source_routed: not next"
11543 				    " source route 0x%x\n",
11544 				    ntohl(dst)));
11545 				return (B_FALSE);
11546 			}
11547 			off = opt[IPOPT_OFFSET];
11548 			off--;
11549 			if (optlen < IP_ADDR_LEN ||
11550 			    off > optlen - IP_ADDR_LEN) {
11551 				/* End of source route */
11552 				ip1dbg(("ip_source_routed: end of SR\n"));
11553 				return (B_FALSE);
11554 			}
11555 			return (B_TRUE);
11556 		}
11557 	}
11558 	ip2dbg(("not source routed\n"));
11559 	return (B_FALSE);
11560 }
11561 
11562 /*
11563  * ip_unbind is called by the transports to remove a conn from
11564  * the fanout table.
11565  */
11566 void
11567 ip_unbind(conn_t *connp)
11568 {
11569 
11570 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11571 
11572 	if (is_system_labeled() && connp->conn_anon_port) {
11573 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11574 		    connp->conn_mlp_type, connp->conn_proto,
11575 		    ntohs(connp->conn_lport), B_FALSE);
11576 		connp->conn_anon_port = 0;
11577 	}
11578 	connp->conn_mlp_type = mlptSingle;
11579 
11580 	ipcl_hash_remove(connp);
11581 }
11582 
11583 /*
11584  * Used for deciding the MSS size for the upper layer. Thus
11585  * we need to check the outbound policy values in the conn.
11586  */
11587 int
11588 conn_ipsec_length(conn_t *connp)
11589 {
11590 	ipsec_latch_t *ipl;
11591 
11592 	ipl = connp->conn_latch;
11593 	if (ipl == NULL)
11594 		return (0);
11595 
11596 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11597 		return (0);
11598 
11599 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11600 }
11601 
11602 /*
11603  * Returns an estimate of the IPsec headers size. This is used if
11604  * we don't want to call into IPsec to get the exact size.
11605  */
11606 int
11607 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11608 {
11609 	ipsec_action_t *a;
11610 
11611 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11612 		return (0);
11613 
11614 	a = ixa->ixa_ipsec_action;
11615 	if (a == NULL) {
11616 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11617 		a = ixa->ixa_ipsec_policy->ipsp_act;
11618 	}
11619 	ASSERT(a != NULL);
11620 
11621 	return (a->ipa_ovhd);
11622 }
11623 
11624 /*
11625  * If there are any source route options, return the true final
11626  * destination. Otherwise, return the destination.
11627  */
11628 ipaddr_t
11629 ip_get_dst(ipha_t *ipha)
11630 {
11631 	ipoptp_t	opts;
11632 	uchar_t		*opt;
11633 	uint8_t		optval;
11634 	uint8_t		optlen;
11635 	ipaddr_t	dst;
11636 	uint32_t off;
11637 
11638 	dst = ipha->ipha_dst;
11639 
11640 	if (IS_SIMPLE_IPH(ipha))
11641 		return (dst);
11642 
11643 	for (optval = ipoptp_first(&opts, ipha);
11644 	    optval != IPOPT_EOL;
11645 	    optval = ipoptp_next(&opts)) {
11646 		opt = opts.ipoptp_cur;
11647 		optlen = opts.ipoptp_len;
11648 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11649 		switch (optval) {
11650 		case IPOPT_SSRR:
11651 		case IPOPT_LSRR:
11652 			off = opt[IPOPT_OFFSET];
11653 			/*
11654 			 * If one of the conditions is true, it means
11655 			 * end of options and dst already has the right
11656 			 * value.
11657 			 */
11658 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11659 				off = optlen - IP_ADDR_LEN;
11660 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11661 			}
11662 			return (dst);
11663 		default:
11664 			break;
11665 		}
11666 	}
11667 
11668 	return (dst);
11669 }
11670 
11671 /*
11672  * Outbound IP fragmentation routine.
11673  * Assumes the caller has checked whether or not fragmentation should
11674  * be allowed. Here we copy the DF bit from the header to all the generated
11675  * fragments.
11676  */
11677 int
11678 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11679     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11680     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11681 {
11682 	int		i1;
11683 	int		hdr_len;
11684 	mblk_t		*hdr_mp;
11685 	ipha_t		*ipha;
11686 	int		ip_data_end;
11687 	int		len;
11688 	mblk_t		*mp = mp_orig;
11689 	int		offset;
11690 	ill_t		*ill = nce->nce_ill;
11691 	ip_stack_t	*ipst = ill->ill_ipst;
11692 	mblk_t		*carve_mp;
11693 	uint32_t	frag_flag;
11694 	uint_t		priority = mp->b_band;
11695 	int		error = 0;
11696 
11697 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11698 
11699 	if (pkt_len != msgdsize(mp)) {
11700 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11701 		    pkt_len, msgdsize(mp)));
11702 		freemsg(mp);
11703 		return (EINVAL);
11704 	}
11705 
11706 	if (max_frag == 0) {
11707 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11708 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11709 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11710 		freemsg(mp);
11711 		return (EINVAL);
11712 	}
11713 
11714 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11715 	ipha = (ipha_t *)mp->b_rptr;
11716 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11717 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11718 
11719 	/*
11720 	 * Establish the starting offset.  May not be zero if we are fragging
11721 	 * a fragment that is being forwarded.
11722 	 */
11723 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11724 
11725 	/* TODO why is this test needed? */
11726 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11727 		/* TODO: notify ulp somehow */
11728 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11729 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11730 		freemsg(mp);
11731 		return (EINVAL);
11732 	}
11733 
11734 	hdr_len = IPH_HDR_LENGTH(ipha);
11735 	ipha->ipha_hdr_checksum = 0;
11736 
11737 	/*
11738 	 * Establish the number of bytes maximum per frag, after putting
11739 	 * in the header.
11740 	 */
11741 	len = (max_frag - hdr_len) & ~7;
11742 
11743 	/* Get a copy of the header for the trailing frags */
11744 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11745 	    mp);
11746 	if (hdr_mp == NULL) {
11747 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11748 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11749 		freemsg(mp);
11750 		return (ENOBUFS);
11751 	}
11752 
11753 	/* Store the starting offset, with the MoreFrags flag. */
11754 	i1 = offset | IPH_MF | frag_flag;
11755 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11756 
11757 	/* Establish the ending byte offset, based on the starting offset. */
11758 	offset <<= 3;
11759 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11760 
11761 	/* Store the length of the first fragment in the IP header. */
11762 	i1 = len + hdr_len;
11763 	ASSERT(i1 <= IP_MAXPACKET);
11764 	ipha->ipha_length = htons((uint16_t)i1);
11765 
11766 	/*
11767 	 * Compute the IP header checksum for the first frag.  We have to
11768 	 * watch out that we stop at the end of the header.
11769 	 */
11770 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11771 
11772 	/*
11773 	 * Now carve off the first frag.  Note that this will include the
11774 	 * original IP header.
11775 	 */
11776 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11777 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11778 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11779 		freeb(hdr_mp);
11780 		freemsg(mp_orig);
11781 		return (ENOBUFS);
11782 	}
11783 
11784 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11785 
11786 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11787 	    ixa_cookie);
11788 	if (error != 0 && error != EWOULDBLOCK) {
11789 		/* No point in sending the other fragments */
11790 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11791 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11792 		freeb(hdr_mp);
11793 		freemsg(mp_orig);
11794 		return (error);
11795 	}
11796 
11797 	/* No need to redo state machine in loop */
11798 	ixaflags &= ~IXAF_REACH_CONF;
11799 
11800 	/* Advance the offset to the second frag starting point. */
11801 	offset += len;
11802 	/*
11803 	 * Update hdr_len from the copied header - there might be less options
11804 	 * in the later fragments.
11805 	 */
11806 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11807 	/* Loop until done. */
11808 	for (;;) {
11809 		uint16_t	offset_and_flags;
11810 		uint16_t	ip_len;
11811 
11812 		if (ip_data_end - offset > len) {
11813 			/*
11814 			 * Carve off the appropriate amount from the original
11815 			 * datagram.
11816 			 */
11817 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11818 				mp = NULL;
11819 				break;
11820 			}
11821 			/*
11822 			 * More frags after this one.  Get another copy
11823 			 * of the header.
11824 			 */
11825 			if (carve_mp->b_datap->db_ref == 1 &&
11826 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11827 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11828 				/* Inline IP header */
11829 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11830 				    hdr_mp->b_rptr;
11831 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11832 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11833 				mp = carve_mp;
11834 			} else {
11835 				if (!(mp = copyb(hdr_mp))) {
11836 					freemsg(carve_mp);
11837 					break;
11838 				}
11839 				/* Get priority marking, if any. */
11840 				mp->b_band = priority;
11841 				mp->b_cont = carve_mp;
11842 			}
11843 			ipha = (ipha_t *)mp->b_rptr;
11844 			offset_and_flags = IPH_MF;
11845 		} else {
11846 			/*
11847 			 * Last frag.  Consume the header. Set len to
11848 			 * the length of this last piece.
11849 			 */
11850 			len = ip_data_end - offset;
11851 
11852 			/*
11853 			 * Carve off the appropriate amount from the original
11854 			 * datagram.
11855 			 */
11856 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11857 				mp = NULL;
11858 				break;
11859 			}
11860 			if (carve_mp->b_datap->db_ref == 1 &&
11861 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11862 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11863 				/* Inline IP header */
11864 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11865 				    hdr_mp->b_rptr;
11866 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11867 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11868 				mp = carve_mp;
11869 				freeb(hdr_mp);
11870 				hdr_mp = mp;
11871 			} else {
11872 				mp = hdr_mp;
11873 				/* Get priority marking, if any. */
11874 				mp->b_band = priority;
11875 				mp->b_cont = carve_mp;
11876 			}
11877 			ipha = (ipha_t *)mp->b_rptr;
11878 			/* A frag of a frag might have IPH_MF non-zero */
11879 			offset_and_flags =
11880 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11881 			    IPH_MF;
11882 		}
11883 		offset_and_flags |= (uint16_t)(offset >> 3);
11884 		offset_and_flags |= (uint16_t)frag_flag;
11885 		/* Store the offset and flags in the IP header. */
11886 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11887 
11888 		/* Store the length in the IP header. */
11889 		ip_len = (uint16_t)(len + hdr_len);
11890 		ipha->ipha_length = htons(ip_len);
11891 
11892 		/*
11893 		 * Set the IP header checksum.	Note that mp is just
11894 		 * the header, so this is easy to pass to ip_csum.
11895 		 */
11896 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11897 
11898 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11899 
11900 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11901 		    nolzid, ixa_cookie);
11902 		/* All done if we just consumed the hdr_mp. */
11903 		if (mp == hdr_mp) {
11904 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11905 			return (error);
11906 		}
11907 		if (error != 0 && error != EWOULDBLOCK) {
11908 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11909 			    mblk_t *, hdr_mp);
11910 			/* No point in sending the other fragments */
11911 			break;
11912 		}
11913 
11914 		/* Otherwise, advance and loop. */
11915 		offset += len;
11916 	}
11917 	/* Clean up following allocation failure. */
11918 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11919 	ip_drop_output("FragFails: loop ended", NULL, ill);
11920 	if (mp != hdr_mp)
11921 		freeb(hdr_mp);
11922 	if (mp != mp_orig)
11923 		freemsg(mp_orig);
11924 	return (error);
11925 }
11926 
11927 /*
11928  * Copy the header plus those options which have the copy bit set
11929  */
11930 static mblk_t *
11931 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11932     mblk_t *src)
11933 {
11934 	mblk_t	*mp;
11935 	uchar_t	*up;
11936 
11937 	/*
11938 	 * Quick check if we need to look for options without the copy bit
11939 	 * set
11940 	 */
11941 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11942 	if (!mp)
11943 		return (mp);
11944 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11945 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11946 		bcopy(rptr, mp->b_rptr, hdr_len);
11947 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11948 		return (mp);
11949 	}
11950 	up  = mp->b_rptr;
11951 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11952 	up += IP_SIMPLE_HDR_LENGTH;
11953 	rptr += IP_SIMPLE_HDR_LENGTH;
11954 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11955 	while (hdr_len > 0) {
11956 		uint32_t optval;
11957 		uint32_t optlen;
11958 
11959 		optval = *rptr;
11960 		if (optval == IPOPT_EOL)
11961 			break;
11962 		if (optval == IPOPT_NOP)
11963 			optlen = 1;
11964 		else
11965 			optlen = rptr[1];
11966 		if (optval & IPOPT_COPY) {
11967 			bcopy(rptr, up, optlen);
11968 			up += optlen;
11969 		}
11970 		rptr += optlen;
11971 		hdr_len -= optlen;
11972 	}
11973 	/*
11974 	 * Make sure that we drop an even number of words by filling
11975 	 * with EOL to the next word boundary.
11976 	 */
11977 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11978 	    hdr_len & 0x3; hdr_len++)
11979 		*up++ = IPOPT_EOL;
11980 	mp->b_wptr = up;
11981 	/* Update header length */
11982 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11983 	return (mp);
11984 }
11985 
11986 /*
11987  * Update any source route, record route, or timestamp options when
11988  * sending a packet back to ourselves.
11989  * Check that we are at end of strict source route.
11990  * The options have been sanity checked by ip_output_options().
11991  */
11992 void
11993 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11994 {
11995 	ipoptp_t	opts;
11996 	uchar_t		*opt;
11997 	uint8_t		optval;
11998 	uint8_t		optlen;
11999 	ipaddr_t	dst;
12000 	uint32_t	ts;
12001 	timestruc_t	now;
12002 
12003 	for (optval = ipoptp_first(&opts, ipha);
12004 	    optval != IPOPT_EOL;
12005 	    optval = ipoptp_next(&opts)) {
12006 		opt = opts.ipoptp_cur;
12007 		optlen = opts.ipoptp_len;
12008 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
12009 		switch (optval) {
12010 			uint32_t off;
12011 		case IPOPT_SSRR:
12012 		case IPOPT_LSRR:
12013 			off = opt[IPOPT_OFFSET];
12014 			off--;
12015 			if (optlen < IP_ADDR_LEN ||
12016 			    off > optlen - IP_ADDR_LEN) {
12017 				/* End of source route */
12018 				break;
12019 			}
12020 			/*
12021 			 * This will only happen if two consecutive entries
12022 			 * in the source route contains our address or if
12023 			 * it is a packet with a loose source route which
12024 			 * reaches us before consuming the whole source route
12025 			 */
12026 
12027 			if (optval == IPOPT_SSRR) {
12028 				return;
12029 			}
12030 			/*
12031 			 * Hack: instead of dropping the packet truncate the
12032 			 * source route to what has been used by filling the
12033 			 * rest with IPOPT_NOP.
12034 			 */
12035 			opt[IPOPT_OLEN] = (uint8_t)off;
12036 			while (off < optlen) {
12037 				opt[off++] = IPOPT_NOP;
12038 			}
12039 			break;
12040 		case IPOPT_RR:
12041 			off = opt[IPOPT_OFFSET];
12042 			off--;
12043 			if (optlen < IP_ADDR_LEN ||
12044 			    off > optlen - IP_ADDR_LEN) {
12045 				/* No more room - ignore */
12046 				ip1dbg((
12047 				    "ip_output_local_options: end of RR\n"));
12048 				break;
12049 			}
12050 			dst = htonl(INADDR_LOOPBACK);
12051 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12052 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12053 			break;
12054 		case IPOPT_TS:
12055 			/* Insert timestamp if there is romm */
12056 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12057 			case IPOPT_TS_TSONLY:
12058 				off = IPOPT_TS_TIMELEN;
12059 				break;
12060 			case IPOPT_TS_PRESPEC:
12061 			case IPOPT_TS_PRESPEC_RFC791:
12062 				/* Verify that the address matched */
12063 				off = opt[IPOPT_OFFSET] - 1;
12064 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
12065 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
12066 					/* Not for us */
12067 					break;
12068 				}
12069 				/* FALLTHRU */
12070 			case IPOPT_TS_TSANDADDR:
12071 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12072 				break;
12073 			default:
12074 				/*
12075 				 * ip_*put_options should have already
12076 				 * dropped this packet.
12077 				 */
12078 				cmn_err(CE_PANIC, "ip_output_local_options: "
12079 				    "unknown IT - bug in ip_output_options?\n");
12080 				return;	/* Keep "lint" happy */
12081 			}
12082 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
12083 				/* Increase overflow counter */
12084 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
12085 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
12086 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
12087 				    (off << 4);
12088 				break;
12089 			}
12090 			off = opt[IPOPT_OFFSET] - 1;
12091 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12092 			case IPOPT_TS_PRESPEC:
12093 			case IPOPT_TS_PRESPEC_RFC791:
12094 			case IPOPT_TS_TSANDADDR:
12095 				dst = htonl(INADDR_LOOPBACK);
12096 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12097 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12098 				/* FALLTHRU */
12099 			case IPOPT_TS_TSONLY:
12100 				off = opt[IPOPT_OFFSET] - 1;
12101 				/* Compute # of milliseconds since midnight */
12102 				gethrestime(&now);
12103 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
12104 				    now.tv_nsec / (NANOSEC / MILLISEC);
12105 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
12106 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
12107 				break;
12108 			}
12109 			break;
12110 		}
12111 	}
12112 }
12113 
12114 /*
12115  * Prepend an M_DATA fastpath header, and if none present prepend a
12116  * DL_UNITDATA_REQ. Frees the mblk on failure.
12117  *
12118  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12119  * If there is a change to them, the nce will be deleted (condemned) and
12120  * a new nce_t will be created when packets are sent. Thus we need no locks
12121  * to access those fields.
12122  *
12123  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12124  * we place b_band in dl_priority.dl_max.
12125  */
12126 static mblk_t *
12127 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12128 {
12129 	uint_t	hlen;
12130 	mblk_t *mp1;
12131 	uint_t	priority;
12132 	uchar_t *rptr;
12133 
12134 	rptr = mp->b_rptr;
12135 
12136 	ASSERT(DB_TYPE(mp) == M_DATA);
12137 	priority = mp->b_band;
12138 
12139 	ASSERT(nce != NULL);
12140 	if ((mp1 = nce->nce_fp_mp) != NULL) {
12141 		hlen = MBLKL(mp1);
12142 		/*
12143 		 * Check if we have enough room to prepend fastpath
12144 		 * header
12145 		 */
12146 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12147 			rptr -= hlen;
12148 			bcopy(mp1->b_rptr, rptr, hlen);
12149 			/*
12150 			 * Set the b_rptr to the start of the link layer
12151 			 * header
12152 			 */
12153 			mp->b_rptr = rptr;
12154 			return (mp);
12155 		}
12156 		mp1 = copyb(mp1);
12157 		if (mp1 == NULL) {
12158 			ill_t *ill = nce->nce_ill;
12159 
12160 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12161 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12162 			freemsg(mp);
12163 			return (NULL);
12164 		}
12165 		mp1->b_band = priority;
12166 		mp1->b_cont = mp;
12167 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12168 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12169 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12170 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12171 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12172 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12173 		/*
12174 		 * XXX disable ICK_VALID and compute checksum
12175 		 * here; can happen if nce_fp_mp changes and
12176 		 * it can't be copied now due to insufficient
12177 		 * space. (unlikely, fp mp can change, but it
12178 		 * does not increase in length)
12179 		 */
12180 		return (mp1);
12181 	}
12182 	mp1 = copyb(nce->nce_dlur_mp);
12183 
12184 	if (mp1 == NULL) {
12185 		ill_t *ill = nce->nce_ill;
12186 
12187 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12188 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12189 		freemsg(mp);
12190 		return (NULL);
12191 	}
12192 	mp1->b_cont = mp;
12193 	if (priority != 0) {
12194 		mp1->b_band = priority;
12195 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12196 		    priority;
12197 	}
12198 	return (mp1);
12199 #undef rptr
12200 }
12201 
12202 /*
12203  * Finish the outbound IPsec processing. This function is called from
12204  * ipsec_out_process() if the IPsec packet was processed
12205  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12206  * asynchronously.
12207  *
12208  * This is common to IPv4 and IPv6.
12209  */
12210 int
12211 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12212 {
12213 	iaflags_t	ixaflags = ixa->ixa_flags;
12214 	uint_t		pktlen;
12215 
12216 
12217 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12218 	if (ixaflags & IXAF_IS_IPV4) {
12219 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12220 
12221 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12222 		pktlen = ntohs(ipha->ipha_length);
12223 	} else {
12224 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12225 
12226 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12227 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12228 	}
12229 
12230 	/*
12231 	 * We release any hard reference on the SAs here to make
12232 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12233 	 * on the SAs.
12234 	 * If in the future we want the hard latching of the SAs in the
12235 	 * ip_xmit_attr_t then we should remove this.
12236 	 */
12237 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12238 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12239 		ixa->ixa_ipsec_esp_sa = NULL;
12240 	}
12241 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12242 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12243 		ixa->ixa_ipsec_ah_sa = NULL;
12244 	}
12245 
12246 	/* Do we need to fragment? */
12247 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12248 	    pktlen > ixa->ixa_fragsize) {
12249 		if (ixaflags & IXAF_IS_IPV4) {
12250 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12251 			/*
12252 			 * We check for the DF case in ipsec_out_process
12253 			 * hence this only handles the non-DF case.
12254 			 */
12255 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12256 			    pktlen, ixa->ixa_fragsize,
12257 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12258 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12259 			    &ixa->ixa_cookie));
12260 		} else {
12261 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12262 			if (mp == NULL) {
12263 				/* MIB and ip_drop_output already done */
12264 				return (ENOMEM);
12265 			}
12266 			pktlen += sizeof (ip6_frag_t);
12267 			if (pktlen > ixa->ixa_fragsize) {
12268 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12269 				    ixa->ixa_flags, pktlen,
12270 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12271 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12272 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12273 			}
12274 		}
12275 	}
12276 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12277 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12278 	    ixa->ixa_no_loop_zoneid, NULL));
12279 }
12280 
12281 /*
12282  * Finish the inbound IPsec processing. This function is called from
12283  * ipsec_out_process() if the IPsec packet was processed
12284  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12285  * asynchronously.
12286  *
12287  * This is common to IPv4 and IPv6.
12288  */
12289 void
12290 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12291 {
12292 	iaflags_t	iraflags = ira->ira_flags;
12293 
12294 	/* Length might have changed */
12295 	if (iraflags & IRAF_IS_IPV4) {
12296 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12297 
12298 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12299 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12300 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12301 		ira->ira_protocol = ipha->ipha_protocol;
12302 
12303 		ip_fanout_v4(mp, ipha, ira);
12304 	} else {
12305 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12306 		uint8_t		*nexthdrp;
12307 
12308 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12309 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12310 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12311 		    &nexthdrp)) {
12312 			/* Malformed packet */
12313 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12314 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12315 			freemsg(mp);
12316 			return;
12317 		}
12318 		ira->ira_protocol = *nexthdrp;
12319 		ip_fanout_v6(mp, ip6h, ira);
12320 	}
12321 }
12322 
12323 /*
12324  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12325  *
12326  * If this function returns B_TRUE, the requested SA's have been filled
12327  * into the ixa_ipsec_*_sa pointers.
12328  *
12329  * If the function returns B_FALSE, the packet has been "consumed", most
12330  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12331  *
12332  * The SA references created by the protocol-specific "select"
12333  * function will be released in ip_output_post_ipsec.
12334  */
12335 static boolean_t
12336 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12337 {
12338 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12339 	ipsec_policy_t *pp;
12340 	ipsec_action_t *ap;
12341 
12342 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12343 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12344 	    (ixa->ixa_ipsec_action != NULL));
12345 
12346 	ap = ixa->ixa_ipsec_action;
12347 	if (ap == NULL) {
12348 		pp = ixa->ixa_ipsec_policy;
12349 		ASSERT(pp != NULL);
12350 		ap = pp->ipsp_act;
12351 		ASSERT(ap != NULL);
12352 	}
12353 
12354 	/*
12355 	 * We have an action.  now, let's select SA's.
12356 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12357 	 * be cached in the conn_t.
12358 	 */
12359 	if (ap->ipa_want_esp) {
12360 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12361 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12362 			    IPPROTO_ESP);
12363 		}
12364 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12365 	}
12366 
12367 	if (ap->ipa_want_ah) {
12368 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12369 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12370 			    IPPROTO_AH);
12371 		}
12372 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12373 		/*
12374 		 * The ESP and AH processing order needs to be preserved
12375 		 * when both protocols are required (ESP should be applied
12376 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12377 		 * when both ESP and AH are required, and an AH ACQUIRE
12378 		 * is needed.
12379 		 */
12380 		if (ap->ipa_want_esp && need_ah_acquire)
12381 			need_esp_acquire = B_TRUE;
12382 	}
12383 
12384 	/*
12385 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12386 	 * Release SAs that got referenced, but will not be used until we
12387 	 * acquire _all_ of the SAs we need.
12388 	 */
12389 	if (need_ah_acquire || need_esp_acquire) {
12390 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12391 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12392 			ixa->ixa_ipsec_ah_sa = NULL;
12393 		}
12394 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12395 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12396 			ixa->ixa_ipsec_esp_sa = NULL;
12397 		}
12398 
12399 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12400 		return (B_FALSE);
12401 	}
12402 
12403 	return (B_TRUE);
12404 }
12405 
12406 /*
12407  * Handle IPsec output processing.
12408  * This function is only entered once for a given packet.
12409  * We try to do things synchronously, but if we need to have user-level
12410  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12411  * will be completed
12412  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12413  *  - when asynchronous ESP is done it will do AH
12414  *
12415  * In all cases we come back in ip_output_post_ipsec() to fragment and
12416  * send out the packet.
12417  */
12418 int
12419 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12420 {
12421 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12422 	ip_stack_t	*ipst = ixa->ixa_ipst;
12423 	ipsec_stack_t	*ipss;
12424 	ipsec_policy_t	*pp;
12425 	ipsec_action_t	*ap;
12426 
12427 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12428 
12429 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12430 	    (ixa->ixa_ipsec_action != NULL));
12431 
12432 	ipss = ipst->ips_netstack->netstack_ipsec;
12433 	if (!ipsec_loaded(ipss)) {
12434 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12435 		ip_drop_packet(mp, B_TRUE, ill,
12436 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12437 		    &ipss->ipsec_dropper);
12438 		return (ENOTSUP);
12439 	}
12440 
12441 	ap = ixa->ixa_ipsec_action;
12442 	if (ap == NULL) {
12443 		pp = ixa->ixa_ipsec_policy;
12444 		ASSERT(pp != NULL);
12445 		ap = pp->ipsp_act;
12446 		ASSERT(ap != NULL);
12447 	}
12448 
12449 	/* Handle explicit drop action and bypass. */
12450 	switch (ap->ipa_act.ipa_type) {
12451 	case IPSEC_ACT_DISCARD:
12452 	case IPSEC_ACT_REJECT:
12453 		ip_drop_packet(mp, B_FALSE, ill,
12454 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12455 		return (EHOSTUNREACH);	/* IPsec policy failure */
12456 	case IPSEC_ACT_BYPASS:
12457 		return (ip_output_post_ipsec(mp, ixa));
12458 	}
12459 
12460 	/*
12461 	 * The order of processing is first insert a IP header if needed.
12462 	 * Then insert the ESP header and then the AH header.
12463 	 */
12464 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12465 		/*
12466 		 * First get the outer IP header before sending
12467 		 * it to ESP.
12468 		 */
12469 		ipha_t *oipha, *iipha;
12470 		mblk_t *outer_mp, *inner_mp;
12471 
12472 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12473 			(void) mi_strlog(ill->ill_rq, 0,
12474 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12475 			    "ipsec_out_process: "
12476 			    "Self-Encapsulation failed: Out of memory\n");
12477 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12478 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12479 			freemsg(mp);
12480 			return (ENOBUFS);
12481 		}
12482 		inner_mp = mp;
12483 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12484 		oipha = (ipha_t *)outer_mp->b_rptr;
12485 		iipha = (ipha_t *)inner_mp->b_rptr;
12486 		*oipha = *iipha;
12487 		outer_mp->b_wptr += sizeof (ipha_t);
12488 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12489 		    sizeof (ipha_t));
12490 		oipha->ipha_protocol = IPPROTO_ENCAP;
12491 		oipha->ipha_version_and_hdr_length =
12492 		    IP_SIMPLE_HDR_VERSION;
12493 		oipha->ipha_hdr_checksum = 0;
12494 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12495 		outer_mp->b_cont = inner_mp;
12496 		mp = outer_mp;
12497 
12498 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12499 	}
12500 
12501 	/* If we need to wait for a SA then we can't return any errno */
12502 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12503 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12504 	    !ipsec_out_select_sa(mp, ixa))
12505 		return (0);
12506 
12507 	/*
12508 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12509 	 * to do the heavy lifting.
12510 	 */
12511 	if (ap->ipa_want_esp) {
12512 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12513 
12514 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12515 		if (mp == NULL) {
12516 			/*
12517 			 * Either it failed or is pending. In the former case
12518 			 * ipIfStatsInDiscards was increased.
12519 			 */
12520 			return (0);
12521 		}
12522 	}
12523 
12524 	if (ap->ipa_want_ah) {
12525 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12526 
12527 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12528 		if (mp == NULL) {
12529 			/*
12530 			 * Either it failed or is pending. In the former case
12531 			 * ipIfStatsInDiscards was increased.
12532 			 */
12533 			return (0);
12534 		}
12535 	}
12536 	/*
12537 	 * We are done with IPsec processing. Send it over
12538 	 * the wire.
12539 	 */
12540 	return (ip_output_post_ipsec(mp, ixa));
12541 }
12542 
12543 /*
12544  * ioctls that go through a down/up sequence may need to wait for the down
12545  * to complete. This involves waiting for the ire and ipif refcnts to go down
12546  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12547  */
12548 /* ARGSUSED */
12549 void
12550 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12551 {
12552 	struct iocblk *iocp;
12553 	mblk_t *mp1;
12554 	ip_ioctl_cmd_t *ipip;
12555 	int err;
12556 	sin_t	*sin;
12557 	struct lifreq *lifr;
12558 	struct ifreq *ifr;
12559 
12560 	iocp = (struct iocblk *)mp->b_rptr;
12561 	ASSERT(ipsq != NULL);
12562 	/* Existence of mp1 verified in ip_wput_nondata */
12563 	mp1 = mp->b_cont->b_cont;
12564 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12565 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12566 		/*
12567 		 * Special case where ipx_current_ipif is not set:
12568 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12569 		 * We are here as were not able to complete the operation in
12570 		 * ipif_set_values because we could not become exclusive on
12571 		 * the new ipsq.
12572 		 */
12573 		ill_t *ill = q->q_ptr;
12574 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12575 	}
12576 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12577 
12578 	if (ipip->ipi_cmd_type == IF_CMD) {
12579 		/* This a old style SIOC[GS]IF* command */
12580 		ifr = (struct ifreq *)mp1->b_rptr;
12581 		sin = (sin_t *)&ifr->ifr_addr;
12582 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12583 		/* This a new style SIOC[GS]LIF* command */
12584 		lifr = (struct lifreq *)mp1->b_rptr;
12585 		sin = (sin_t *)&lifr->lifr_addr;
12586 	} else {
12587 		sin = NULL;
12588 	}
12589 
12590 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12591 	    q, mp, ipip, mp1->b_rptr);
12592 
12593 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12594 	    int, ipip->ipi_cmd,
12595 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12596 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12597 
12598 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12599 }
12600 
12601 /*
12602  * ioctl processing
12603  *
12604  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12605  * the ioctl command in the ioctl tables, determines the copyin data size
12606  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12607  *
12608  * ioctl processing then continues when the M_IOCDATA makes its way down to
12609  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12610  * associated 'conn' is refheld till the end of the ioctl and the general
12611  * ioctl processing function ip_process_ioctl() is called to extract the
12612  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12613  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12614  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12615  * is used to extract the ioctl's arguments.
12616  *
12617  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12618  * so goes thru the serialization primitive ipsq_try_enter. Then the
12619  * appropriate function to handle the ioctl is called based on the entry in
12620  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12621  * which also refreleases the 'conn' that was refheld at the start of the
12622  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12623  *
12624  * Many exclusive ioctls go thru an internal down up sequence as part of
12625  * the operation. For example an attempt to change the IP address of an
12626  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12627  * does all the cleanup such as deleting all ires that use this address.
12628  * Then we need to wait till all references to the interface go away.
12629  */
12630 void
12631 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12632 {
12633 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12634 	ip_ioctl_cmd_t *ipip = arg;
12635 	ip_extract_func_t *extract_funcp;
12636 	cmd_info_t ci;
12637 	int err;
12638 	boolean_t entered_ipsq = B_FALSE;
12639 
12640 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12641 
12642 	if (ipip == NULL)
12643 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12644 
12645 	/*
12646 	 * SIOCLIFADDIF needs to go thru a special path since the
12647 	 * ill may not exist yet. This happens in the case of lo0
12648 	 * which is created using this ioctl.
12649 	 */
12650 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12651 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12652 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12653 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12654 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12655 		return;
12656 	}
12657 
12658 	ci.ci_ipif = NULL;
12659 	switch (ipip->ipi_cmd_type) {
12660 	case MISC_CMD:
12661 	case MSFILT_CMD:
12662 		/*
12663 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12664 		 */
12665 		if (ipip->ipi_cmd == IF_UNITSEL) {
12666 			/* ioctl comes down the ill */
12667 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12668 			ipif_refhold(ci.ci_ipif);
12669 		}
12670 		err = 0;
12671 		ci.ci_sin = NULL;
12672 		ci.ci_sin6 = NULL;
12673 		ci.ci_lifr = NULL;
12674 		extract_funcp = NULL;
12675 		break;
12676 
12677 	case IF_CMD:
12678 	case LIF_CMD:
12679 		extract_funcp = ip_extract_lifreq;
12680 		break;
12681 
12682 	case ARP_CMD:
12683 	case XARP_CMD:
12684 		extract_funcp = ip_extract_arpreq;
12685 		break;
12686 
12687 	default:
12688 		ASSERT(0);
12689 	}
12690 
12691 	if (extract_funcp != NULL) {
12692 		err = (*extract_funcp)(q, mp, ipip, &ci);
12693 		if (err != 0) {
12694 			DTRACE_PROBE4(ipif__ioctl,
12695 			    char *, "ip_process_ioctl finish err",
12696 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12697 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12698 			return;
12699 		}
12700 
12701 		/*
12702 		 * All of the extraction functions return a refheld ipif.
12703 		 */
12704 		ASSERT(ci.ci_ipif != NULL);
12705 	}
12706 
12707 	if (!(ipip->ipi_flags & IPI_WR)) {
12708 		/*
12709 		 * A return value of EINPROGRESS means the ioctl is
12710 		 * either queued and waiting for some reason or has
12711 		 * already completed.
12712 		 */
12713 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12714 		    ci.ci_lifr);
12715 		if (ci.ci_ipif != NULL) {
12716 			DTRACE_PROBE4(ipif__ioctl,
12717 			    char *, "ip_process_ioctl finish RD",
12718 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12719 			    ipif_t *, ci.ci_ipif);
12720 			ipif_refrele(ci.ci_ipif);
12721 		} else {
12722 			DTRACE_PROBE4(ipif__ioctl,
12723 			    char *, "ip_process_ioctl finish RD",
12724 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12725 		}
12726 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12727 		return;
12728 	}
12729 
12730 	ASSERT(ci.ci_ipif != NULL);
12731 
12732 	/*
12733 	 * If ipsq is non-NULL, we are already being called exclusively
12734 	 */
12735 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12736 	if (ipsq == NULL) {
12737 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12738 		    NEW_OP, B_TRUE);
12739 		if (ipsq == NULL) {
12740 			ipif_refrele(ci.ci_ipif);
12741 			return;
12742 		}
12743 		entered_ipsq = B_TRUE;
12744 	}
12745 	/*
12746 	 * Release the ipif so that ipif_down and friends that wait for
12747 	 * references to go away are not misled about the current ipif_refcnt
12748 	 * values. We are writer so we can access the ipif even after releasing
12749 	 * the ipif.
12750 	 */
12751 	ipif_refrele(ci.ci_ipif);
12752 
12753 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12754 
12755 	/*
12756 	 * A return value of EINPROGRESS means the ioctl is
12757 	 * either queued and waiting for some reason or has
12758 	 * already completed.
12759 	 */
12760 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12761 
12762 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12763 	    int, ipip->ipi_cmd,
12764 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12765 	    ipif_t *, ci.ci_ipif);
12766 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12767 
12768 	if (entered_ipsq)
12769 		ipsq_exit(ipsq);
12770 }
12771 
12772 /*
12773  * Complete the ioctl. Typically ioctls use the mi package and need to
12774  * do mi_copyout/mi_copy_done.
12775  */
12776 void
12777 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12778 {
12779 	conn_t	*connp = NULL;
12780 
12781 	if (err == EINPROGRESS)
12782 		return;
12783 
12784 	if (CONN_Q(q)) {
12785 		connp = Q_TO_CONN(q);
12786 		ASSERT(connp->conn_ref >= 2);
12787 	}
12788 
12789 	switch (mode) {
12790 	case COPYOUT:
12791 		if (err == 0)
12792 			mi_copyout(q, mp);
12793 		else
12794 			mi_copy_done(q, mp, err);
12795 		break;
12796 
12797 	case NO_COPYOUT:
12798 		mi_copy_done(q, mp, err);
12799 		break;
12800 
12801 	default:
12802 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12803 		break;
12804 	}
12805 
12806 	/*
12807 	 * The conn refhold and ioctlref placed on the conn at the start of the
12808 	 * ioctl are released here.
12809 	 */
12810 	if (connp != NULL) {
12811 		CONN_DEC_IOCTLREF(connp);
12812 		CONN_OPER_PENDING_DONE(connp);
12813 	}
12814 
12815 	if (ipsq != NULL)
12816 		ipsq_current_finish(ipsq);
12817 }
12818 
12819 /* Handles all non data messages */
12820 void
12821 ip_wput_nondata(queue_t *q, mblk_t *mp)
12822 {
12823 	mblk_t		*mp1;
12824 	struct iocblk	*iocp;
12825 	ip_ioctl_cmd_t	*ipip;
12826 	conn_t		*connp;
12827 	cred_t		*cr;
12828 	char		*proto_str;
12829 
12830 	if (CONN_Q(q))
12831 		connp = Q_TO_CONN(q);
12832 	else
12833 		connp = NULL;
12834 
12835 	switch (DB_TYPE(mp)) {
12836 	case M_IOCTL:
12837 		/*
12838 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12839 		 * will arrange to copy in associated control structures.
12840 		 */
12841 		ip_sioctl_copyin_setup(q, mp);
12842 		return;
12843 	case M_IOCDATA:
12844 		/*
12845 		 * Ensure that this is associated with one of our trans-
12846 		 * parent ioctls.  If it's not ours, discard it if we're
12847 		 * running as a driver, or pass it on if we're a module.
12848 		 */
12849 		iocp = (struct iocblk *)mp->b_rptr;
12850 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12851 		if (ipip == NULL) {
12852 			if (q->q_next == NULL) {
12853 				goto nak;
12854 			} else {
12855 				putnext(q, mp);
12856 			}
12857 			return;
12858 		}
12859 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12860 			/*
12861 			 * The ioctl is one we recognise, but is not consumed
12862 			 * by IP as a module and we are a module, so we drop
12863 			 */
12864 			goto nak;
12865 		}
12866 
12867 		/* IOCTL continuation following copyin or copyout. */
12868 		if (mi_copy_state(q, mp, NULL) == -1) {
12869 			/*
12870 			 * The copy operation failed.  mi_copy_state already
12871 			 * cleaned up, so we're out of here.
12872 			 */
12873 			return;
12874 		}
12875 		/*
12876 		 * If we just completed a copy in, we become writer and
12877 		 * continue processing in ip_sioctl_copyin_done.  If it
12878 		 * was a copy out, we call mi_copyout again.  If there is
12879 		 * nothing more to copy out, it will complete the IOCTL.
12880 		 */
12881 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12882 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12883 				mi_copy_done(q, mp, EPROTO);
12884 				return;
12885 			}
12886 			/*
12887 			 * Check for cases that need more copying.  A return
12888 			 * value of 0 means a second copyin has been started,
12889 			 * so we return; a return value of 1 means no more
12890 			 * copying is needed, so we continue.
12891 			 */
12892 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12893 			    MI_COPY_COUNT(mp) == 1) {
12894 				if (ip_copyin_msfilter(q, mp) == 0)
12895 					return;
12896 			}
12897 			/*
12898 			 * Refhold the conn, till the ioctl completes. This is
12899 			 * needed in case the ioctl ends up in the pending mp
12900 			 * list. Every mp in the ipx_pending_mp list must have
12901 			 * a refhold on the conn to resume processing. The
12902 			 * refhold is released when the ioctl completes
12903 			 * (whether normally or abnormally). An ioctlref is also
12904 			 * placed on the conn to prevent TCP from removing the
12905 			 * queue needed to send the ioctl reply back.
12906 			 * In all cases ip_ioctl_finish is called to finish
12907 			 * the ioctl and release the refholds.
12908 			 */
12909 			if (connp != NULL) {
12910 				/* This is not a reentry */
12911 				CONN_INC_REF(connp);
12912 				CONN_INC_IOCTLREF(connp);
12913 			} else {
12914 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12915 					mi_copy_done(q, mp, EINVAL);
12916 					return;
12917 				}
12918 			}
12919 
12920 			ip_process_ioctl(NULL, q, mp, ipip);
12921 
12922 		} else {
12923 			mi_copyout(q, mp);
12924 		}
12925 		return;
12926 
12927 	case M_IOCNAK:
12928 		/*
12929 		 * The only way we could get here is if a resolver didn't like
12930 		 * an IOCTL we sent it.	 This shouldn't happen.
12931 		 */
12932 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12933 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12934 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12935 		freemsg(mp);
12936 		return;
12937 	case M_IOCACK:
12938 		/* /dev/ip shouldn't see this */
12939 		goto nak;
12940 	case M_FLUSH:
12941 		if (*mp->b_rptr & FLUSHW)
12942 			flushq(q, FLUSHALL);
12943 		if (q->q_next) {
12944 			putnext(q, mp);
12945 			return;
12946 		}
12947 		if (*mp->b_rptr & FLUSHR) {
12948 			*mp->b_rptr &= ~FLUSHW;
12949 			qreply(q, mp);
12950 			return;
12951 		}
12952 		freemsg(mp);
12953 		return;
12954 	case M_CTL:
12955 		break;
12956 	case M_PROTO:
12957 	case M_PCPROTO:
12958 		/*
12959 		 * The only PROTO messages we expect are SNMP-related.
12960 		 */
12961 		switch (((union T_primitives *)mp->b_rptr)->type) {
12962 		case T_SVR4_OPTMGMT_REQ:
12963 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12964 			    "flags %x\n",
12965 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12966 
12967 			if (connp == NULL) {
12968 				proto_str = "T_SVR4_OPTMGMT_REQ";
12969 				goto protonak;
12970 			}
12971 
12972 			/*
12973 			 * All Solaris components should pass a db_credp
12974 			 * for this TPI message, hence we ASSERT.
12975 			 * But in case there is some other M_PROTO that looks
12976 			 * like a TPI message sent by some other kernel
12977 			 * component, we check and return an error.
12978 			 */
12979 			cr = msg_getcred(mp, NULL);
12980 			ASSERT(cr != NULL);
12981 			if (cr == NULL) {
12982 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12983 				if (mp != NULL)
12984 					qreply(q, mp);
12985 				return;
12986 			}
12987 
12988 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12989 				proto_str = "Bad SNMPCOM request?";
12990 				goto protonak;
12991 			}
12992 			return;
12993 		default:
12994 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12995 			    (int)*(uint_t *)mp->b_rptr));
12996 			freemsg(mp);
12997 			return;
12998 		}
12999 	default:
13000 		break;
13001 	}
13002 	if (q->q_next) {
13003 		putnext(q, mp);
13004 	} else
13005 		freemsg(mp);
13006 	return;
13007 
13008 nak:
13009 	iocp->ioc_error = EINVAL;
13010 	mp->b_datap->db_type = M_IOCNAK;
13011 	iocp->ioc_count = 0;
13012 	qreply(q, mp);
13013 	return;
13014 
13015 protonak:
13016 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
13017 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
13018 		qreply(q, mp);
13019 }
13020 
13021 /*
13022  * Process IP options in an outbound packet.  Verify that the nexthop in a
13023  * strict source route is onlink.
13024  * Returns non-zero if something fails in which case an ICMP error has been
13025  * sent and mp freed.
13026  *
13027  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
13028  */
13029 int
13030 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
13031 {
13032 	ipoptp_t	opts;
13033 	uchar_t		*opt;
13034 	uint8_t		optval;
13035 	uint8_t		optlen;
13036 	ipaddr_t	dst;
13037 	intptr_t	code = 0;
13038 	ire_t		*ire;
13039 	ip_stack_t	*ipst = ixa->ixa_ipst;
13040 	ip_recv_attr_t	iras;
13041 
13042 	ip2dbg(("ip_output_options\n"));
13043 
13044 	dst = ipha->ipha_dst;
13045 	for (optval = ipoptp_first(&opts, ipha);
13046 	    optval != IPOPT_EOL;
13047 	    optval = ipoptp_next(&opts)) {
13048 		opt = opts.ipoptp_cur;
13049 		optlen = opts.ipoptp_len;
13050 		ip2dbg(("ip_output_options: opt %d, len %d\n",
13051 		    optval, optlen));
13052 		switch (optval) {
13053 			uint32_t off;
13054 		case IPOPT_SSRR:
13055 		case IPOPT_LSRR:
13056 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13057 				ip1dbg((
13058 				    "ip_output_options: bad option offset\n"));
13059 				code = (char *)&opt[IPOPT_OLEN] -
13060 				    (char *)ipha;
13061 				goto param_prob;
13062 			}
13063 			off = opt[IPOPT_OFFSET];
13064 			ip1dbg(("ip_output_options: next hop 0x%x\n",
13065 			    ntohl(dst)));
13066 			/*
13067 			 * For strict: verify that dst is directly
13068 			 * reachable.
13069 			 */
13070 			if (optval == IPOPT_SSRR) {
13071 				ire = ire_ftable_lookup_v4(dst, 0, 0,
13072 				    IRE_IF_ALL, NULL, ALL_ZONES, ixa->ixa_tsl,
13073 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
13074 				    NULL);
13075 				if (ire == NULL) {
13076 					ip1dbg(("ip_output_options: SSRR not"
13077 					    " directly reachable: 0x%x\n",
13078 					    ntohl(dst)));
13079 					goto bad_src_route;
13080 				}
13081 				ire_refrele(ire);
13082 			}
13083 			break;
13084 		case IPOPT_RR:
13085 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13086 				ip1dbg((
13087 				    "ip_output_options: bad option offset\n"));
13088 				code = (char *)&opt[IPOPT_OLEN] -
13089 				    (char *)ipha;
13090 				goto param_prob;
13091 			}
13092 			break;
13093 		case IPOPT_TS:
13094 			/*
13095 			 * Verify that length >=5 and that there is either
13096 			 * room for another timestamp or that the overflow
13097 			 * counter is not maxed out.
13098 			 */
13099 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
13100 			if (optlen < IPOPT_MINLEN_IT) {
13101 				goto param_prob;
13102 			}
13103 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13104 				ip1dbg((
13105 				    "ip_output_options: bad option offset\n"));
13106 				code = (char *)&opt[IPOPT_OFFSET] -
13107 				    (char *)ipha;
13108 				goto param_prob;
13109 			}
13110 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13111 			case IPOPT_TS_TSONLY:
13112 				off = IPOPT_TS_TIMELEN;
13113 				break;
13114 			case IPOPT_TS_TSANDADDR:
13115 			case IPOPT_TS_PRESPEC:
13116 			case IPOPT_TS_PRESPEC_RFC791:
13117 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13118 				break;
13119 			default:
13120 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
13121 				    (char *)ipha;
13122 				goto param_prob;
13123 			}
13124 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13125 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13126 				/*
13127 				 * No room and the overflow counter is 15
13128 				 * already.
13129 				 */
13130 				goto param_prob;
13131 			}
13132 			break;
13133 		}
13134 	}
13135 
13136 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13137 		return (0);
13138 
13139 	ip1dbg(("ip_output_options: error processing IP options."));
13140 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13141 
13142 param_prob:
13143 	bzero(&iras, sizeof (iras));
13144 	iras.ira_ill = iras.ira_rill = ill;
13145 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13146 	iras.ira_rifindex = iras.ira_ruifindex;
13147 	iras.ira_flags = IRAF_IS_IPV4;
13148 
13149 	ip_drop_output("ip_output_options", mp, ill);
13150 	icmp_param_problem(mp, (uint8_t)code, &iras);
13151 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13152 	return (-1);
13153 
13154 bad_src_route:
13155 	bzero(&iras, sizeof (iras));
13156 	iras.ira_ill = iras.ira_rill = ill;
13157 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13158 	iras.ira_rifindex = iras.ira_ruifindex;
13159 	iras.ira_flags = IRAF_IS_IPV4;
13160 
13161 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13162 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13163 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13164 	return (-1);
13165 }
13166 
13167 /*
13168  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13169  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13170  * thru /etc/system.
13171  */
13172 #define	CONN_MAXDRAINCNT	64
13173 
13174 static void
13175 conn_drain_init(ip_stack_t *ipst)
13176 {
13177 	int i, j;
13178 	idl_tx_list_t *itl_tx;
13179 
13180 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13181 
13182 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
13183 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13184 		/*
13185 		 * Default value of the number of drainers is the
13186 		 * number of cpus, subject to maximum of 8 drainers.
13187 		 */
13188 		if (boot_max_ncpus != -1)
13189 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13190 		else
13191 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13192 	}
13193 
13194 	ipst->ips_idl_tx_list =
13195 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13196 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13197 		itl_tx =  &ipst->ips_idl_tx_list[i];
13198 		itl_tx->txl_drain_list =
13199 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13200 		    sizeof (idl_t), KM_SLEEP);
13201 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13202 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13203 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13204 			    MUTEX_DEFAULT, NULL);
13205 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13206 		}
13207 	}
13208 }
13209 
13210 static void
13211 conn_drain_fini(ip_stack_t *ipst)
13212 {
13213 	int i;
13214 	idl_tx_list_t *itl_tx;
13215 
13216 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13217 		itl_tx =  &ipst->ips_idl_tx_list[i];
13218 		kmem_free(itl_tx->txl_drain_list,
13219 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13220 	}
13221 	kmem_free(ipst->ips_idl_tx_list,
13222 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13223 	ipst->ips_idl_tx_list = NULL;
13224 }
13225 
13226 /*
13227  * Note: For an overview of how flowcontrol is handled in IP please see the
13228  * IP Flowcontrol notes at the top of this file.
13229  *
13230  * Flow control has blocked us from proceeding. Insert the given conn in one
13231  * of the conn drain lists. These conn wq's will be qenabled later on when
13232  * STREAMS flow control does a backenable. conn_walk_drain will enable
13233  * the first conn in each of these drain lists. Each of these qenabled conns
13234  * in turn enables the next in the list, after it runs, or when it closes,
13235  * thus sustaining the drain process.
13236  */
13237 void
13238 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13239 {
13240 	idl_t	*idl = tx_list->txl_drain_list;
13241 	uint_t	index;
13242 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13243 
13244 	mutex_enter(&connp->conn_lock);
13245 	if (connp->conn_state_flags & CONN_CLOSING) {
13246 		/*
13247 		 * The conn is closing as a result of which CONN_CLOSING
13248 		 * is set. Return.
13249 		 */
13250 		mutex_exit(&connp->conn_lock);
13251 		return;
13252 	} else if (connp->conn_idl == NULL) {
13253 		/*
13254 		 * Assign the next drain list round robin. We dont' use
13255 		 * a lock, and thus it may not be strictly round robin.
13256 		 * Atomicity of load/stores is enough to make sure that
13257 		 * conn_drain_list_index is always within bounds.
13258 		 */
13259 		index = tx_list->txl_drain_index;
13260 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13261 		connp->conn_idl = &tx_list->txl_drain_list[index];
13262 		index++;
13263 		if (index == ipst->ips_conn_drain_list_cnt)
13264 			index = 0;
13265 		tx_list->txl_drain_index = index;
13266 	}
13267 	mutex_exit(&connp->conn_lock);
13268 
13269 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
13270 	if ((connp->conn_drain_prev != NULL) ||
13271 	    (connp->conn_state_flags & CONN_CLOSING)) {
13272 		/*
13273 		 * The conn is already in the drain list, OR
13274 		 * the conn is closing. We need to check again for
13275 		 * the closing case again since close can happen
13276 		 * after we drop the conn_lock, and before we
13277 		 * acquire the CONN_DRAIN_LIST_LOCK.
13278 		 */
13279 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
13280 		return;
13281 	} else {
13282 		idl = connp->conn_idl;
13283 	}
13284 
13285 	/*
13286 	 * The conn is not in the drain list. Insert it at the
13287 	 * tail of the drain list. The drain list is circular
13288 	 * and doubly linked. idl_conn points to the 1st element
13289 	 * in the list.
13290 	 */
13291 	if (idl->idl_conn == NULL) {
13292 		idl->idl_conn = connp;
13293 		connp->conn_drain_next = connp;
13294 		connp->conn_drain_prev = connp;
13295 	} else {
13296 		conn_t *head = idl->idl_conn;
13297 
13298 		connp->conn_drain_next = head;
13299 		connp->conn_drain_prev = head->conn_drain_prev;
13300 		head->conn_drain_prev->conn_drain_next = connp;
13301 		head->conn_drain_prev = connp;
13302 	}
13303 	/*
13304 	 * For non streams based sockets assert flow control.
13305 	 */
13306 	conn_setqfull(connp, NULL);
13307 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
13308 }
13309 
13310 static void
13311 conn_idl_remove(conn_t *connp)
13312 {
13313 	idl_t *idl = connp->conn_idl;
13314 
13315 	if (idl != NULL) {
13316 		/*
13317 		 * Remove ourself from the drain list, if we did not do
13318 		 * a putq, or if the conn is closing.
13319 		 * Note: It is possible that q->q_first is non-null. It means
13320 		 * that these messages landed after we did a enableok() in
13321 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
13322 		 * service them.
13323 		 */
13324 		if (connp->conn_drain_next == connp) {
13325 			/* Singleton in the list */
13326 			ASSERT(connp->conn_drain_prev == connp);
13327 			idl->idl_conn = NULL;
13328 		} else {
13329 			connp->conn_drain_prev->conn_drain_next =
13330 			    connp->conn_drain_next;
13331 			connp->conn_drain_next->conn_drain_prev =
13332 			    connp->conn_drain_prev;
13333 			if (idl->idl_conn == connp)
13334 				idl->idl_conn = connp->conn_drain_next;
13335 		}
13336 	}
13337 	connp->conn_drain_next = NULL;
13338 	connp->conn_drain_prev = NULL;
13339 
13340 	conn_clrqfull(connp, NULL);
13341 	/*
13342 	 * For streams based sockets open up flow control.
13343 	 */
13344 	if (!IPCL_IS_NONSTR(connp))
13345 		enableok(connp->conn_wq);
13346 }
13347 
13348 /*
13349  * This conn is closing, and we are called from ip_close. OR
13350  * this conn is draining because flow-control on the ill has been relieved.
13351  *
13352  * We must also need to remove conn's on this idl from the list, and also
13353  * inform the sockfs upcalls about the change in flow-control.
13354  */
13355 static void
13356 conn_drain_tail(conn_t *connp, boolean_t closing)
13357 {
13358 	idl_t *idl;
13359 	conn_t *next_connp;
13360 
13361 	/*
13362 	 * connp->conn_idl is stable at this point, and no lock is needed
13363 	 * to check it. If we are called from ip_close, close has already
13364 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13365 	 * called us only because conn_idl is non-null. If we are called thru
13366 	 * service, conn_idl could be null, but it cannot change because
13367 	 * service is single-threaded per queue, and there cannot be another
13368 	 * instance of service trying to call conn_drain_insert on this conn
13369 	 * now.
13370 	 */
13371 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13372 
13373 	/*
13374 	 * If connp->conn_idl is null, the conn has not been inserted into any
13375 	 * drain list even once since creation of the conn. Just return.
13376 	 */
13377 	if (connp == NULL || connp->conn_idl == NULL)
13378 		return;
13379 
13380 	if (connp->conn_drain_prev == NULL) {
13381 		/* This conn is currently not in the drain list.  */
13382 		return;
13383 	}
13384 	idl = connp->conn_idl;
13385 	if (!closing) {
13386 		/*
13387 		 * This conn is the current drainer. If this is the last conn
13388 		 * in the drain list, we need to do more checks, in the 'if'
13389 		 * below. Otherwwise we need to just qenable the next conn,
13390 		 * to sustain the draining, and is handled in the 'else'
13391 		 * below.
13392 		 */
13393 		next_connp = connp->conn_drain_next;
13394 		while (next_connp != connp) {
13395 			conn_t *delconnp = next_connp;
13396 
13397 			next_connp = next_connp->conn_drain_next;
13398 			conn_idl_remove(delconnp);
13399 		}
13400 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13401 	}
13402 	conn_idl_remove(connp);
13403 
13404 }
13405 
13406 /*
13407  * Write service routine. Shared perimeter entry point.
13408  * The device queue's messages has fallen below the low water mark and STREAMS
13409  * has backenabled the ill_wq. Send sockfs notification about flow-control onx
13410  * each waiting conn.
13411  */
13412 void
13413 ip_wsrv(queue_t *q)
13414 {
13415 	ill_t	*ill;
13416 
13417 	ill = (ill_t *)q->q_ptr;
13418 	if (ill->ill_state_flags == 0) {
13419 		ip_stack_t *ipst = ill->ill_ipst;
13420 
13421 		/*
13422 		 * The device flow control has opened up.
13423 		 * Walk through conn drain lists and qenable the
13424 		 * first conn in each list. This makes sense only
13425 		 * if the stream is fully plumbed and setup.
13426 		 * Hence the ill_state_flags check above.
13427 		 */
13428 		ip1dbg(("ip_wsrv: walking\n"));
13429 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13430 		enableok(ill->ill_wq);
13431 	}
13432 }
13433 
13434 /*
13435  * Callback to disable flow control in IP.
13436  *
13437  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13438  * is enabled.
13439  *
13440  * When MAC_TX() is not able to send any more packets, dld sets its queue
13441  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13442  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13443  * function and wakes up corresponding mac worker threads, which in turn
13444  * calls this callback function, and disables flow control.
13445  */
13446 void
13447 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13448 {
13449 	ill_t *ill = (ill_t *)arg;
13450 	ip_stack_t *ipst = ill->ill_ipst;
13451 	idl_tx_list_t *idl_txl;
13452 
13453 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13454 	mutex_enter(&idl_txl->txl_lock);
13455 	/* add code to to set a flag to indicate idl_txl is enabled */
13456 	conn_walk_drain(ipst, idl_txl);
13457 	mutex_exit(&idl_txl->txl_lock);
13458 }
13459 
13460 /*
13461  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
13462  * of conns that need to be drained, check if drain is already in progress.
13463  * If so set the idl_repeat bit, indicating that the last conn in the list
13464  * needs to reinitiate the drain once again, for the list. If drain is not
13465  * in progress for the list, initiate the draining, by qenabling the 1st
13466  * conn in the list. The drain is self-sustaining, each qenabled conn will
13467  * in turn qenable the next conn, when it is done/blocked/closing.
13468  */
13469 static void
13470 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13471 {
13472 	int i;
13473 	idl_t *idl;
13474 
13475 	IP_STAT(ipst, ip_conn_walk_drain);
13476 
13477 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13478 		idl = &tx_list->txl_drain_list[i];
13479 		mutex_enter(&idl->idl_lock);
13480 		conn_drain_tail(idl->idl_conn, B_FALSE);
13481 		mutex_exit(&idl->idl_lock);
13482 	}
13483 }
13484 
13485 /*
13486  * Determine if the ill and multicast aspects of that packets
13487  * "matches" the conn.
13488  */
13489 boolean_t
13490 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13491 {
13492 	ill_t		*ill = ira->ira_rill;
13493 	zoneid_t	zoneid = ira->ira_zoneid;
13494 	uint_t		in_ifindex;
13495 	ipaddr_t	dst, src;
13496 
13497 	dst = ipha->ipha_dst;
13498 	src = ipha->ipha_src;
13499 
13500 	/*
13501 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13502 	 * unicast, broadcast and multicast reception to
13503 	 * conn_incoming_ifindex.
13504 	 * conn_wantpacket is called for unicast, broadcast and
13505 	 * multicast packets.
13506 	 */
13507 	in_ifindex = connp->conn_incoming_ifindex;
13508 
13509 	/* mpathd can bind to the under IPMP interface, which we allow */
13510 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13511 		if (!IS_UNDER_IPMP(ill))
13512 			return (B_FALSE);
13513 
13514 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13515 			return (B_FALSE);
13516 	}
13517 
13518 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13519 		return (B_FALSE);
13520 
13521 	if (!(ira->ira_flags & IRAF_MULTICAST))
13522 		return (B_TRUE);
13523 
13524 	if (connp->conn_multi_router) {
13525 		/* multicast packet and multicast router socket: send up */
13526 		return (B_TRUE);
13527 	}
13528 
13529 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13530 	    ipha->ipha_protocol == IPPROTO_RSVP)
13531 		return (B_TRUE);
13532 
13533 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13534 }
13535 
13536 void
13537 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13538 {
13539 	if (IPCL_IS_NONSTR(connp)) {
13540 		(*connp->conn_upcalls->su_txq_full)
13541 		    (connp->conn_upper_handle, B_TRUE);
13542 		if (flow_stopped != NULL)
13543 			*flow_stopped = B_TRUE;
13544 	} else {
13545 		queue_t *q = connp->conn_wq;
13546 
13547 		ASSERT(q != NULL);
13548 		if (!(q->q_flag & QFULL)) {
13549 			mutex_enter(QLOCK(q));
13550 			if (!(q->q_flag & QFULL)) {
13551 				/* still need to set QFULL */
13552 				q->q_flag |= QFULL;
13553 				/* set flow_stopped to true under QLOCK */
13554 				if (flow_stopped != NULL)
13555 					*flow_stopped = B_TRUE;
13556 				mutex_exit(QLOCK(q));
13557 			} else {
13558 				/* flow_stopped is left unchanged */
13559 				mutex_exit(QLOCK(q));
13560 			}
13561 		}
13562 	}
13563 }
13564 
13565 void
13566 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13567 {
13568 	if (IPCL_IS_NONSTR(connp)) {
13569 		(*connp->conn_upcalls->su_txq_full)
13570 		    (connp->conn_upper_handle, B_FALSE);
13571 		if (flow_stopped != NULL)
13572 			*flow_stopped = B_FALSE;
13573 	} else {
13574 		queue_t *q = connp->conn_wq;
13575 
13576 		ASSERT(q != NULL);
13577 		if (q->q_flag & QFULL) {
13578 			mutex_enter(QLOCK(q));
13579 			if (q->q_flag & QFULL) {
13580 				q->q_flag &= ~QFULL;
13581 				/* set flow_stopped to false under QLOCK */
13582 				if (flow_stopped != NULL)
13583 					*flow_stopped = B_FALSE;
13584 				mutex_exit(QLOCK(q));
13585 				if (q->q_flag & QWANTW)
13586 					qbackenable(q, 0);
13587 			} else {
13588 				/* flow_stopped is left unchanged */
13589 				mutex_exit(QLOCK(q));
13590 			}
13591 		}
13592 	}
13593 	connp->conn_direct_blocked = B_FALSE;
13594 }
13595 
13596 /*
13597  * Return the length in bytes of the IPv4 headers (base header, label, and
13598  * other IP options) that will be needed based on the
13599  * ip_pkt_t structure passed by the caller.
13600  *
13601  * The returned length does not include the length of the upper level
13602  * protocol (ULP) header.
13603  * The caller needs to check that the length doesn't exceed the max for IPv4.
13604  */
13605 int
13606 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13607 {
13608 	int len;
13609 
13610 	len = IP_SIMPLE_HDR_LENGTH;
13611 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13612 		ASSERT(ipp->ipp_label_len_v4 != 0);
13613 		/* We need to round up here */
13614 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13615 	}
13616 
13617 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13618 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13619 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13620 		len += ipp->ipp_ipv4_options_len;
13621 	}
13622 	return (len);
13623 }
13624 
13625 /*
13626  * All-purpose routine to build an IPv4 header with options based
13627  * on the abstract ip_pkt_t.
13628  *
13629  * The caller has to set the source and destination address as well as
13630  * ipha_length. The caller has to massage any source route and compensate
13631  * for the ULP pseudo-header checksum due to the source route.
13632  */
13633 void
13634 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13635     uint8_t protocol)
13636 {
13637 	ipha_t	*ipha = (ipha_t *)buf;
13638 	uint8_t *cp;
13639 
13640 	/* Initialize IPv4 header */
13641 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13642 	ipha->ipha_length = 0;	/* Caller will set later */
13643 	ipha->ipha_ident = 0;
13644 	ipha->ipha_fragment_offset_and_flags = 0;
13645 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13646 	ipha->ipha_protocol = protocol;
13647 	ipha->ipha_hdr_checksum = 0;
13648 
13649 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13650 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13651 		ipha->ipha_src = ipp->ipp_addr_v4;
13652 
13653 	cp = (uint8_t *)&ipha[1];
13654 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13655 		ASSERT(ipp->ipp_label_len_v4 != 0);
13656 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13657 		cp += ipp->ipp_label_len_v4;
13658 		/* We need to round up here */
13659 		while ((uintptr_t)cp & 0x3) {
13660 			*cp++ = IPOPT_NOP;
13661 		}
13662 	}
13663 
13664 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13665 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13666 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13667 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13668 		cp += ipp->ipp_ipv4_options_len;
13669 	}
13670 	ipha->ipha_version_and_hdr_length =
13671 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13672 
13673 	ASSERT((int)(cp - buf) == buf_len);
13674 }
13675 
13676 /* Allocate the private structure */
13677 static int
13678 ip_priv_alloc(void **bufp)
13679 {
13680 	void	*buf;
13681 
13682 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13683 		return (ENOMEM);
13684 
13685 	*bufp = buf;
13686 	return (0);
13687 }
13688 
13689 /* Function to delete the private structure */
13690 void
13691 ip_priv_free(void *buf)
13692 {
13693 	ASSERT(buf != NULL);
13694 	kmem_free(buf, sizeof (ip_priv_t));
13695 }
13696 
13697 /*
13698  * The entry point for IPPF processing.
13699  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13700  * routine just returns.
13701  *
13702  * When called, ip_process generates an ipp_packet_t structure
13703  * which holds the state information for this packet and invokes the
13704  * the classifier (via ipp_packet_process). The classification, depending on
13705  * configured filters, results in a list of actions for this packet. Invoking
13706  * an action may cause the packet to be dropped, in which case we return NULL.
13707  * proc indicates the callout position for
13708  * this packet and ill is the interface this packet arrived on or will leave
13709  * on (inbound and outbound resp.).
13710  *
13711  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13712  * on the ill corrsponding to the destination IP address.
13713  */
13714 mblk_t *
13715 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13716 {
13717 	ip_priv_t	*priv;
13718 	ipp_action_id_t	aid;
13719 	int		rc = 0;
13720 	ipp_packet_t	*pp;
13721 
13722 	/* If the classifier is not loaded, return  */
13723 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13724 		return (mp);
13725 	}
13726 
13727 	ASSERT(mp != NULL);
13728 
13729 	/* Allocate the packet structure */
13730 	rc = ipp_packet_alloc(&pp, "ip", aid);
13731 	if (rc != 0)
13732 		goto drop;
13733 
13734 	/* Allocate the private structure */
13735 	rc = ip_priv_alloc((void **)&priv);
13736 	if (rc != 0) {
13737 		ipp_packet_free(pp);
13738 		goto drop;
13739 	}
13740 	priv->proc = proc;
13741 	priv->ill_index = ill_get_upper_ifindex(rill);
13742 
13743 	ipp_packet_set_private(pp, priv, ip_priv_free);
13744 	ipp_packet_set_data(pp, mp);
13745 
13746 	/* Invoke the classifier */
13747 	rc = ipp_packet_process(&pp);
13748 	if (pp != NULL) {
13749 		mp = ipp_packet_get_data(pp);
13750 		ipp_packet_free(pp);
13751 		if (rc != 0)
13752 			goto drop;
13753 		return (mp);
13754 	} else {
13755 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13756 		mp = NULL;
13757 	}
13758 drop:
13759 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13760 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13761 		ip_drop_input("ip_process", mp, ill);
13762 	} else {
13763 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13764 		ip_drop_output("ip_process", mp, ill);
13765 	}
13766 	freemsg(mp);
13767 	return (NULL);
13768 }
13769 
13770 /*
13771  * Propagate a multicast group membership operation (add/drop) on
13772  * all the interfaces crossed by the related multirt routes.
13773  * The call is considered successful if the operation succeeds
13774  * on at least one interface.
13775  *
13776  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13777  * multicast addresses with the ire argument being the first one.
13778  * We walk the bucket to find all the of those.
13779  *
13780  * Common to IPv4 and IPv6.
13781  */
13782 static int
13783 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13784     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13785     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13786     mcast_record_t fmode, const in6_addr_t *v6src)
13787 {
13788 	ire_t		*ire_gw;
13789 	irb_t		*irb;
13790 	int		ifindex;
13791 	int		error = 0;
13792 	int		result;
13793 	ip_stack_t	*ipst = ire->ire_ipst;
13794 	ipaddr_t	group;
13795 	boolean_t	isv6;
13796 	int		match_flags;
13797 
13798 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13799 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13800 		isv6 = B_FALSE;
13801 	} else {
13802 		isv6 = B_TRUE;
13803 	}
13804 
13805 	irb = ire->ire_bucket;
13806 	ASSERT(irb != NULL);
13807 
13808 	result = 0;
13809 	irb_refhold(irb);
13810 	for (; ire != NULL; ire = ire->ire_next) {
13811 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13812 			continue;
13813 
13814 		/* We handle -ifp routes by matching on the ill if set */
13815 		match_flags = MATCH_IRE_TYPE;
13816 		if (ire->ire_ill != NULL)
13817 			match_flags |= MATCH_IRE_ILL;
13818 
13819 		if (isv6) {
13820 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13821 				continue;
13822 
13823 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13824 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13825 			    match_flags, 0, ipst, NULL);
13826 		} else {
13827 			if (ire->ire_addr != group)
13828 				continue;
13829 
13830 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13831 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13832 			    match_flags, 0, ipst, NULL);
13833 		}
13834 		/* No interface route exists for the gateway; skip this ire. */
13835 		if (ire_gw == NULL)
13836 			continue;
13837 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13838 			ire_refrele(ire_gw);
13839 			continue;
13840 		}
13841 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13842 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13843 
13844 		/*
13845 		 * The operation is considered a success if
13846 		 * it succeeds at least once on any one interface.
13847 		 */
13848 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13849 		    fmode, v6src);
13850 		if (error == 0)
13851 			result = CGTP_MCAST_SUCCESS;
13852 
13853 		ire_refrele(ire_gw);
13854 	}
13855 	irb_refrele(irb);
13856 	/*
13857 	 * Consider the call as successful if we succeeded on at least
13858 	 * one interface. Otherwise, return the last encountered error.
13859 	 */
13860 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13861 }
13862 
13863 /*
13864  * Get the CGTP (multirouting) filtering status.
13865  * If 0, the CGTP hooks are transparent.
13866  */
13867 /* ARGSUSED */
13868 static int
13869 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
13870 {
13871 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
13872 
13873 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
13874 	return (0);
13875 }
13876 
13877 /*
13878  * Set the CGTP (multirouting) filtering status.
13879  * If the status is changed from active to transparent
13880  * or from transparent to active, forward the new status
13881  * to the filtering module (if loaded).
13882  */
13883 /* ARGSUSED */
13884 static int
13885 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
13886     cred_t *ioc_cr)
13887 {
13888 	long		new_value;
13889 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
13890 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
13891 
13892 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
13893 		return (EPERM);
13894 
13895 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
13896 	    new_value < 0 || new_value > 1) {
13897 		return (EINVAL);
13898 	}
13899 
13900 	if ((!*ip_cgtp_filter_value) && new_value) {
13901 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
13902 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
13903 		    " (module not loaded)" : "");
13904 	}
13905 	if (*ip_cgtp_filter_value && (!new_value)) {
13906 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
13907 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
13908 		    " (module not loaded)" : "");
13909 	}
13910 
13911 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13912 		int	res;
13913 		netstackid_t stackid;
13914 
13915 		stackid = ipst->ips_netstack->netstack_stackid;
13916 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
13917 		    new_value);
13918 		if (res)
13919 			return (res);
13920 	}
13921 
13922 	*ip_cgtp_filter_value = (boolean_t)new_value;
13923 
13924 	ill_set_inputfn_all(ipst);
13925 	return (0);
13926 }
13927 
13928 /*
13929  * Return the expected CGTP hooks version number.
13930  */
13931 int
13932 ip_cgtp_filter_supported(void)
13933 {
13934 	return (ip_cgtp_filter_rev);
13935 }
13936 
13937 /*
13938  * CGTP hooks can be registered by invoking this function.
13939  * Checks that the version number matches.
13940  */
13941 int
13942 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13943 {
13944 	netstack_t *ns;
13945 	ip_stack_t *ipst;
13946 
13947 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13948 		return (ENOTSUP);
13949 
13950 	ns = netstack_find_by_stackid(stackid);
13951 	if (ns == NULL)
13952 		return (EINVAL);
13953 	ipst = ns->netstack_ip;
13954 	ASSERT(ipst != NULL);
13955 
13956 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13957 		netstack_rele(ns);
13958 		return (EALREADY);
13959 	}
13960 
13961 	ipst->ips_ip_cgtp_filter_ops = ops;
13962 
13963 	ill_set_inputfn_all(ipst);
13964 
13965 	netstack_rele(ns);
13966 	return (0);
13967 }
13968 
13969 /*
13970  * CGTP hooks can be unregistered by invoking this function.
13971  * Returns ENXIO if there was no registration.
13972  * Returns EBUSY if the ndd variable has not been turned off.
13973  */
13974 int
13975 ip_cgtp_filter_unregister(netstackid_t stackid)
13976 {
13977 	netstack_t *ns;
13978 	ip_stack_t *ipst;
13979 
13980 	ns = netstack_find_by_stackid(stackid);
13981 	if (ns == NULL)
13982 		return (EINVAL);
13983 	ipst = ns->netstack_ip;
13984 	ASSERT(ipst != NULL);
13985 
13986 	if (ipst->ips_ip_cgtp_filter) {
13987 		netstack_rele(ns);
13988 		return (EBUSY);
13989 	}
13990 
13991 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13992 		netstack_rele(ns);
13993 		return (ENXIO);
13994 	}
13995 	ipst->ips_ip_cgtp_filter_ops = NULL;
13996 
13997 	ill_set_inputfn_all(ipst);
13998 
13999 	netstack_rele(ns);
14000 	return (0);
14001 }
14002 
14003 /*
14004  * Check whether there is a CGTP filter registration.
14005  * Returns non-zero if there is a registration, otherwise returns zero.
14006  * Note: returns zero if bad stackid.
14007  */
14008 int
14009 ip_cgtp_filter_is_registered(netstackid_t stackid)
14010 {
14011 	netstack_t *ns;
14012 	ip_stack_t *ipst;
14013 	int ret;
14014 
14015 	ns = netstack_find_by_stackid(stackid);
14016 	if (ns == NULL)
14017 		return (0);
14018 	ipst = ns->netstack_ip;
14019 	ASSERT(ipst != NULL);
14020 
14021 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
14022 		ret = 1;
14023 	else
14024 		ret = 0;
14025 
14026 	netstack_rele(ns);
14027 	return (ret);
14028 }
14029 
14030 static int
14031 ip_squeue_switch(int val)
14032 {
14033 	int rval;
14034 
14035 	switch (val) {
14036 	case IP_SQUEUE_ENTER_NODRAIN:
14037 		rval = SQ_NODRAIN;
14038 		break;
14039 	case IP_SQUEUE_ENTER:
14040 		rval = SQ_PROCESS;
14041 		break;
14042 	case IP_SQUEUE_FILL:
14043 	default:
14044 		rval = SQ_FILL;
14045 		break;
14046 	}
14047 	return (rval);
14048 }
14049 
14050 /* ARGSUSED */
14051 static int
14052 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
14053     caddr_t addr, cred_t *cr)
14054 {
14055 	int *v = (int *)addr;
14056 	long new_value;
14057 
14058 	if (secpolicy_net_config(cr, B_FALSE) != 0)
14059 		return (EPERM);
14060 
14061 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
14062 		return (EINVAL);
14063 
14064 	ip_squeue_flag = ip_squeue_switch(new_value);
14065 	*v = new_value;
14066 	return (0);
14067 }
14068 
14069 /*
14070  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
14071  * ip_debug.
14072  */
14073 /* ARGSUSED */
14074 static int
14075 ip_int_set(queue_t *q, mblk_t *mp, char *value,
14076     caddr_t addr, cred_t *cr)
14077 {
14078 	int *v = (int *)addr;
14079 	long new_value;
14080 
14081 	if (secpolicy_net_config(cr, B_FALSE) != 0)
14082 		return (EPERM);
14083 
14084 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
14085 		return (EINVAL);
14086 
14087 	*v = new_value;
14088 	return (0);
14089 }
14090 
14091 static void *
14092 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
14093 {
14094 	kstat_t *ksp;
14095 
14096 	ip_stat_t template = {
14097 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
14098 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
14099 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
14100 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
14101 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
14102 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
14103 		{ "ip_opt",			KSTAT_DATA_UINT64 },
14104 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
14105 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
14106 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
14107 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
14108 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
14109 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
14110 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
14111 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
14112 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
14113 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
14114 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
14115 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
14116 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
14117 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
14118 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
14119 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
14120 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
14121 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
14122 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
14123 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
14124 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
14125 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
14126 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
14127 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
14128 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
14129 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
14130 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
14131 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
14132 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
14133 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
14134 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
14135 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
14136 	};
14137 
14138 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
14139 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
14140 	    KSTAT_FLAG_VIRTUAL, stackid);
14141 
14142 	if (ksp == NULL)
14143 		return (NULL);
14144 
14145 	bcopy(&template, ip_statisticsp, sizeof (template));
14146 	ksp->ks_data = (void *)ip_statisticsp;
14147 	ksp->ks_private = (void *)(uintptr_t)stackid;
14148 
14149 	kstat_install(ksp);
14150 	return (ksp);
14151 }
14152 
14153 static void
14154 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
14155 {
14156 	if (ksp != NULL) {
14157 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14158 		kstat_delete_netstack(ksp, stackid);
14159 	}
14160 }
14161 
14162 static void *
14163 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
14164 {
14165 	kstat_t	*ksp;
14166 
14167 	ip_named_kstat_t template = {
14168 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
14169 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
14170 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
14171 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
14172 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
14173 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
14174 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
14175 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
14176 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
14177 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
14178 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
14179 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
14180 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
14181 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
14182 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
14183 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
14184 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
14185 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
14186 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
14187 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
14188 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
14189 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
14190 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
14191 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
14192 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
14193 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
14194 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
14195 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
14196 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
14197 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
14198 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
14199 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
14200 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
14201 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
14202 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
14203 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
14204 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
14205 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
14206 	};
14207 
14208 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
14209 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
14210 	if (ksp == NULL || ksp->ks_data == NULL)
14211 		return (NULL);
14212 
14213 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
14214 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
14215 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
14216 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
14217 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14218 
14219 	template.netToMediaEntrySize.value.i32 =
14220 	    sizeof (mib2_ipNetToMediaEntry_t);
14221 
14222 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14223 
14224 	bcopy(&template, ksp->ks_data, sizeof (template));
14225 	ksp->ks_update = ip_kstat_update;
14226 	ksp->ks_private = (void *)(uintptr_t)stackid;
14227 
14228 	kstat_install(ksp);
14229 	return (ksp);
14230 }
14231 
14232 static void
14233 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14234 {
14235 	if (ksp != NULL) {
14236 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14237 		kstat_delete_netstack(ksp, stackid);
14238 	}
14239 }
14240 
14241 static int
14242 ip_kstat_update(kstat_t *kp, int rw)
14243 {
14244 	ip_named_kstat_t *ipkp;
14245 	mib2_ipIfStatsEntry_t ipmib;
14246 	ill_walk_context_t ctx;
14247 	ill_t *ill;
14248 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14249 	netstack_t	*ns;
14250 	ip_stack_t	*ipst;
14251 
14252 	if (kp == NULL || kp->ks_data == NULL)
14253 		return (EIO);
14254 
14255 	if (rw == KSTAT_WRITE)
14256 		return (EACCES);
14257 
14258 	ns = netstack_find_by_stackid(stackid);
14259 	if (ns == NULL)
14260 		return (-1);
14261 	ipst = ns->netstack_ip;
14262 	if (ipst == NULL) {
14263 		netstack_rele(ns);
14264 		return (-1);
14265 	}
14266 	ipkp = (ip_named_kstat_t *)kp->ks_data;
14267 
14268 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14269 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14270 	ill = ILL_START_WALK_V4(&ctx, ipst);
14271 	for (; ill != NULL; ill = ill_next(&ctx, ill))
14272 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14273 	rw_exit(&ipst->ips_ill_g_lock);
14274 
14275 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
14276 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
14277 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
14278 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
14279 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
14280 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14281 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
14282 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
14283 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
14284 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
14285 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
14286 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
14287 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
14288 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
14289 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
14290 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
14291 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
14292 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
14293 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
14294 
14295 	ipkp->routingDiscards.value.ui32 =	0;
14296 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
14297 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
14298 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
14299 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
14300 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
14301 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
14302 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
14303 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
14304 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
14305 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
14306 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
14307 
14308 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
14309 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
14310 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14311 
14312 	netstack_rele(ns);
14313 
14314 	return (0);
14315 }
14316 
14317 static void *
14318 icmp_kstat_init(netstackid_t stackid)
14319 {
14320 	kstat_t	*ksp;
14321 
14322 	icmp_named_kstat_t template = {
14323 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14324 		{ "inErrors",		KSTAT_DATA_UINT32 },
14325 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14326 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14327 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14328 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14329 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14330 		{ "inEchos",		KSTAT_DATA_UINT32 },
14331 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14332 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14333 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14334 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14335 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14336 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14337 		{ "outErrors",		KSTAT_DATA_UINT32 },
14338 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14339 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14340 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14341 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14342 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14343 		{ "outEchos",		KSTAT_DATA_UINT32 },
14344 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14345 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14346 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14347 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14348 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14349 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14350 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14351 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14352 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14353 		{ "outDrops",		KSTAT_DATA_UINT32 },
14354 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14355 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14356 	};
14357 
14358 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14359 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14360 	if (ksp == NULL || ksp->ks_data == NULL)
14361 		return (NULL);
14362 
14363 	bcopy(&template, ksp->ks_data, sizeof (template));
14364 
14365 	ksp->ks_update = icmp_kstat_update;
14366 	ksp->ks_private = (void *)(uintptr_t)stackid;
14367 
14368 	kstat_install(ksp);
14369 	return (ksp);
14370 }
14371 
14372 static void
14373 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14374 {
14375 	if (ksp != NULL) {
14376 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14377 		kstat_delete_netstack(ksp, stackid);
14378 	}
14379 }
14380 
14381 static int
14382 icmp_kstat_update(kstat_t *kp, int rw)
14383 {
14384 	icmp_named_kstat_t *icmpkp;
14385 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14386 	netstack_t	*ns;
14387 	ip_stack_t	*ipst;
14388 
14389 	if ((kp == NULL) || (kp->ks_data == NULL))
14390 		return (EIO);
14391 
14392 	if (rw == KSTAT_WRITE)
14393 		return (EACCES);
14394 
14395 	ns = netstack_find_by_stackid(stackid);
14396 	if (ns == NULL)
14397 		return (-1);
14398 	ipst = ns->netstack_ip;
14399 	if (ipst == NULL) {
14400 		netstack_rele(ns);
14401 		return (-1);
14402 	}
14403 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14404 
14405 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14406 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14407 	icmpkp->inDestUnreachs.value.ui32 =
14408 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14409 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14410 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14411 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14412 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14413 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14414 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14415 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14416 	icmpkp->inTimestampReps.value.ui32 =
14417 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14418 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14419 	icmpkp->inAddrMaskReps.value.ui32 =
14420 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14421 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14422 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14423 	icmpkp->outDestUnreachs.value.ui32 =
14424 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14425 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14426 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14427 	icmpkp->outSrcQuenchs.value.ui32 =
14428 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14429 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14430 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14431 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14432 	icmpkp->outTimestamps.value.ui32 =
14433 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14434 	icmpkp->outTimestampReps.value.ui32 =
14435 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14436 	icmpkp->outAddrMasks.value.ui32 =
14437 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14438 	icmpkp->outAddrMaskReps.value.ui32 =
14439 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14440 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14441 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14442 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14443 	icmpkp->outFragNeeded.value.ui32 =
14444 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14445 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14446 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14447 	icmpkp->inBadRedirects.value.ui32 =
14448 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14449 
14450 	netstack_rele(ns);
14451 	return (0);
14452 }
14453 
14454 /*
14455  * This is the fanout function for raw socket opened for SCTP.  Note
14456  * that it is called after SCTP checks that there is no socket which
14457  * wants a packet.  Then before SCTP handles this out of the blue packet,
14458  * this function is called to see if there is any raw socket for SCTP.
14459  * If there is and it is bound to the correct address, the packet will
14460  * be sent to that socket.  Note that only one raw socket can be bound to
14461  * a port.  This is assured in ipcl_sctp_hash_insert();
14462  */
14463 void
14464 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14465     ip_recv_attr_t *ira)
14466 {
14467 	conn_t		*connp;
14468 	queue_t		*rq;
14469 	boolean_t	secure;
14470 	ill_t		*ill = ira->ira_ill;
14471 	ip_stack_t	*ipst = ill->ill_ipst;
14472 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14473 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14474 	iaflags_t	iraflags = ira->ira_flags;
14475 	ill_t		*rill = ira->ira_rill;
14476 
14477 	secure = iraflags & IRAF_IPSEC_SECURE;
14478 
14479 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14480 	    ira, ipst);
14481 	if (connp == NULL) {
14482 		/*
14483 		 * Although raw sctp is not summed, OOB chunks must be.
14484 		 * Drop the packet here if the sctp checksum failed.
14485 		 */
14486 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14487 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
14488 			freemsg(mp);
14489 			return;
14490 		}
14491 		ira->ira_ill = ira->ira_rill = NULL;
14492 		sctp_ootb_input(mp, ira, ipst);
14493 		ira->ira_ill = ill;
14494 		ira->ira_rill = rill;
14495 		return;
14496 	}
14497 	rq = connp->conn_rq;
14498 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14499 		CONN_DEC_REF(connp);
14500 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14501 		freemsg(mp);
14502 		return;
14503 	}
14504 	if (((iraflags & IRAF_IS_IPV4) ?
14505 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14506 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14507 	    secure) {
14508 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14509 		    ip6h, ira);
14510 		if (mp == NULL) {
14511 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14512 			/* Note that mp is NULL */
14513 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14514 			CONN_DEC_REF(connp);
14515 			return;
14516 		}
14517 	}
14518 
14519 	if (iraflags & IRAF_ICMP_ERROR) {
14520 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14521 	} else {
14522 		ill_t *rill = ira->ira_rill;
14523 
14524 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14525 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14526 		ira->ira_ill = ira->ira_rill = NULL;
14527 		(connp->conn_recv)(connp, mp, NULL, ira);
14528 		ira->ira_ill = ill;
14529 		ira->ira_rill = rill;
14530 	}
14531 	CONN_DEC_REF(connp);
14532 }
14533 
14534 /*
14535  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14536  * header before the ip payload.
14537  */
14538 static void
14539 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14540 {
14541 	int len = (mp->b_wptr - mp->b_rptr);
14542 	mblk_t *ip_mp;
14543 
14544 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14545 	if (is_fp_mp || len != fp_mp_len) {
14546 		if (len > fp_mp_len) {
14547 			/*
14548 			 * fastpath header and ip header in the first mblk
14549 			 */
14550 			mp->b_rptr += fp_mp_len;
14551 		} else {
14552 			/*
14553 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14554 			 * attach the fastpath header before ip header.
14555 			 */
14556 			ip_mp = mp->b_cont;
14557 			freeb(mp);
14558 			mp = ip_mp;
14559 			mp->b_rptr += (fp_mp_len - len);
14560 		}
14561 	} else {
14562 		ip_mp = mp->b_cont;
14563 		freeb(mp);
14564 		mp = ip_mp;
14565 	}
14566 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14567 	freemsg(mp);
14568 }
14569 
14570 /*
14571  * Normal post fragmentation function.
14572  *
14573  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14574  * using the same state machine.
14575  *
14576  * We return an error on failure. In particular we return EWOULDBLOCK
14577  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14578  * (currently by canputnext failure resulting in backenabling from GLD.)
14579  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14580  * indication that they can flow control until ip_wsrv() tells then to restart.
14581  *
14582  * If the nce passed by caller is incomplete, this function
14583  * queues the packet and if necessary, sends ARP request and bails.
14584  * If the Neighbor Cache passed is fully resolved, we simply prepend
14585  * the link-layer header to the packet, do ipsec hw acceleration
14586  * work if necessary, and send the packet out on the wire.
14587  */
14588 /* ARGSUSED6 */
14589 int
14590 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14591     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14592 {
14593 	queue_t		*wq;
14594 	ill_t		*ill = nce->nce_ill;
14595 	ip_stack_t	*ipst = ill->ill_ipst;
14596 	uint64_t	delta;
14597 	boolean_t	isv6 = ill->ill_isv6;
14598 	boolean_t	fp_mp;
14599 	ncec_t		*ncec = nce->nce_common;
14600 	int64_t		now = LBOLT_FASTPATH64;
14601 	boolean_t	is_probe;
14602 
14603 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14604 
14605 	ASSERT(mp != NULL);
14606 	ASSERT(mp->b_datap->db_type == M_DATA);
14607 	ASSERT(pkt_len == msgdsize(mp));
14608 
14609 	/*
14610 	 * If we have already been here and are coming back after ARP/ND.
14611 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14612 	 * in that case since they have seen the packet when it came here
14613 	 * the first time.
14614 	 */
14615 	if (ixaflags & IXAF_NO_TRACE)
14616 		goto sendit;
14617 
14618 	if (ixaflags & IXAF_IS_IPV4) {
14619 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14620 
14621 		ASSERT(!isv6);
14622 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14623 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14624 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14625 			int	error;
14626 
14627 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14628 			    ipst->ips_ipv4firewall_physical_out,
14629 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14630 			DTRACE_PROBE1(ip4__physical__out__end,
14631 			    mblk_t *, mp);
14632 			if (mp == NULL)
14633 				return (error);
14634 
14635 			/* The length could have changed */
14636 			pkt_len = msgdsize(mp);
14637 		}
14638 		if (ipst->ips_ip4_observe.he_interested) {
14639 			/*
14640 			 * Note that for TX the zoneid is the sending
14641 			 * zone, whether or not MLP is in play.
14642 			 * Since the szone argument is the IP zoneid (i.e.,
14643 			 * zero for exclusive-IP zones) and ipobs wants
14644 			 * the system zoneid, we map it here.
14645 			 */
14646 			szone = IP_REAL_ZONEID(szone, ipst);
14647 
14648 			/*
14649 			 * On the outbound path the destination zone will be
14650 			 * unknown as we're sending this packet out on the
14651 			 * wire.
14652 			 */
14653 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14654 			    ill, ipst);
14655 		}
14656 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14657 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14658 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14659 	} else {
14660 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14661 
14662 		ASSERT(isv6);
14663 		ASSERT(pkt_len ==
14664 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14665 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14666 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14667 			int	error;
14668 
14669 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14670 			    ipst->ips_ipv6firewall_physical_out,
14671 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14672 			DTRACE_PROBE1(ip6__physical__out__end,
14673 			    mblk_t *, mp);
14674 			if (mp == NULL)
14675 				return (error);
14676 
14677 			/* The length could have changed */
14678 			pkt_len = msgdsize(mp);
14679 		}
14680 		if (ipst->ips_ip6_observe.he_interested) {
14681 			/* See above */
14682 			szone = IP_REAL_ZONEID(szone, ipst);
14683 
14684 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14685 			    ill, ipst);
14686 		}
14687 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14688 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14689 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14690 	}
14691 
14692 sendit:
14693 	/*
14694 	 * We check the state without a lock because the state can never
14695 	 * move "backwards" to initial or incomplete.
14696 	 */
14697 	switch (ncec->ncec_state) {
14698 	case ND_REACHABLE:
14699 	case ND_STALE:
14700 	case ND_DELAY:
14701 	case ND_PROBE:
14702 		mp = ip_xmit_attach_llhdr(mp, nce);
14703 		if (mp == NULL) {
14704 			/*
14705 			 * ip_xmit_attach_llhdr has increased
14706 			 * ipIfStatsOutDiscards and called ip_drop_output()
14707 			 */
14708 			return (ENOBUFS);
14709 		}
14710 		/*
14711 		 * check if nce_fastpath completed and we tagged on a
14712 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14713 		 */
14714 		fp_mp = (mp->b_datap->db_type == M_DATA);
14715 
14716 		if (fp_mp &&
14717 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14718 			ill_dld_direct_t *idd;
14719 
14720 			idd = &ill->ill_dld_capab->idc_direct;
14721 			/*
14722 			 * Send the packet directly to DLD, where it
14723 			 * may be queued depending on the availability
14724 			 * of transmit resources at the media layer.
14725 			 * Return value should be taken into
14726 			 * account and flow control the TCP.
14727 			 */
14728 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14729 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14730 			    pkt_len);
14731 
14732 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14733 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14734 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14735 			} else {
14736 				uintptr_t cookie;
14737 
14738 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14739 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14740 					if (ixacookie != NULL)
14741 						*ixacookie = cookie;
14742 					return (EWOULDBLOCK);
14743 				}
14744 			}
14745 		} else {
14746 			wq = ill->ill_wq;
14747 
14748 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14749 			    !canputnext(wq)) {
14750 				if (ixacookie != NULL)
14751 					*ixacookie = 0;
14752 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14753 				    nce->nce_fp_mp != NULL ?
14754 				    MBLKL(nce->nce_fp_mp) : 0);
14755 				return (EWOULDBLOCK);
14756 			}
14757 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14758 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14759 			    pkt_len);
14760 			putnext(wq, mp);
14761 		}
14762 
14763 		/*
14764 		 * The rest of this function implements Neighbor Unreachability
14765 		 * detection. Determine if the ncec is eligible for NUD.
14766 		 */
14767 		if (ncec->ncec_flags & NCE_F_NONUD)
14768 			return (0);
14769 
14770 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14771 
14772 		/*
14773 		 * Check for upper layer advice
14774 		 */
14775 		if (ixaflags & IXAF_REACH_CONF) {
14776 			timeout_id_t tid;
14777 
14778 			/*
14779 			 * It should be o.k. to check the state without
14780 			 * a lock here, at most we lose an advice.
14781 			 */
14782 			ncec->ncec_last = TICK_TO_MSEC(now);
14783 			if (ncec->ncec_state != ND_REACHABLE) {
14784 				mutex_enter(&ncec->ncec_lock);
14785 				ncec->ncec_state = ND_REACHABLE;
14786 				tid = ncec->ncec_timeout_id;
14787 				ncec->ncec_timeout_id = 0;
14788 				mutex_exit(&ncec->ncec_lock);
14789 				(void) untimeout(tid);
14790 				if (ip_debug > 2) {
14791 					/* ip1dbg */
14792 					pr_addr_dbg("ip_xmit: state"
14793 					    " for %s changed to"
14794 					    " REACHABLE\n", AF_INET6,
14795 					    &ncec->ncec_addr);
14796 				}
14797 			}
14798 			return (0);
14799 		}
14800 
14801 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14802 		ip1dbg(("ip_xmit: delta = %" PRId64
14803 		    " ill_reachable_time = %d \n", delta,
14804 		    ill->ill_reachable_time));
14805 		if (delta > (uint64_t)ill->ill_reachable_time) {
14806 			mutex_enter(&ncec->ncec_lock);
14807 			switch (ncec->ncec_state) {
14808 			case ND_REACHABLE:
14809 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14810 				/* FALLTHROUGH */
14811 			case ND_STALE:
14812 				/*
14813 				 * ND_REACHABLE is identical to
14814 				 * ND_STALE in this specific case. If
14815 				 * reachable time has expired for this
14816 				 * neighbor (delta is greater than
14817 				 * reachable time), conceptually, the
14818 				 * neighbor cache is no longer in
14819 				 * REACHABLE state, but already in
14820 				 * STALE state.  So the correct
14821 				 * transition here is to ND_DELAY.
14822 				 */
14823 				ncec->ncec_state = ND_DELAY;
14824 				mutex_exit(&ncec->ncec_lock);
14825 				nce_restart_timer(ncec,
14826 				    ipst->ips_delay_first_probe_time);
14827 				if (ip_debug > 3) {
14828 					/* ip2dbg */
14829 					pr_addr_dbg("ip_xmit: state"
14830 					    " for %s changed to"
14831 					    " DELAY\n", AF_INET6,
14832 					    &ncec->ncec_addr);
14833 				}
14834 				break;
14835 			case ND_DELAY:
14836 			case ND_PROBE:
14837 				mutex_exit(&ncec->ncec_lock);
14838 				/* Timers have already started */
14839 				break;
14840 			case ND_UNREACHABLE:
14841 				/*
14842 				 * nce_timer has detected that this ncec
14843 				 * is unreachable and initiated deleting
14844 				 * this ncec.
14845 				 * This is a harmless race where we found the
14846 				 * ncec before it was deleted and have
14847 				 * just sent out a packet using this
14848 				 * unreachable ncec.
14849 				 */
14850 				mutex_exit(&ncec->ncec_lock);
14851 				break;
14852 			default:
14853 				ASSERT(0);
14854 				mutex_exit(&ncec->ncec_lock);
14855 			}
14856 		}
14857 		return (0);
14858 
14859 	case ND_INCOMPLETE:
14860 		/*
14861 		 * the state could have changed since we didn't hold the lock.
14862 		 * Re-verify state under lock.
14863 		 */
14864 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14865 		mutex_enter(&ncec->ncec_lock);
14866 		if (NCE_ISREACHABLE(ncec)) {
14867 			mutex_exit(&ncec->ncec_lock);
14868 			goto sendit;
14869 		}
14870 		/* queue the packet */
14871 		nce_queue_mp(ncec, mp, is_probe);
14872 		mutex_exit(&ncec->ncec_lock);
14873 		DTRACE_PROBE2(ip__xmit__incomplete,
14874 		    (ncec_t *), ncec, (mblk_t *), mp);
14875 		return (0);
14876 
14877 	case ND_INITIAL:
14878 		/*
14879 		 * State could have changed since we didn't hold the lock, so
14880 		 * re-verify state.
14881 		 */
14882 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14883 		mutex_enter(&ncec->ncec_lock);
14884 		if (NCE_ISREACHABLE(ncec))  {
14885 			mutex_exit(&ncec->ncec_lock);
14886 			goto sendit;
14887 		}
14888 		nce_queue_mp(ncec, mp, is_probe);
14889 		if (ncec->ncec_state == ND_INITIAL) {
14890 			ncec->ncec_state = ND_INCOMPLETE;
14891 			mutex_exit(&ncec->ncec_lock);
14892 			/*
14893 			 * figure out the source we want to use
14894 			 * and resolve it.
14895 			 */
14896 			ip_ndp_resolve(ncec);
14897 		} else  {
14898 			mutex_exit(&ncec->ncec_lock);
14899 		}
14900 		return (0);
14901 
14902 	case ND_UNREACHABLE:
14903 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14904 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14905 		    mp, ill);
14906 		freemsg(mp);
14907 		return (0);
14908 
14909 	default:
14910 		ASSERT(0);
14911 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14912 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14913 		    mp, ill);
14914 		freemsg(mp);
14915 		return (ENETUNREACH);
14916 	}
14917 }
14918 
14919 /*
14920  * Return B_TRUE if the buffers differ in length or content.
14921  * This is used for comparing extension header buffers.
14922  * Note that an extension header would be declared different
14923  * even if all that changed was the next header value in that header i.e.
14924  * what really changed is the next extension header.
14925  */
14926 boolean_t
14927 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14928     uint_t blen)
14929 {
14930 	if (!b_valid)
14931 		blen = 0;
14932 
14933 	if (alen != blen)
14934 		return (B_TRUE);
14935 	if (alen == 0)
14936 		return (B_FALSE);	/* Both zero length */
14937 	return (bcmp(abuf, bbuf, alen));
14938 }
14939 
14940 /*
14941  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14942  * Return B_FALSE if memory allocation fails - don't change any state!
14943  */
14944 boolean_t
14945 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14946     const void *src, uint_t srclen)
14947 {
14948 	void *dst;
14949 
14950 	if (!src_valid)
14951 		srclen = 0;
14952 
14953 	ASSERT(*dstlenp == 0);
14954 	if (src != NULL && srclen != 0) {
14955 		dst = mi_alloc(srclen, BPRI_MED);
14956 		if (dst == NULL)
14957 			return (B_FALSE);
14958 	} else {
14959 		dst = NULL;
14960 	}
14961 	if (*dstp != NULL)
14962 		mi_free(*dstp);
14963 	*dstp = dst;
14964 	*dstlenp = dst == NULL ? 0 : srclen;
14965 	return (B_TRUE);
14966 }
14967 
14968 /*
14969  * Replace what is in *dst, *dstlen with the source.
14970  * Assumes ip_allocbuf has already been called.
14971  */
14972 void
14973 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14974     const void *src, uint_t srclen)
14975 {
14976 	if (!src_valid)
14977 		srclen = 0;
14978 
14979 	ASSERT(*dstlenp == srclen);
14980 	if (src != NULL && srclen != 0)
14981 		bcopy(src, *dstp, srclen);
14982 }
14983 
14984 /*
14985  * Free the storage pointed to by the members of an ip_pkt_t.
14986  */
14987 void
14988 ip_pkt_free(ip_pkt_t *ipp)
14989 {
14990 	uint_t	fields = ipp->ipp_fields;
14991 
14992 	if (fields & IPPF_HOPOPTS) {
14993 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14994 		ipp->ipp_hopopts = NULL;
14995 		ipp->ipp_hopoptslen = 0;
14996 	}
14997 	if (fields & IPPF_RTHDRDSTOPTS) {
14998 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14999 		ipp->ipp_rthdrdstopts = NULL;
15000 		ipp->ipp_rthdrdstoptslen = 0;
15001 	}
15002 	if (fields & IPPF_DSTOPTS) {
15003 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15004 		ipp->ipp_dstopts = NULL;
15005 		ipp->ipp_dstoptslen = 0;
15006 	}
15007 	if (fields & IPPF_RTHDR) {
15008 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15009 		ipp->ipp_rthdr = NULL;
15010 		ipp->ipp_rthdrlen = 0;
15011 	}
15012 	if (fields & IPPF_IPV4_OPTIONS) {
15013 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
15014 		ipp->ipp_ipv4_options = NULL;
15015 		ipp->ipp_ipv4_options_len = 0;
15016 	}
15017 	if (fields & IPPF_LABEL_V4) {
15018 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
15019 		ipp->ipp_label_v4 = NULL;
15020 		ipp->ipp_label_len_v4 = 0;
15021 	}
15022 	if (fields & IPPF_LABEL_V6) {
15023 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
15024 		ipp->ipp_label_v6 = NULL;
15025 		ipp->ipp_label_len_v6 = 0;
15026 	}
15027 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15028 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
15029 }
15030 
15031 /*
15032  * Copy from src to dst and allocate as needed.
15033  * Returns zero or ENOMEM.
15034  *
15035  * The caller must initialize dst to zero.
15036  */
15037 int
15038 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
15039 {
15040 	uint_t	fields = src->ipp_fields;
15041 
15042 	/* Start with fields that don't require memory allocation */
15043 	dst->ipp_fields = fields &
15044 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15045 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
15046 
15047 	dst->ipp_addr = src->ipp_addr;
15048 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
15049 	dst->ipp_hoplimit = src->ipp_hoplimit;
15050 	dst->ipp_tclass = src->ipp_tclass;
15051 	dst->ipp_type_of_service = src->ipp_type_of_service;
15052 
15053 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15054 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
15055 		return (0);
15056 
15057 	if (fields & IPPF_HOPOPTS) {
15058 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
15059 		if (dst->ipp_hopopts == NULL) {
15060 			ip_pkt_free(dst);
15061 			return (ENOMEM);
15062 		}
15063 		dst->ipp_fields |= IPPF_HOPOPTS;
15064 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
15065 		    src->ipp_hopoptslen);
15066 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
15067 	}
15068 	if (fields & IPPF_RTHDRDSTOPTS) {
15069 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
15070 		    kmflag);
15071 		if (dst->ipp_rthdrdstopts == NULL) {
15072 			ip_pkt_free(dst);
15073 			return (ENOMEM);
15074 		}
15075 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
15076 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
15077 		    src->ipp_rthdrdstoptslen);
15078 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
15079 	}
15080 	if (fields & IPPF_DSTOPTS) {
15081 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
15082 		if (dst->ipp_dstopts == NULL) {
15083 			ip_pkt_free(dst);
15084 			return (ENOMEM);
15085 		}
15086 		dst->ipp_fields |= IPPF_DSTOPTS;
15087 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
15088 		    src->ipp_dstoptslen);
15089 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
15090 	}
15091 	if (fields & IPPF_RTHDR) {
15092 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
15093 		if (dst->ipp_rthdr == NULL) {
15094 			ip_pkt_free(dst);
15095 			return (ENOMEM);
15096 		}
15097 		dst->ipp_fields |= IPPF_RTHDR;
15098 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
15099 		    src->ipp_rthdrlen);
15100 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
15101 	}
15102 	if (fields & IPPF_IPV4_OPTIONS) {
15103 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
15104 		    kmflag);
15105 		if (dst->ipp_ipv4_options == NULL) {
15106 			ip_pkt_free(dst);
15107 			return (ENOMEM);
15108 		}
15109 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
15110 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
15111 		    src->ipp_ipv4_options_len);
15112 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
15113 	}
15114 	if (fields & IPPF_LABEL_V4) {
15115 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
15116 		if (dst->ipp_label_v4 == NULL) {
15117 			ip_pkt_free(dst);
15118 			return (ENOMEM);
15119 		}
15120 		dst->ipp_fields |= IPPF_LABEL_V4;
15121 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
15122 		    src->ipp_label_len_v4);
15123 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
15124 	}
15125 	if (fields & IPPF_LABEL_V6) {
15126 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
15127 		if (dst->ipp_label_v6 == NULL) {
15128 			ip_pkt_free(dst);
15129 			return (ENOMEM);
15130 		}
15131 		dst->ipp_fields |= IPPF_LABEL_V6;
15132 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
15133 		    src->ipp_label_len_v6);
15134 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
15135 	}
15136 	if (fields & IPPF_FRAGHDR) {
15137 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
15138 		if (dst->ipp_fraghdr == NULL) {
15139 			ip_pkt_free(dst);
15140 			return (ENOMEM);
15141 		}
15142 		dst->ipp_fields |= IPPF_FRAGHDR;
15143 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
15144 		    src->ipp_fraghdrlen);
15145 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
15146 	}
15147 	return (0);
15148 }
15149 
15150 /*
15151  * Returns INADDR_ANY if no source route
15152  */
15153 ipaddr_t
15154 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
15155 {
15156 	ipaddr_t	nexthop = INADDR_ANY;
15157 	ipoptp_t	opts;
15158 	uchar_t		*opt;
15159 	uint8_t		optval;
15160 	uint8_t		optlen;
15161 	uint32_t	totallen;
15162 
15163 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15164 		return (INADDR_ANY);
15165 
15166 	totallen = ipp->ipp_ipv4_options_len;
15167 	if (totallen & 0x3)
15168 		return (INADDR_ANY);
15169 
15170 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15171 	    optval != IPOPT_EOL;
15172 	    optval = ipoptp_next(&opts)) {
15173 		opt = opts.ipoptp_cur;
15174 		switch (optval) {
15175 			uint8_t off;
15176 		case IPOPT_SSRR:
15177 		case IPOPT_LSRR:
15178 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15179 				break;
15180 			}
15181 			optlen = opts.ipoptp_len;
15182 			off = opt[IPOPT_OFFSET];
15183 			off--;
15184 			if (optlen < IP_ADDR_LEN ||
15185 			    off > optlen - IP_ADDR_LEN) {
15186 				/* End of source route */
15187 				break;
15188 			}
15189 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
15190 			if (nexthop == htonl(INADDR_LOOPBACK)) {
15191 				/* Ignore */
15192 				nexthop = INADDR_ANY;
15193 				break;
15194 			}
15195 			break;
15196 		}
15197 	}
15198 	return (nexthop);
15199 }
15200 
15201 /*
15202  * Reverse a source route.
15203  */
15204 void
15205 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
15206 {
15207 	ipaddr_t	tmp;
15208 	ipoptp_t	opts;
15209 	uchar_t		*opt;
15210 	uint8_t		optval;
15211 	uint32_t	totallen;
15212 
15213 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15214 		return;
15215 
15216 	totallen = ipp->ipp_ipv4_options_len;
15217 	if (totallen & 0x3)
15218 		return;
15219 
15220 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15221 	    optval != IPOPT_EOL;
15222 	    optval = ipoptp_next(&opts)) {
15223 		uint8_t off1, off2;
15224 
15225 		opt = opts.ipoptp_cur;
15226 		switch (optval) {
15227 		case IPOPT_SSRR:
15228 		case IPOPT_LSRR:
15229 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15230 				break;
15231 			}
15232 			off1 = IPOPT_MINOFF_SR - 1;
15233 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15234 			while (off2 > off1) {
15235 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15236 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15237 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15238 				off2 -= IP_ADDR_LEN;
15239 				off1 += IP_ADDR_LEN;
15240 			}
15241 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15242 			break;
15243 		}
15244 	}
15245 }
15246 
15247 /*
15248  * Returns NULL if no routing header
15249  */
15250 in6_addr_t *
15251 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15252 {
15253 	in6_addr_t	*nexthop = NULL;
15254 	ip6_rthdr0_t	*rthdr;
15255 
15256 	if (!(ipp->ipp_fields & IPPF_RTHDR))
15257 		return (NULL);
15258 
15259 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15260 	if (rthdr->ip6r0_segleft == 0)
15261 		return (NULL);
15262 
15263 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15264 	return (nexthop);
15265 }
15266 
15267 zoneid_t
15268 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15269     zoneid_t lookup_zoneid)
15270 {
15271 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15272 	ire_t		*ire;
15273 	int		ire_flags = MATCH_IRE_TYPE;
15274 	zoneid_t	zoneid = ALL_ZONES;
15275 
15276 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15277 		return (ALL_ZONES);
15278 
15279 	if (lookup_zoneid != ALL_ZONES)
15280 		ire_flags |= MATCH_IRE_ZONEONLY;
15281 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15282 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15283 	if (ire != NULL) {
15284 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15285 		ire_refrele(ire);
15286 	}
15287 	return (zoneid);
15288 }
15289 
15290 zoneid_t
15291 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15292     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15293 {
15294 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15295 	ire_t		*ire;
15296 	int		ire_flags = MATCH_IRE_TYPE;
15297 	zoneid_t	zoneid = ALL_ZONES;
15298 
15299 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15300 		return (ALL_ZONES);
15301 
15302 	if (IN6_IS_ADDR_LINKLOCAL(addr))
15303 		ire_flags |= MATCH_IRE_ILL;
15304 
15305 	if (lookup_zoneid != ALL_ZONES)
15306 		ire_flags |= MATCH_IRE_ZONEONLY;
15307 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15308 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15309 	if (ire != NULL) {
15310 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15311 		ire_refrele(ire);
15312 	}
15313 	return (zoneid);
15314 }
15315 
15316 /*
15317  * IP obserability hook support functions.
15318  */
15319 static void
15320 ipobs_init(ip_stack_t *ipst)
15321 {
15322 	netid_t id;
15323 
15324 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15325 
15326 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15327 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15328 
15329 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15330 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15331 }
15332 
15333 static void
15334 ipobs_fini(ip_stack_t *ipst)
15335 {
15336 
15337 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15338 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15339 }
15340 
15341 /*
15342  * hook_pkt_observe_t is composed in network byte order so that the
15343  * entire mblk_t chain handed into hook_run can be used as-is.
15344  * The caveat is that use of the fields, such as the zone fields,
15345  * requires conversion into host byte order first.
15346  */
15347 void
15348 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15349     const ill_t *ill, ip_stack_t *ipst)
15350 {
15351 	hook_pkt_observe_t *hdr;
15352 	uint64_t grifindex;
15353 	mblk_t *imp;
15354 
15355 	imp = allocb(sizeof (*hdr), BPRI_HI);
15356 	if (imp == NULL)
15357 		return;
15358 
15359 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15360 	/*
15361 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15362 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15363 	 */
15364 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15365 	imp->b_cont = mp;
15366 
15367 	ASSERT(DB_TYPE(mp) == M_DATA);
15368 
15369 	if (IS_UNDER_IPMP(ill))
15370 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15371 	else
15372 		grifindex = 0;
15373 
15374 	hdr->hpo_version = 1;
15375 	hdr->hpo_htype = htons(htype);
15376 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15377 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15378 	hdr->hpo_grifindex = htonl(grifindex);
15379 	hdr->hpo_zsrc = htonl(zsrc);
15380 	hdr->hpo_zdst = htonl(zdst);
15381 	hdr->hpo_pkt = imp;
15382 	hdr->hpo_ctx = ipst->ips_netstack;
15383 
15384 	if (ill->ill_isv6) {
15385 		hdr->hpo_family = AF_INET6;
15386 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15387 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15388 	} else {
15389 		hdr->hpo_family = AF_INET;
15390 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15391 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15392 	}
15393 
15394 	imp->b_cont = NULL;
15395 	freemsg(imp);
15396 }
15397 
15398 /*
15399  * Utility routine that checks if `v4srcp' is a valid address on underlying
15400  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15401  * associated with `v4srcp' on success.  NOTE: if this is not called from
15402  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15403  * group during or after this lookup.
15404  */
15405 boolean_t
15406 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15407 {
15408 	ipif_t *ipif;
15409 
15410 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15411 	if (ipif != NULL) {
15412 		if (ipifp != NULL)
15413 			*ipifp = ipif;
15414 		else
15415 			ipif_refrele(ipif);
15416 		return (B_TRUE);
15417 	}
15418 
15419 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15420 	    *v4srcp));
15421 	return (B_FALSE);
15422 }
15423